diff --git a/DEPS b/DEPS index 3a94d35..5aab574 100644 --- a/DEPS +++ b/DEPS
@@ -115,11 +115,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': '15640698497a9d9175828091922d7c57f38093e2', + 'skia_revision': '9cabb4f98e998409612a0227b3f0e7530f853b72', # 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': 'c2ee93406a001b80556c39f66f1a8d00bfcc9517', + 'v8_revision': 'ff281cc41581a8fef2aa62cd542bc3049eb13159', # 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. @@ -127,7 +127,7 @@ # 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': '149eb33bb49faed65a7edb3f5c1d58641fe981c0', + 'angle_revision': 'f5c88e7e1c1aaf0acedb83c174e3d1f121973cda', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling build tools # and whatever else without interference from each other. @@ -139,7 +139,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': '1ccf890a09a33b8e49d92f8f8f565645be82fb6b', + 'pdfium_revision': 'f4f8cc56aacf075306bbb6ee0da845e4f3ae32e3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -175,7 +175,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '60a61e85fed1aa7856f9dda3fe3983b6634404ad', + 'catapult_revision': '74c92bb2207675ea7702153dd1cf60fddefe8495', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -239,7 +239,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': 'a49242766a107c411d744d828a733317ef92dc83', + 'dawn_revision': 'd86edb310a70f1ef054b7e0aa85f0ba1d9031ba2', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -662,7 +662,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '24c806768f5764f99b64315fbfd28172a93870d0', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'bdff670a66b96fba54337abf41106b77036c5066', 'condition': 'checkout_linux', }, @@ -687,7 +687,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '762a25693faf4d7e82a70d1021aebd7d981297ff', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '52411ecf1fa5d12f3ea0a4bb4afa350e92a49b28', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -1019,7 +1019,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'faae590fff1a333b4c7b3d16c93dd6d01c539e02', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '3c2ff12d419d88a817723b6191ae19def4e6e196', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1182,7 +1182,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '5b6cbd789b9b91b4e46dde883c9f2ecb31eddade', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '69540f44196eba13cb7c9046aa838c461eba9029', + Var('webrtc_git') + '/src.git' + '@' + '8f66ddbae3250f71b173f9f5c96c1edf3d4b585f', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d', @@ -1213,7 +1213,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@ddee6ce9c58a72fc2bd4e2da086178c5b468b578', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@757effd70e5f62ab2d6b85623d9fb8643b8b9a82', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index fa3b43e..f14ad2d7 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -621,6 +621,8 @@ "browser/net/input_stream_reader.h", "browser/net_helpers.cc", "browser/net_helpers.h", + "browser/net_network_service/android_stream_reader_url_loader.cc", + "browser/net_network_service/android_stream_reader_url_loader.h", "browser/parent_compositor_draw_constraints.cc", "browser/parent_compositor_draw_constraints.h", "browser/parent_output_surface.cc",
diff --git a/android_webview/browser/DEPS b/android_webview/browser/DEPS index 19b4409..ca1bb07f 100644 --- a/android_webview/browser/DEPS +++ b/android_webview/browser/DEPS
@@ -55,6 +55,10 @@ "+services/network/public", "+services/service_manager/public/cpp", + # network service related unit tests + "+services/network/test", + "+mojo/core/embedder/embedder.h", + "+storage/browser/quota", "+storage/common/quota",
diff --git a/android_webview/browser/deferred_gpu_command_service.cc b/android_webview/browser/deferred_gpu_command_service.cc index ca7382dd..c645f864 100644 --- a/android_webview/browser/deferred_gpu_command_service.cc +++ b/android_webview/browser/deferred_gpu_command_service.cc
@@ -72,10 +72,6 @@ bool ShouldYield() override { return false; } - // Should not be called because BlockThreadOnWaitSyncToken() returns true, - // and the client should not disable sequences to wait for sync tokens. - void SetEnabled(bool enabled) override { NOTREACHED(); } - void ScheduleTask(base::OnceClosure task, std::vector<gpu::SyncToken> sync_token_fences) override { uint32_t order_num = @@ -287,10 +283,6 @@ } } -bool DeferredGpuCommandService::BlockThreadOnWaitSyncToken() const { - return true; -} - bool DeferredGpuCommandService::CanSupportThreadedTextureMailbox() const { return gpu_info_.can_support_threaded_texture_mailbox; }
diff --git a/android_webview/browser/deferred_gpu_command_service.h b/android_webview/browser/deferred_gpu_command_service.h index 27d9cae..0a84ddf 100644 --- a/android_webview/browser/deferred_gpu_command_service.h +++ b/android_webview/browser/deferred_gpu_command_service.h
@@ -49,7 +49,6 @@ // gpu::CommandBufferTaskExecutor implementation. bool ForceVirtualizedGLContexts() const override; bool ShouldCreateMemoryTracker() const override; - bool BlockThreadOnWaitSyncToken() const override; std::unique_ptr<gpu::CommandBufferTaskExecutor::Sequence> CreateSequence() override; void ScheduleOutOfOrderTask(base::OnceClosure task) override;
diff --git a/android_webview/browser/net_network_service/android_stream_reader_url_loader.cc b/android_webview/browser/net_network_service/android_stream_reader_url_loader.cc new file mode 100644 index 0000000..06c8cbca --- /dev/null +++ b/android_webview/browser/net_network_service/android_stream_reader_url_loader.cc
@@ -0,0 +1,242 @@ +// 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 "android_webview/browser/net_network_service/android_stream_reader_url_loader.h" + +#include "android_webview/browser/input_stream.h" +#include "android_webview/browser/net/input_stream_reader.h" +#include "base/callback.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/http/http_status_code.h" +#include "net/http/http_util.h" +#include "services/network/public/cpp/url_loader_completion_status.h" + +namespace android_webview { + +namespace { + +const char kResponseHeaderViaShouldInterceptRequest[] = + "Client-Via: shouldInterceptRequest"; +const char kHTTPOkText[] = "OK"; +const char kHTTPNotFoundText[] = "Not Found"; + +} // namespace + +// In the case when stream reader related tasks are posted on a dedicated +// thread they can outlive the loader. This is a wrapper is for holding both +// InputStream and InputStreamReader to ensure they are still there when the +// task is run. +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); +}; + +class AndroidResponseDelegate + : public AndroidStreamReaderURLLoader::ResponseDelegate { + public: + AndroidResponseDelegate(std::unique_ptr<AwWebResourceResponse> response) + : response_(std::move(response)) {} + std::unique_ptr<android_webview::InputStream> OpenInputStream( + JNIEnv* env) override { + return response_->GetInputStream(env); + } + + private: + std::unique_ptr<AwWebResourceResponse> response_; +}; + +AndroidStreamReaderURLLoader::AndroidStreamReaderURLLoader( + const network::ResourceRequest& resource_request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, + std::unique_ptr<ResponseDelegate> response_delegate) + : resource_request_(resource_request), + client_(std::move(client)), + traffic_annotation_(traffic_annotation), + response_delegate_(std::move(response_delegate)), + weak_factory_(this) { + // If there is a client error, clean up the request. + client_.set_connection_error_handler(base::BindOnce( + &AndroidStreamReaderURLLoader::OnRequestError, weak_factory_.GetWeakPtr(), + network::URLLoaderCompletionStatus(net::ERR_ABORTED))); +} + +AndroidStreamReaderURLLoader::~AndroidStreamReaderURLLoader() {} + +void AndroidStreamReaderURLLoader::FollowRedirect( + const base::Optional<std::vector<std::string>>& + to_be_removed_request_headers, + const base::Optional<net::HttpRequestHeaders>& modified_request_headers, + const base::Optional<GURL>& new_url) {} +void AndroidStreamReaderURLLoader::ProceedWithResponse() {} +void AndroidStreamReaderURLLoader::SetPriority(net::RequestPriority priority, + int intra_priority_value) {} +void AndroidStreamReaderURLLoader::PauseReadingBodyFromNet() {} +void AndroidStreamReaderURLLoader::ResumeReadingBodyFromNet() {} + +void AndroidStreamReaderURLLoader::Start() { + if (!ParseRange(resource_request_.headers)) { + OnRequestError(network::URLLoaderCompletionStatus( + net::ERR_REQUEST_RANGE_NOT_SATISFIABLE)); + return; + } + + JNIEnv* env = base::android::AttachCurrentThread(); + DCHECK(env); + + // TODO(timvolodine): keep the original threading behavior (as in + // AndroidStreamReaderURLRequestJob) and open the stream on a dedicated + // thread. (crbug.com/913524). + std::unique_ptr<InputStream> input_stream = + response_delegate_->OpenInputStream(env); + OnInputStreamOpened(std::move(input_stream)); +} + +void AndroidStreamReaderURLLoader::OnInputStreamOpened( + std::unique_ptr<InputStream> input_stream) { + if (!input_stream) { + // restart not required + HeadersComplete(net::HTTP_NOT_FOUND, kHTTPNotFoundText); + return; + } + + auto input_stream_reader = + std::make_unique<InputStreamReader>(input_stream.get()); + DCHECK(input_stream); + DCHECK(!input_stream_reader_wrapper_); + + input_stream_reader_wrapper_ = base::MakeRefCounted<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(&AndroidStreamReaderURLLoader::OnReaderSeekCompleted, + weak_factory_.GetWeakPtr())); +} + +void AndroidStreamReaderURLLoader::OnReaderSeekCompleted(int result) { + if (result >= 0) { + // we've got the expected content size here + HeadersComplete(net::HTTP_OK, kHTTPOkText); + } else { + OnRequestError(network::URLLoaderCompletionStatus(net::ERR_FAILED)); + } +} + +// TODO(timvolodine): move this to delegate to make this more generic, +// to also support streams other than for shouldInterceptRequest. +void AndroidStreamReaderURLLoader::HeadersComplete( + int status_code, + const std::string& status_text) { + std::string status("HTTP/1.1 "); + status.append(base::IntToString(status_code)); + status.append(" "); + status.append(status_text); + // HttpResponseHeaders expects its input string to be terminated by two NULs. + status.append("\0\0", 2); + + network::ResourceResponseHead head; + head.request_start = base::TimeTicks::Now(); + head.response_start = base::TimeTicks::Now(); + head.headers = new net::HttpResponseHeaders(status); + + // TODO(timvolodine): add content length header + // TODO(timvolodine): add proper mime information + + // Indicate that the response had been obtained via shouldInterceptRequest. + head.headers->AddHeader(kResponseHeaderViaShouldInterceptRequest); + + DCHECK(client_.is_bound()); + client_->OnReceiveResponse(head); + + if (status_code != net::HTTP_OK) { + OnRequestError(network::URLLoaderCompletionStatus(net::ERR_FAILED)); + return; + } + + SendBody(); +} + +void AndroidStreamReaderURLLoader::SendBody() { + // TODO(timvolodine): implement IOBuffer stream -> mojo pipes here + mojo::ScopedDataPipeConsumerHandle body_to_send; + client_->OnStartLoadingResponseBody(std::move(body_to_send)); + RequestComplete(network::URLLoaderCompletionStatus(net::OK)); +} + +void AndroidStreamReaderURLLoader::RequestComplete( + const network::URLLoaderCompletionStatus& status) { + if (status.error_code != net::OK) { + OnRequestError(status); + return; + } + client_->OnComplete(status); + + // Manages its own lifetime + delete this; +} + +void AndroidStreamReaderURLLoader::OnRequestError( + const network::URLLoaderCompletionStatus& status) { + client_->OnComplete(status); + + // Manages it's own lifetime + delete this; +} + +// TODO(timvolodine): consider moving this to the net_helpers.cc +bool AndroidStreamReaderURLLoader::ParseRange( + const net::HttpRequestHeaders& headers) { + std::string range_header; + if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) { + // This loader 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. + std::vector<net::HttpByteRange> ranges; + if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) { + // In case of multi-range request only use the first range. + // We don't support multirange requests. + if (ranges.size() == 1) + byte_range_ = ranges[0]; + } else { + // This happens if the range header could not be parsed or is invalid. + return false; + } + } + return true; +} + +} // namespace android_webview
diff --git a/android_webview/browser/net_network_service/android_stream_reader_url_loader.h b/android_webview/browser/net_network_service/android_stream_reader_url_loader.h new file mode 100644 index 0000000..4cfde36 --- /dev/null +++ b/android_webview/browser/net_network_service/android_stream_reader_url_loader.h
@@ -0,0 +1,76 @@ +// 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 ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_ +#define ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_ + +#include "android_webview/browser/net/aw_web_resource_response.h" +#include "net/http/http_byte_range.h" +#include "services/network/public/mojom/url_loader.mojom.h" + +namespace android_webview { + +class InputStream; +class InputStreamReaderWrapper; + +// Custom URLLoader implementation for loading network responses from stream. +// Current implementation is in particular for supporting shouldInterceptRequest +// callback in webview. +class AndroidStreamReaderURLLoader : public network::mojom::URLLoader { + public: + // Delegate abstraction for obtaining input streams. + // TODO(timvolodine): add other methods to this delegate + class ResponseDelegate { + public: + virtual ~ResponseDelegate() {} + virtual std::unique_ptr<android_webview::InputStream> OpenInputStream( + JNIEnv* env) = 0; + }; + + AndroidStreamReaderURLLoader( + const network::ResourceRequest& resource_request, + network::mojom::URLLoaderClientPtr client, + const net::MutableNetworkTrafficAnnotationTag& traffic_annotation, + std::unique_ptr<ResponseDelegate> response_delegate); + ~AndroidStreamReaderURLLoader() override; + + void Start(); + + // network::mojom::URLLoader overrides: + void FollowRedirect( + const base::Optional<std::vector<std::string>>& + to_be_removed_request_headers, + const base::Optional<net::HttpRequestHeaders>& modified_request_headers, + const base::Optional<GURL>& new_url) override; + void ProceedWithResponse() override; + void SetPriority(net::RequestPriority priority, + int intra_priority_value) override; + void PauseReadingBodyFromNet() override; + void ResumeReadingBodyFromNet() override; + + private: + bool ParseRange(const net::HttpRequestHeaders& headers); + void OnInputStreamOpened( + std::unique_ptr<android_webview::InputStream> input_stream); + void OnReaderSeekCompleted(int result); + void HeadersComplete(int status_code, const std::string& status_text); + void RequestComplete(const network::URLLoaderCompletionStatus& status); + void SendBody(); + void OnRequestError(const network::URLLoaderCompletionStatus& status); + + net::HttpByteRange byte_range_; + network::ResourceRequest resource_request_; + network::mojom::URLLoaderClientPtr client_; + const net::MutableNetworkTrafficAnnotationTag traffic_annotation_; + std::unique_ptr<ResponseDelegate> response_delegate_; + scoped_refptr<InputStreamReaderWrapper> input_stream_reader_wrapper_; + + base::WeakPtrFactory<AndroidStreamReaderURLLoader> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(AndroidStreamReaderURLLoader); +}; + +} // namespace android_webview + +#endif
diff --git a/android_webview/browser/net_network_service/android_stream_reader_url_loader_unittest.cc b/android_webview/browser/net_network_service/android_stream_reader_url_loader_unittest.cc new file mode 100644 index 0000000..f2a2b2f5d --- /dev/null +++ b/android_webview/browser/net_network_service/android_stream_reader_url_loader_unittest.cc
@@ -0,0 +1,170 @@ +// 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 "android_webview/browser/net_network_service/android_stream_reader_url_loader.h" + +#include "android_webview/browser/input_stream.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/scoped_task_environment.h" +#include "content/public/common/resource_type.h" +#include "mojo/core/embedder/embedder.h" +#include "net/http/http_request_headers.h" +#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" +#include "services/network/public/cpp/features.h" +#include "services/network/test/test_url_loader_client.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace android_webview { + +// Always succeeds +class FakeInputStream : public InputStream { + public: + FakeInputStream() {} + ~FakeInputStream() override {} + bool BytesAvailable(int* bytes_available) const override { return true; } + bool Skip(int64_t n, int64_t* bytes_skipped) override { + *bytes_skipped = n; + return true; + } + bool Read(net::IOBuffer* dest, int length, int* bytes_read) override { + return true; + } +}; + +// Stream that always fails +class FakeFailingInputStream : public InputStream { + public: + FakeFailingInputStream() {} + ~FakeFailingInputStream() override {} + bool BytesAvailable(int* bytes_available) const override { return false; } + bool Skip(int64_t n, int64_t* bytes_skipped) override { return false; } + bool Read(net::IOBuffer* dest, int length, int* bytes_read) override { + return false; + } +}; + +class TestResponseDelegate + : public AndroidStreamReaderURLLoader::ResponseDelegate { + public: + TestResponseDelegate(std::unique_ptr<InputStream> input_stream) + : input_stream_(std::move(input_stream)) {} + ~TestResponseDelegate() override {} + + std::unique_ptr<android_webview::InputStream> OpenInputStream( + JNIEnv* env) override { + return std::move(input_stream_); + } + + private: + std::unique_ptr<InputStream> input_stream_; +}; + +class AndroidStreamReaderURLLoaderTest : public ::testing::Test { + protected: + AndroidStreamReaderURLLoaderTest() {} + ~AndroidStreamReaderURLLoaderTest() override = default; + + void SetUp() override { + mojo::core::Init(); + feature_list_.InitAndEnableFeature(network::features::kNetworkService); + } + + network::ResourceRequest CreateRequest(const GURL& url) { + network::ResourceRequest request; + request.url = url; + request.method = "GET"; + request.resource_type = content::RESOURCE_TYPE_SUB_RESOURCE; + return request; + } + + // helper method for creating loaders given a stream + AndroidStreamReaderURLLoader* CreateLoader( + const network::ResourceRequest& request, + network::TestURLLoaderClient* client, + std::unique_ptr<InputStream> input_stream) { + return new AndroidStreamReaderURLLoader( + request, client->CreateInterfacePtr(), + net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS), + std::make_unique<TestResponseDelegate>(std::move(input_stream))); + } + + base::test::ScopedFeatureList feature_list_; + base::test::ScopedTaskEnvironment scoped_task_environment_; + + DISALLOW_COPY_AND_ASSIGN(AndroidStreamReaderURLLoaderTest); +}; + +TEST_F(AndroidStreamReaderURLLoaderTest, ReadFakeStream) { + network::ResourceRequest request = + CreateRequest(GURL("https://www.example.com/")); + std::unique_ptr<network::TestURLLoaderClient> client = + std::make_unique<network::TestURLLoaderClient>(); + AndroidStreamReaderURLLoader* loader = + CreateLoader(request, client.get(), std::make_unique<FakeInputStream>()); + loader->Start(); + client->RunUntilComplete(); + EXPECT_EQ(net::OK, client->completion_status().error_code); + EXPECT_EQ("HTTP/1.1 200 OK", + client->response_head().headers->GetStatusLine()); +} + +TEST_F(AndroidStreamReaderURLLoaderTest, ReadFailingStream) { + network::ResourceRequest request = + CreateRequest(GURL("https://www.example.com/")); + std::unique_ptr<network::TestURLLoaderClient> client = + std::make_unique<network::TestURLLoaderClient>(); + AndroidStreamReaderURLLoader* loader = CreateLoader( + request, client.get(), std::make_unique<FakeFailingInputStream>()); + loader->Start(); + client->RunUntilComplete(); + EXPECT_EQ(net::ERR_FAILED, client->completion_status().error_code); +} + +TEST_F(AndroidStreamReaderURLLoaderTest, ValidRangeRequest) { + network::ResourceRequest request = + CreateRequest(GURL("https://www.example.com/")); + request.headers.SetHeader(net::HttpRequestHeaders::kRange, "bytes=10-200"); + + std::unique_ptr<network::TestURLLoaderClient> client = + std::make_unique<network::TestURLLoaderClient>(); + AndroidStreamReaderURLLoader* loader = + CreateLoader(request, client.get(), std::make_unique<FakeInputStream>()); + loader->Start(); + client->RunUntilComplete(); + EXPECT_EQ(net::OK, client->completion_status().error_code); + EXPECT_EQ("HTTP/1.1 200 OK", + client->response_head().headers->GetStatusLine()); +} + +TEST_F(AndroidStreamReaderURLLoaderTest, InvalidRangeRequest) { + network::ResourceRequest request = + CreateRequest(GURL("https://www.example.com/")); + request.headers.SetHeader(net::HttpRequestHeaders::kRange, "bytes=10-0"); + + std::unique_ptr<network::TestURLLoaderClient> client = + std::make_unique<network::TestURLLoaderClient>(); + AndroidStreamReaderURLLoader* loader = + CreateLoader(request, client.get(), std::make_unique<FakeInputStream>()); + loader->Start(); + client->RunUntilComplete(); + EXPECT_EQ(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE, + client->completion_status().error_code); +} + +TEST_F(AndroidStreamReaderURLLoaderTest, NullInputStream) { + network::ResourceRequest request = + CreateRequest(GURL("https://www.example.com/")); + + std::unique_ptr<network::TestURLLoaderClient> client = + std::make_unique<network::TestURLLoaderClient>(); + AndroidStreamReaderURLLoader* loader = + CreateLoader(request, client.get(), nullptr); + loader->Start(); + client->RunUntilComplete(); + EXPECT_EQ(net::ERR_FAILED, client->completion_status().error_code); + EXPECT_EQ("HTTP/1.1 404 Not Found", + client->response_head().headers->GetStatusLine()); +} + +} // namespace android_webview
diff --git a/android_webview/common/aw_content_client.cc b/android_webview/common/aw_content_client.cc index 32e9a15..8831cc76 100644 --- a/android_webview/common/aw_content_client.cc +++ b/android_webview/common/aw_content_client.cc
@@ -47,6 +47,12 @@ resource_id, scale_factor); } +base::RefCountedMemory* AwContentClient::GetDataResourceBytes( + int resource_id) const { + return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( + resource_id); +} + bool AwContentClient::CanSendWhileSwappedOut(const IPC::Message* message) { // For legacy API support we perform a few browser -> renderer synchronous IPC // messages that block the browser. However, the synchronous IPC replies might
diff --git a/android_webview/common/aw_content_client.h b/android_webview/common/aw_content_client.h index c6a1c651..f46f756a 100644 --- a/android_webview/common/aw_content_client.h +++ b/android_webview/common/aw_content_client.h
@@ -23,6 +23,7 @@ base::StringPiece GetDataResource( int resource_id, ui::ScaleFactor scale_factor) const override; + base::RefCountedMemory* GetDataResourceBytes(int resource_id) const override; bool CanSendWhileSwappedOut(const IPC::Message* message) override; void SetGpuInfo(const gpu::GPUInfo& gpu_info) override; bool UsingSynchronousCompositing() override;
diff --git a/android_webview/renderer/aw_render_frame_ext.cc b/android_webview/renderer/aw_render_frame_ext.cc index d2fc7c5..479e74d94 100644 --- a/android_webview/renderer/aw_render_frame_ext.cc +++ b/android_webview/renderer/aw_render_frame_ext.cc
@@ -79,8 +79,9 @@ if (spec.starts_with(prefix)) { url::RawCanonOutputW<1024> output; - url::DecodeURLEscapeSequences(spec.data() + prefix.length(), - spec.length() - prefix.length(), &output); + url::DecodeURLEscapeSequences( + spec.data() + prefix.length(), spec.length() - prefix.length(), + url::DecodeURLMode::kUTF8OrIsomorphic, &output); *dest = base::UTF16ToUTF8(base::StringPiece16(output.data(), output.length())); return true;
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 614eb99..9891932 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -345,6 +345,7 @@ "../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/net_network_service/android_stream_reader_url_loader_unittest.cc", "../browser/permission/media_access_permission_request_unittest.cc", "../browser/permission/permission_request_handler_unittest.cc", "../browser/renderer_host/auto_login_parser_unittest.cc",
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 517068d0..6d8c12d 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -7,7 +7,7 @@ import("//chromeos/assistant/assistant.gni") import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") import("//tools/grit/repack.gni") @@ -174,6 +174,9 @@ "assistant/assistant_setup_controller.h", "assistant/assistant_ui_controller.cc", "assistant/assistant_ui_controller.h", + "assistant/model/assistant_alarm_timer_model.cc", + "assistant/model/assistant_alarm_timer_model.h", + "assistant/model/assistant_alarm_timer_model_observer.h", "assistant/model/assistant_cache_model.cc", "assistant/model/assistant_cache_model.h", "assistant/model/assistant_cache_model_observer.h", @@ -2319,7 +2322,7 @@ ] } -service("ash_service") { +service_executable("ash_service") { output_name = "ash" sources = [
diff --git a/ash/assistant/assistant_alarm_timer_controller.cc b/ash/assistant/assistant_alarm_timer_controller.cc index c949222..145b698 100644 --- a/ash/assistant/assistant_alarm_timer_controller.cc +++ b/ash/assistant/assistant_alarm_timer_controller.cc
@@ -16,15 +16,23 @@ namespace { -constexpr char kTimerFireNotificationGroupId[] = "assistant/timer_fire"; +// Grouping key for timer notifications. +constexpr char kTimerNotificationGroupingKey[] = "assistant/timer"; + +// Interval at which alarms/timers are ticked. +constexpr base::TimeDelta kTickInterval = base::TimeDelta::FromSeconds(1); } // namespace AssistantAlarmTimerController::AssistantAlarmTimerController( AssistantController* assistant_controller) - : assistant_controller_(assistant_controller), binding_(this) {} + : assistant_controller_(assistant_controller), binding_(this) { + AddModelObserver(this); +} -AssistantAlarmTimerController::~AssistantAlarmTimerController() = default; +AssistantAlarmTimerController::~AssistantAlarmTimerController() { + RemoveModelObserver(this); +} void AssistantAlarmTimerController::BindRequest( mojom::AssistantAlarmTimerControllerRequest request) { @@ -32,13 +40,41 @@ binding_.Bind(std::move(request)); } -// TODO(dmblack): Abstract this out into a model that tracks timer state so that -// we can observe it to either add a system notification or an in-Assistant -// notification depending on UI visibility state. These notifications will need -// to be updated in sync with clock ticks until the notification is dismissed. +void AssistantAlarmTimerController::AddModelObserver( + AssistantAlarmTimerModelObserver* observer) { + model_.AddObserver(observer); +} + +void AssistantAlarmTimerController::RemoveModelObserver( + AssistantAlarmTimerModelObserver* observer) { + model_.RemoveObserver(observer); +} + +// TODO(dmblack): Remove method when the LibAssistant Alarm/Timer API is ready. void AssistantAlarmTimerController::OnTimerSoundingStarted() { - // TODO(llin): Migrate to use the AlarmManager API to better support multiple - // timers when the API is available. + static constexpr char kIdPrefix[] = "assistant/timer"; + + AlarmTimer timer; + timer.id = kIdPrefix + std::to_string(next_timer_id_++); + timer.type = AlarmTimerType::kTimer; + timer.end_time = base::TimeTicks::Now(); + model_.AddAlarmTimer(timer); +} + +// TODO(dmblack): Remove method when the LibAssistant Alarm/Timer API is ready. +void AssistantAlarmTimerController::OnTimerSoundingFinished() { + model_.RemoveAllAlarmsTimers(); +} + +void AssistantAlarmTimerController::OnAlarmTimerAdded( + const AlarmTimer& alarm_timer, + const base::TimeDelta& time_remaining) { + // Schedule a repeating timer to tick the tracked alarms/timers. + if (!timer_.IsRunning()) { + timer_.Start(FROM_HERE, kTickInterval, &model_, + &AssistantAlarmTimerModel::Tick); + } + const std::string title = l10n_util::GetStringUTF8(IDS_ASSISTANT_TIMER_NOTIFICATION_TITLE); const std::string message = @@ -52,7 +88,7 @@ notification->title = title; notification->message = message; notification->action_url = action_url; - notification->grouping_key = kTimerFireNotificationGroupId; + notification->grouping_key = kTimerNotificationGroupingKey; // "STOP" button. notification->buttons.push_back( @@ -70,13 +106,17 @@ l10n_util::GetStringUTF8( IDS_ASSISTANT_TIMER_NOTIFICATION_ADD_1_MIN_QUERY)))); + DCHECK(chromeos::assistant::features::IsTimerNotificationEnabled()); assistant_controller_->notification_controller()->OnShowNotification( std::move(notification)); } -void AssistantAlarmTimerController::OnTimerSoundingFinished() { +void AssistantAlarmTimerController::OnAllAlarmsTimersRemoved() { + timer_.Stop(); + + DCHECK(chromeos::assistant::features::IsTimerNotificationEnabled()); assistant_controller_->notification_controller()->OnRemoveNotification( - kTimerFireNotificationGroupId); + kTimerNotificationGroupingKey); } } // namespace ash
diff --git a/ash/assistant/assistant_alarm_timer_controller.h b/ash/assistant/assistant_alarm_timer_controller.h index 63a30f8..abe601c 100644 --- a/ash/assistant/assistant_alarm_timer_controller.h +++ b/ash/assistant/assistant_alarm_timer_controller.h
@@ -5,8 +5,11 @@ #ifndef ASH_ASSISTANT_ASSISTANT_ALARM_TIMER_CONTROLLER_H_ #define ASH_ASSISTANT_ASSISTANT_ALARM_TIMER_CONTROLLER_H_ +#include "ash/assistant/model/assistant_alarm_timer_model.h" +#include "ash/assistant/model/assistant_alarm_timer_model_observer.h" #include "ash/public/interfaces/assistant_controller.mojom.h" #include "base/macros.h" +#include "base/timer/timer.h" #include "mojo/public/cpp/bindings/binding.h" namespace ash { @@ -16,7 +19,8 @@ // The AssistantAlarmTimerController is a sub-controller of AssistantController // tasked with tracking alarm/timer state and providing alarm/timer APIs. class AssistantAlarmTimerController - : public mojom::AssistantAlarmTimerController { + : public mojom::AssistantAlarmTimerController, + public AssistantAlarmTimerModelObserver { public: explicit AssistantAlarmTimerController( AssistantController* assistant_controller); @@ -24,15 +28,33 @@ void BindRequest(mojom::AssistantAlarmTimerControllerRequest request); + // Returns the underlying model. + const AssistantAlarmTimerModel* model() const { return &model_; } + + // Adds/removes the specified model |observer|. + void AddModelObserver(AssistantAlarmTimerModelObserver* observer); + void RemoveModelObserver(AssistantAlarmTimerModelObserver* observer); + // mojom::AssistantAlarmTimerController: void OnTimerSoundingStarted() override; void OnTimerSoundingFinished() override; + // AssistantAlarmTimerModelObserver: + void OnAlarmTimerAdded(const AlarmTimer& alarm_timer, + const base::TimeDelta& time_remaining) override; + void OnAllAlarmsTimersRemoved() override; + private: AssistantController* const assistant_controller_; // Owned by Shell. mojo::Binding<mojom::AssistantAlarmTimerController> binding_; + AssistantAlarmTimerModel model_; + + base::RepeatingTimer timer_; + + int next_timer_id_ = 1; + DISALLOW_COPY_AND_ASSIGN(AssistantAlarmTimerController); };
diff --git a/ash/assistant/model/assistant_alarm_timer_model.cc b/ash/assistant/model/assistant_alarm_timer_model.cc new file mode 100644 index 0000000..bfa6403 --- /dev/null +++ b/ash/assistant/model/assistant_alarm_timer_model.cc
@@ -0,0 +1,70 @@ +// 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 "ash/assistant/model/assistant_alarm_timer_model.h" + +#include "ash/assistant/model/assistant_alarm_timer_model_observer.h" +#include "base/stl_util.h" + +namespace ash { + +AssistantAlarmTimerModel::AssistantAlarmTimerModel() = default; + +AssistantAlarmTimerModel::~AssistantAlarmTimerModel() = default; + +void AssistantAlarmTimerModel::AddObserver( + AssistantAlarmTimerModelObserver* observer) { + observers_.AddObserver(observer); +} + +void AssistantAlarmTimerModel::RemoveObserver( + AssistantAlarmTimerModelObserver* observer) { + observers_.RemoveObserver(observer); +} + +void AssistantAlarmTimerModel::AddAlarmTimer(const AlarmTimer& alarm_timer) { + DCHECK(!base::ContainsKey(alarms_timers_, alarm_timer.id)); + alarms_timers_[alarm_timer.id] = alarm_timer; + NotifyAlarmTimerAdded(alarm_timer, /*time_remaining=*/base::TimeTicks::Now() - + alarm_timer.end_time); +} + +void AssistantAlarmTimerModel::RemoveAllAlarmsTimers() { + if (alarms_timers_.empty()) + return; + + alarms_timers_.clear(); + NotifyAllAlarmsTimersRemoved(); +} + +void AssistantAlarmTimerModel::Tick() { + const base::TimeTicks now = base::TimeTicks::Now(); + + // Calculate remaining time for all tracked alarms/timers. + std::map<std::string, base::TimeDelta> times_remaining; + for (auto& alarm_timer : alarms_timers_) + times_remaining[alarm_timer.first] = now - alarm_timer.second.end_time; + + NotifyAlarmsTimersTicked(times_remaining); +} + +void AssistantAlarmTimerModel::NotifyAlarmTimerAdded( + const AlarmTimer& alarm_timer, + const base::TimeDelta& time_remaining) { + for (auto& observer : observers_) + observer.OnAlarmTimerAdded(alarm_timer, time_remaining); +} + +void AssistantAlarmTimerModel::NotifyAlarmsTimersTicked( + const std::map<std::string, base::TimeDelta>& times_remaining) { + for (auto& observer : observers_) + observer.OnAlarmsTimersTicked(times_remaining); +} + +void AssistantAlarmTimerModel::NotifyAllAlarmsTimersRemoved() { + for (auto& observer : observers_) + observer.OnAllAlarmsTimersRemoved(); +} + +} // namespace ash
diff --git a/ash/assistant/model/assistant_alarm_timer_model.h b/ash/assistant/model/assistant_alarm_timer_model.h new file mode 100644 index 0000000..bf2e064 --- /dev/null +++ b/ash/assistant/model/assistant_alarm_timer_model.h
@@ -0,0 +1,65 @@ +// 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 ASH_ASSISTANT_MODEL_ASSISTANT_ALARM_TIMER_MODEL_H_ +#define ASH_ASSISTANT_MODEL_ASSISTANT_ALARM_TIMER_MODEL_H_ + +#include <map> +#include <string> + +#include "base/macros.h" +#include "base/observer_list.h" + +namespace ash { + +class AssistantAlarmTimerModelObserver; + +enum class AlarmTimerType { + kAlarm, + kTimer, +}; + +struct AlarmTimer { + std::string id; + AlarmTimerType type; + base::TimeTicks end_time; +}; + +// The model belonging to AssistantAlarmTimerController which tracks alarm/timer +// state and notifies a pool of observers. +class AssistantAlarmTimerModel { + public: + AssistantAlarmTimerModel(); + ~AssistantAlarmTimerModel(); + + // Adds/removes the specified alarm/timer model |observer|. + void AddObserver(AssistantAlarmTimerModelObserver* observer); + void RemoveObserver(AssistantAlarmTimerModelObserver* observer); + + // Adds the specified alarm/timer to the model. + void AddAlarmTimer(const AlarmTimer& alarm_timer); + + // Remove all alarms/timers from the model. + void RemoveAllAlarmsTimers(); + + // Invoke to tick any alarms/timers and to notify observers of time remaining. + void Tick(); + + private: + void NotifyAlarmTimerAdded(const AlarmTimer& alarm_timer, + const base::TimeDelta& time_remaining); + void NotifyAlarmsTimersTicked( + const std::map<std::string, base::TimeDelta>& times_remaining); + void NotifyAllAlarmsTimersRemoved(); + + std::map<std::string, AlarmTimer> alarms_timers_; + + base::ObserverList<AssistantAlarmTimerModelObserver> observers_; + + DISALLOW_COPY_AND_ASSIGN(AssistantAlarmTimerModel); +}; + +} // namespace ash + +#endif // ASH_ASSISTANT_MODEL_ASSISTANT_ALARM_TIMER_MODEL_H_
diff --git a/ash/assistant/model/assistant_alarm_timer_model_observer.h b/ash/assistant/model/assistant_alarm_timer_model_observer.h new file mode 100644 index 0000000..d586304 --- /dev/null +++ b/ash/assistant/model/assistant_alarm_timer_model_observer.h
@@ -0,0 +1,43 @@ +// 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 ASH_ASSISTANT_MODEL_ASSISTANT_ALARM_TIMER_MODEL_OBSERVER_H_ +#define ASH_ASSISTANT_MODEL_ASSISTANT_ALARM_TIMER_MODEL_OBSERVER_H_ + +#include <map> +#include <string> + +#include "base/observer_list_types.h" + +namespace base { +class TimeDelta; +} // namespace base + +namespace ash { + +struct AlarmTimer; + +// A checked observer which receives notification of changes to the Assistant +// alarm/timer model. +class AssistantAlarmTimerModelObserver : public base::CheckedObserver { + public: + // Invoked when the specified alarm/timer has been added. + virtual void OnAlarmTimerAdded(const AlarmTimer& alarm_timer, + const base::TimeDelta& time_remaining) {} + + // Invoked when the alarms/timers associated with the given ids have ticked + // with the specified time remaining. + virtual void OnAlarmsTimersTicked( + const std::map<std::string, base::TimeDelta>& times_remaining) {} + + // Invoked when all alarms/timers have been removed. + virtual void OnAllAlarmsTimersRemoved() {} + + protected: + ~AssistantAlarmTimerModelObserver() override = default; +}; + +} // namespace ash + +#endif // ASH_ASSISTANT_MODEL_ASSISTANT_ALARM_TIMER_MODEL_OBSERVER_H_
diff --git a/ash/components/quick_launch/BUILD.gn b/ash/components/quick_launch/BUILD.gn index e504924..f8f4b0f 100644 --- a/ash/components/quick_launch/BUILD.gn +++ b/ash/components/quick_launch/BUILD.gn
@@ -3,9 +3,9 @@ # found in the LICENSE file. import("//build/config/ui.gni") -import("//services/service_manager/public/cpp/service.gni") -import("//services/service_manager/public/service_manifest.gni") import("//mojo/public/tools/bindings/mojom.gni") +import("//services/service_manager/public/cpp/service_executable.gni") +import("//services/service_manager/public/service_manifest.gni") import("//tools/grit/repack.gni") source_set("lib") { @@ -28,7 +28,7 @@ ] } -service("quick_launch_app") { +service_executable("quick_launch_app") { sources = [ "main.cc", ]
diff --git a/ash/components/quick_launch/main.cc b/ash/components/quick_launch/main.cc index d3b21b47..ea494d4 100644 --- a/ash/components/quick_launch/main.cc +++ b/ash/components/quick_launch/main.cc
@@ -4,7 +4,7 @@ #include "ash/components/quick_launch/quick_launch_application.h" #include "base/message_loop/message_loop.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/ash/public/cpp/ash_features.cc b/ash/public/cpp/ash_features.cc index 3588974..99b4277 100644 --- a/ash/public/cpp/ash_features.cc +++ b/ash/public/cpp/ash_features.cc
@@ -23,7 +23,7 @@ "KeyboardShortcutViewerApp", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kLockScreenNotifications{"LockScreenNotifications", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kLockScreenInlineReply{"LockScreenInlineReply", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ash/system/message_center/unified_message_center_view_unittest.cc b/ash/system/message_center/unified_message_center_view_unittest.cc index 3f328eab..0a37287 100644 --- a/ash/system/message_center/unified_message_center_view_unittest.cc +++ b/ash/system/message_center/unified_message_center_view_unittest.cc
@@ -4,6 +4,7 @@ #include "ash/system/message_center/unified_message_center_view.h" +#include "ash/public/cpp/ash_features.h" #include "ash/system/message_center/message_center_scroll_bar.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/unified/unified_system_tray_controller.h" @@ -194,6 +195,11 @@ } TEST_F(UnifiedMessageCenterViewTest, NotVisibleWhenLocked) { + // Skip the test if the lock screen notification is enabled. + // TODO(yoshiki): Clean up after the feature is launched crbug.com/913764. + if (features::IsLockScreenNotificationsEnabled()) + return; + AddNotification(); AddNotification(); @@ -203,6 +209,21 @@ EXPECT_FALSE(message_center_view()->visible()); } +TEST_F(UnifiedMessageCenterViewTest, VisibleWhenLocked) { + // Skip the test if the lock screen notification is disabled. + // TODO(yoshiki): Clean up after the feature is launched crbug.com/913764. + if (!features::IsLockScreenNotificationsEnabled()) + return; + + AddNotification(); + AddNotification(); + + BlockUserSession(BLOCKED_BY_LOCK_SCREEN); + CreateMessageCenterView(); + + EXPECT_TRUE(message_center_view()->visible()); +} + TEST_F(UnifiedMessageCenterViewTest, ClearAllPressed) { AddNotification(); AddNotification();
diff --git a/base/containers/hash_tables.h b/base/containers/hash_tables.h index 8da7b67..164a4ab5 100644 --- a/base/containers/hash_tables.h +++ b/base/containers/hash_tables.h
@@ -48,21 +48,6 @@ class Alloc = std::allocator<std::pair<const Key, T>>> using hash_map = std::unordered_map<Key, T, Hash, Pred, Alloc>; -// Use std::unordered_multimap instead. -template <class Key, - class T, - class Hash = BASE_HASH_NAMESPACE::hash<Key>, - class Pred = std::equal_to<Key>, - class Alloc = std::allocator<std::pair<const Key, T>>> -using hash_multimap = std::unordered_multimap<Key, T, Hash, Pred, Alloc>; - -// Use std::unordered_multiset instead. -template <class Key, - class Hash = BASE_HASH_NAMESPACE::hash<Key>, - class Pred = std::equal_to<Key>, - class Alloc = std::allocator<Key>> -using hash_multiset = std::unordered_multiset<Key, Hash, Pred, Alloc>; - // Use std::unordered_set instead. template <class Key, class Hash = BASE_HASH_NAMESPACE::hash<Key>,
diff --git a/base/task/sequence_manager/sequence_manager_impl_unittest.cc b/base/task/sequence_manager/sequence_manager_impl_unittest.cc index a1ddabd..d85ecd3 100644 --- a/base/task/sequence_manager/sequence_manager_impl_unittest.cc +++ b/base/task/sequence_manager/sequence_manager_impl_unittest.cc
@@ -2852,6 +2852,43 @@ EXPECT_EQ(0u, queues_[0]->GetNumberOfPendingTasks()); } +TEST_P(SequenceManagerTest, SweepCanceledDelayedTasks_ManyTasks) { + CreateTaskQueues(1u); + + TimeTicks start_time = manager_->NowTicks(); + + constexpr const int kNumTasks = 100; + + std::vector<std::unique_ptr<CancelableTask>> tasks(100); + std::vector<TimeTicks> run_times; + for (int i = 0; i < kNumTasks; i++) { + tasks[i] = std::make_unique<CancelableTask>(GetTickClock()); + queues_[0]->task_runner()->PostDelayedTask( + FROM_HERE, + BindOnce(&CancelableTask::RecordTimeTask, + tasks[i]->weak_factory_.GetWeakPtr(), &run_times), + TimeDelta::FromSeconds(i + 1)); + } + + // Invalidate ever other timer. + for (int i = 0; i < kNumTasks; i++) { + if (i % 2) + tasks[i]->weak_factory_.InvalidateWeakPtrs(); + } + + manager_->ReclaimMemory(); + EXPECT_EQ(50u, queues_[0]->GetNumberOfPendingTasks()); + + // Make sure the priority queue still operates as expected. + test_task_runner_->FastForwardUntilNoTasksRemain(); + ASSERT_EQ(50u, run_times.size()); + for (int i = 0; i < 50; i++) { + TimeTicks expected_run_time = + start_time + TimeDelta::FromSeconds(2 * i + 1); + EXPECT_EQ(run_times[i], expected_run_time); + } +} + TEST_P(SequenceManagerTest, DelayTillNextTask) { CreateTaskQueues(2u);
diff --git a/base/task/sequence_manager/task_queue_impl.cc b/base/task/sequence_manager/task_queue_impl.cc index 17c3335..f0031c3 100644 --- a/base/task/sequence_manager/task_queue_impl.cc +++ b/base/task/sequence_manager/task_queue_impl.cc
@@ -139,9 +139,8 @@ // order inversion for tasks that are posted from within a lock, with a // destructor that acquires the same lock. - std::priority_queue<Task> delayed_incoming_queue = - main_thread_only().delayed_incoming_queue.TakeTasks(); - + DelayedIncomingQueue delayed_incoming_queue; + delayed_incoming_queue.swap(&main_thread_only().delayed_incoming_queue); std::unique_ptr<WorkQueue> immediate_work_queue = std::move(main_thread_only().immediate_work_queue); std::unique_ptr<WorkQueue> delayed_work_queue = @@ -737,23 +736,6 @@ } // static -void TaskQueueImpl::QueueAsValueInto(const std::priority_queue<Task>& queue, - TimeTicks now, - trace_event::TracedValue* state) { - // Remove const to search |queue| in the destructive manner. Restore the - // content from |visited| later. - std::priority_queue<Task>* mutable_queue = - const_cast<std::priority_queue<Task>*>(&queue); - std::priority_queue<Task> visited; - while (!mutable_queue->empty()) { - TaskAsValueInto(mutable_queue->top(), now, state); - visited.push(std::move(const_cast<Task&>(mutable_queue->top()))); - mutable_queue->pop(); - } - *mutable_queue = std::move(visited); -} - -// static void TaskQueueImpl::TaskAsValueInto(const Task& task, TimeTicks now, trace_event::TracedValue* state) { @@ -1012,7 +994,7 @@ main_thread_only().immediate_work_queue->DeletePendingTasks(); // TODO(altimin): Add clear() method to DelayedIncomingQueue. DelayedIncomingQueue queue_to_delete; - main_thread_only().delayed_incoming_queue.swap(queue_to_delete); + main_thread_only().delayed_incoming_queue.swap(&queue_to_delete); TaskDeque deque; { @@ -1059,28 +1041,40 @@ queue_.pop(); } -void TaskQueueImpl::DelayedIncomingQueue::SweepCancelledTasks() { - std::priority_queue<Task> remaining_tasks; - while (!empty()) { - if (!top().task.IsCancelled()) { - if (top().is_high_res) - pending_high_res_tasks_++; - remaining_tasks.push(std::move(const_cast<Task&>(top()))); - } - pop(); - } - queue_ = std::move(remaining_tasks); +void TaskQueueImpl::DelayedIncomingQueue::swap(DelayedIncomingQueue* rhs) { + std::swap(pending_high_res_tasks_, rhs->pending_high_res_tasks_); + std::swap(queue_, rhs->queue_); } -void TaskQueueImpl::DelayedIncomingQueue::swap(DelayedIncomingQueue& other) { - queue_.swap(other.queue_); - std::swap(pending_high_res_tasks_, other.pending_high_res_tasks_); +void TaskQueueImpl::DelayedIncomingQueue::SweepCancelledTasks() { + // Under the hood a std::priority_queue is a heap and usually it's built on + // top of a std::vector. We poke at that vector directly here to filter out + // canceled tasks in place. + bool task_deleted = false; + auto it = queue_.c.begin(); + while (it != queue_.c.end()) { + if (it->task.IsCancelled()) { + if (it->is_high_res) + pending_high_res_tasks_--; + *it = std::move(queue_.c.back()); + queue_.c.pop_back(); + task_deleted = true; + } else { + it++; + } + } + + // If we deleted something, re-enforce the heap property. + if (task_deleted) + std::make_heap(queue_.c.begin(), queue_.c.end(), queue_.comp); } void TaskQueueImpl::DelayedIncomingQueue::AsValueInto( TimeTicks now, trace_event::TracedValue* state) const { - QueueAsValueInto(queue_, now, state); + for (const Task& task : queue_.c) { + TaskAsValueInto(task, now, state); + } } } // namespace internal
diff --git a/base/task/sequence_manager/task_queue_impl.h b/base/task/sequence_manager/task_queue_impl.h index 508818cd..90dcac1 100644 --- a/base/task/sequence_manager/task_queue_impl.h +++ b/base/task/sequence_manager/task_queue_impl.h
@@ -282,7 +282,7 @@ bool empty() const { return queue_.empty(); } size_t size() const { return queue_.size(); } const Task& top() const { return queue_.top(); } - void swap(DelayedIncomingQueue& other); + void swap(DelayedIncomingQueue* other); bool has_pending_high_resolution_tasks() const { return pending_high_res_tasks_; @@ -293,7 +293,14 @@ void AsValueInto(TimeTicks now, trace_event::TracedValue* state) const; private: - std::priority_queue<Task> queue_; + struct PQueue : public std::priority_queue<Task> { + // Expose the container and comparator. + using std::priority_queue<Task>::c; + using std::priority_queue<Task>::comp; + }; + + PQueue queue_; + // Number of pending tasks in the queue that need high resolution timing. int pending_high_res_tasks_ = 0;
diff --git a/base/test/scoped_task_environment.cc b/base/test/scoped_task_environment.cc index b3c81c7..333956f3 100644 --- a/base/test/scoped_task_environment.cc +++ b/base/test/scoped_task_environment.cc
@@ -13,6 +13,8 @@ #include "base/synchronization/condition_variable.h" #include "base/synchronization/lock.h" #include "base/task/post_task.h" +#include "base/task/sequence_manager/sequence_manager_impl.h" +#include "base/task/sequence_manager/time_domain.h" #include "base/task/task_scheduler/task_scheduler.h" #include "base/task/task_scheduler/task_scheduler_impl.h" #include "base/test/test_mock_time_task_runner.h" @@ -36,20 +38,35 @@ LazyInstance<ThreadLocalPointer<ScopedTaskEnvironment::LifetimeObserver>>::Leaky environment_lifetime_observer; -std::unique_ptr<MessageLoop> CreateMessageLoopForMainThreadType( +base::Optional<MessageLoop::Type> GetMessageLoopTypeForMainThreadType( ScopedTaskEnvironment::MainThreadType main_thread_type) { switch (main_thread_type) { case ScopedTaskEnvironment::MainThreadType::DEFAULT: - return std::make_unique<MessageLoop>(MessageLoop::TYPE_DEFAULT); case ScopedTaskEnvironment::MainThreadType::MOCK_TIME: - return nullptr; + return MessageLoop::TYPE_DEFAULT; case ScopedTaskEnvironment::MainThreadType::UI: - return std::make_unique<MessageLoop>(MessageLoop::TYPE_UI); + case ScopedTaskEnvironment::MainThreadType::UI_MOCK_TIME: + return MessageLoop::TYPE_UI; case ScopedTaskEnvironment::MainThreadType::IO: - return std::make_unique<MessageLoop>(MessageLoop::TYPE_IO); + case ScopedTaskEnvironment::MainThreadType::IO_MOCK_TIME: + return MessageLoop::TYPE_IO; } NOTREACHED(); - return nullptr; + return base::nullopt; +} + +std::unique_ptr<sequence_manager::SequenceManager> +CreateSequenceManagerForMainThreadType( + ScopedTaskEnvironment::MainThreadType main_thread_type) { + auto type = GetMessageLoopTypeForMainThreadType(main_thread_type); + if (!type) { + return nullptr; + } else { + auto settings = base::sequence_manager::SequenceManager::Settings{ + .message_loop_type = *type}; + return sequence_manager::CreateSequenceManagerOnCurrentThreadWithPump( + MessageLoop::CreateMessagePumpForType(*type), std::move(settings)); + } } class TickClockBasedClock : public Clock { @@ -71,6 +88,135 @@ } // namespace +class ScopedTaskEnvironment::MockTimeDomain + : public sequence_manager::TimeDomain, + public TickClock { + public: + MockTimeDomain() = default; + ~MockTimeDomain() override = default; + + using TimeDomain::NextScheduledRunTime; + + static std::unique_ptr<ScopedTaskEnvironment::MockTimeDomain> Create( + ScopedTaskEnvironment::MainThreadType main_thread_type) { + if (main_thread_type == MainThreadType::MOCK_TIME || + main_thread_type == MainThreadType::UI_MOCK_TIME || + main_thread_type == MainThreadType::IO_MOCK_TIME) { + return std::make_unique<ScopedTaskEnvironment::MockTimeDomain>(); + } + return nullptr; + } + + // sequence_manager::TimeDomain: + + sequence_manager::LazyNow CreateLazyNow() const override { + base::AutoLock lock(now_ticks_lock_); + return sequence_manager::LazyNow(now_ticks_); + } + + TimeTicks Now() const override { + // This can be called from any thread. + base::AutoLock lock(now_ticks_lock_); + return now_ticks_; + } + + Optional<TimeDelta> DelayTillNextTask( + sequence_manager::LazyNow* lazy_now) override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Make sure TimeDomain::NextScheduledRunTime has taken canceled tasks into + // account, ReclaimMemory sweeps canceled delayed tasks. + sequence_manager()->ReclaimMemory(); + Optional<TimeTicks> run_time = NextScheduledRunTime(); + // Check if we've run out of tasks. + if (!run_time) + return base::nullopt; + + // Check if we have a task that should be running now. + if (run_time <= now_ticks_) + return base::TimeDelta(); + + // The next task is a future delayed task. Since we're using mock time, we + // don't want an actual OS level delayed wake up scheduled, so pretend we + // have no more work. This will result in MaybeFastForwardToNextTask getting + // called which lets us advance |now_ticks_|. + return base::nullopt; + } + + // This method is called when the underlying message pump has run out of + // non-delayed work. + bool MaybeFastForwardToNextTask(bool quit_when_idle_requested) override { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // If we're being externally controlled by a RunLoop in client code, check + // if the RunLoop is due to quit when idle, if so we don't want to advance + // mock time. + if (stop_when_message_pump_is_idle_ && quit_when_idle_requested) + return false; + + // We don't need to call ReclaimMemory here because + // DelayTillNextTask will have dealt with cancelled delayed tasks for us. + Optional<TimeTicks> run_time = NextScheduledRunTime(); + if (!run_time) { + // We've run out of tasks, but ScopedTaskEnvironment::FastForwardBy + // requires the virtual time to be consumed. + if (now_ticks_ < allow_advance_until_ && !allow_advance_until_.is_max()) + SetTime(allow_advance_until_); + return false; + } + + // Don't advance past |allow_advance_until_|. + DCHECK_GT(*run_time, now_ticks_); + TimeTicks time_to_advance_to = std::min(allow_advance_until_, *run_time); + if (time_to_advance_to <= now_ticks_) + return false; + + SetTime(time_to_advance_to); + + // Make sure a DoWork is scheduled. + return true; + } + + const char* GetName() const override { return "MockTimeDomain"; } + + // TickClock implementation: + TimeTicks NowTicks() const override { return Now(); } + + // Allows time to advance when reaching idle, until + // |now_ticks_ == advance_until|. No-op if |advance_until <= now_ticks_|. + // Doesn't schedule work by itself. + void SetAllowTimeToAutoAdvanceUntil(TimeTicks advance_until) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + allow_advance_until_ = advance_until; + } + + void SetStopWhenMessagePumpIsIdle(bool stop_when_message_pump_is_idle) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + stop_when_message_pump_is_idle_ = stop_when_message_pump_is_idle; + } + + private: + void SetTime(TimeTicks time) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK_LE(time, allow_advance_until_); + + base::AutoLock lock(now_ticks_lock_); + now_ticks_ = time; + } + + SEQUENCE_CHECKER(sequence_checker_); + + // By default we want RunLoop.Run() to advance virtual time due to the API + // contract. + TimeTicks allow_advance_until_ = TimeTicks::Max(); + bool stop_when_message_pump_is_idle_ = true; + + // Protects |now_ticks_| + mutable Lock now_ticks_lock_; + + // Only ever written to from the main sequence. + TimeTicks now_ticks_; +}; + class ScopedTaskEnvironment::TestTaskTracker : public internal::TaskSchedulerImpl::TaskTrackerImpl { public: @@ -119,31 +265,40 @@ ScopedTaskEnvironment::ScopedTaskEnvironment( MainThreadType main_thread_type, ExecutionMode execution_control_mode) + : ScopedTaskEnvironment( + CreateSequenceManagerForMainThreadType(main_thread_type), + nullptr, + main_thread_type, + execution_control_mode) {} + +ScopedTaskEnvironment::ScopedTaskEnvironment( + sequence_manager::SequenceManager* sequence_manager, + MainThreadType main_thread_type, + ExecutionMode execution_control_mode) + : ScopedTaskEnvironment(nullptr, + sequence_manager, + main_thread_type, + execution_control_mode) {} + +ScopedTaskEnvironment::ScopedTaskEnvironment( + std::unique_ptr<sequence_manager::SequenceManager> owned_sequence_manager, + sequence_manager::SequenceManager* sequence_manager, + MainThreadType main_thread_type, + ExecutionMode execution_control_mode) : execution_control_mode_(execution_control_mode), - message_loop_(CreateMessageLoopForMainThreadType(main_thread_type)), - mock_time_task_runner_( - main_thread_type == MainThreadType::MOCK_TIME - ? MakeRefCounted<TestMockTimeTaskRunner>( - TestMockTimeTaskRunner::Type::kBoundToThread) - : nullptr), - slsm_for_mock_time_( - main_thread_type == MainThreadType::MOCK_TIME - ? std::make_unique<internal::SequenceLocalStorageMap>() - : nullptr), - slsm_registration_for_mock_time_( - main_thread_type == MainThreadType::MOCK_TIME - ? std::make_unique< - internal::ScopedSetSequenceLocalStorageMapForCurrentThread>( - slsm_for_mock_time_.get()) - : nullptr), - mock_clock_(mock_time_task_runner_ - ? std::make_unique<TickClockBasedClock>( - mock_time_task_runner_->GetMockTickClock()) - : nullptr), + mock_time_domain_(MockTimeDomain::Create(main_thread_type)), + owned_sequence_manager_(std::move(owned_sequence_manager)), + sequence_manager_(owned_sequence_manager_.get() + ? owned_sequence_manager_.get() + : sequence_manager), + task_queue_(CreateDefaultTaskQueue()), + mock_clock_(mock_time_domain_ ? std::make_unique<TickClockBasedClock>( + mock_time_domain_.get()) + : nullptr), #if defined(OS_POSIX) || defined(OS_FUCHSIA) file_descriptor_watcher_(main_thread_type == MainThreadType::IO ? std::make_unique<FileDescriptorWatcher>( - message_loop_->task_runner()) + task_queue_->task_runner()) : nullptr), #endif // defined(OS_POSIX) || defined(OS_FUCHSIA) task_tracker_(new TestTaskTracker()) { @@ -154,6 +309,8 @@ "someone has explicitly disabled it with " "DisableCheckForLeakedGlobals()."; + sequence_manager_->SetDefaultTaskRunner(task_queue_->task_runner()); + // Instantiate a TaskScheduler with 2 threads in each of its 4 pools. Threads // stay alive even when they don't have work. // Each pool uses two threads to prevent deadlocks in unit tests that have a @@ -220,6 +377,20 @@ LifetimeObserver* observer = environment_lifetime_observer.Get().Get(); if (observer) observer->OnScopedTaskEnvironmentDestroyed(); + + task_queue_ = nullptr; + if (mock_time_domain_) + sequence_manager_->UnregisterTimeDomain(mock_time_domain_.get()); +} + +scoped_refptr<sequence_manager::TaskQueue> +ScopedTaskEnvironment::CreateDefaultTaskQueue() { + if (mock_time_domain_) + sequence_manager_->RegisterTimeDomain(mock_time_domain_.get()); + + return sequence_manager_->CreateTaskQueue( + sequence_manager::TaskQueue::Spec("scoped_task_environment_default") + .SetTimeDomain(mock_time_domain_.get())); } void ScopedTaskEnvironment::SetLifetimeObserver( @@ -230,20 +401,29 @@ scoped_refptr<base::SingleThreadTaskRunner> ScopedTaskEnvironment::GetMainThreadTaskRunner() { - if (message_loop_) - return message_loop_->task_runner(); - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_; + return task_queue_->task_runner(); } bool ScopedTaskEnvironment::MainThreadHasPendingTask() const { - if (message_loop_) - return !message_loop_->IsIdleForTesting(); - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_->HasPendingTask(); + sequence_manager::internal::SequenceManagerImpl* sequence_manager_impl = + static_cast<sequence_manager::internal::SequenceManagerImpl*>( + sequence_manager_); + // ReclaimMemory sweeps canceled delayed tasks. + sequence_manager_impl->ReclaimMemory(); + // Unfortunately this API means different things depending on whether mock + // time is used or not. If MockTime is used then tests want to know if there + // are any delayed or non-delayed tasks, otherwise only non-delayed tasks are + // considered. + if (mock_time_domain_) + return sequence_manager_impl->HasTasks(); + return !sequence_manager_impl->IsIdleForTesting(); } void ScopedTaskEnvironment::RunUntilIdle() { + // Prevent virtual time from advancing while within this call. + if (mock_time_domain_) + mock_time_domain_->SetAllowTimeToAutoAdvanceUntil(TimeTicks()); + // TODO(gab): This can be heavily simplified to essentially: // bool HasMainThreadTasks() { // if (message_loop_) @@ -321,31 +501,36 @@ // parallel execution before returning unless in ExecutionMode::QUEUED. if (execution_control_mode_ != ExecutionMode::QUEUED) task_tracker_->AllowRunTasks(); + + if (mock_time_domain_) + mock_time_domain_->SetAllowTimeToAutoAdvanceUntil(TimeTicks::Max()); } void ScopedTaskEnvironment::FastForwardBy(TimeDelta delta) { - DCHECK(mock_time_task_runner_); - mock_time_task_runner_->FastForwardBy(delta); + MessageLoopCurrent::ScopedNestableTaskAllower allow; + DCHECK(mock_time_domain_); + mock_time_domain_->SetStopWhenMessagePumpIsIdle(false); + mock_time_domain_->SetAllowTimeToAutoAdvanceUntil(mock_time_domain_->Now() + + delta); + RunLoop().RunUntilIdle(); + mock_time_domain_->SetStopWhenMessagePumpIsIdle(true); + mock_time_domain_->SetAllowTimeToAutoAdvanceUntil(TimeTicks::Max()); } void ScopedTaskEnvironment::FastForwardUntilNoTasksRemain() { - DCHECK(mock_time_task_runner_); - mock_time_task_runner_->FastForwardUntilNoTasksRemain(); + // TimeTicks::operator+(TimeDelta) uses saturated arithmetic so it's safe to + // pass in TimeDelta::Max(). + FastForwardBy(TimeDelta::Max()); } const TickClock* ScopedTaskEnvironment::GetMockTickClock() const { - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_->GetMockTickClock(); -} - -std::unique_ptr<TickClock> ScopedTaskEnvironment::DeprecatedGetMockTickClock() { - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_->DeprecatedGetMockTickClock(); + DCHECK(mock_time_domain_); + return mock_time_domain_.get(); } base::TimeTicks ScopedTaskEnvironment::NowTicks() const { - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_->NowTicks(); + DCHECK(mock_time_domain_); + return mock_time_domain_->Now(); } const Clock* ScopedTaskEnvironment::GetMockClock() const { @@ -354,13 +539,19 @@ } size_t ScopedTaskEnvironment::GetPendingMainThreadTaskCount() const { - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_->GetPendingTaskCount(); + // ReclaimMemory sweeps canceled delayed tasks. + sequence_manager_->ReclaimMemory(); + return sequence_manager_->GetPendingTaskCountForTesting(); } TimeDelta ScopedTaskEnvironment::NextMainThreadPendingTaskDelay() const { - DCHECK(mock_time_task_runner_); - return mock_time_task_runner_->NextPendingTaskDelay(); + // ReclaimMemory sweeps canceled delayed tasks. + sequence_manager_->ReclaimMemory(); + DCHECK(mock_time_domain_); + Optional<TimeTicks> run_time = mock_time_domain_->NextScheduledRunTime(); + if (run_time) + return *run_time - mock_time_domain_->Now(); + return TimeDelta::Max(); } ScopedTaskEnvironment::TestTaskTracker::TestTaskTracker()
diff --git a/base/test/scoped_task_environment.h b/base/test/scoped_task_environment.h index fe77549..b86acbc 100644 --- a/base/test/scoped_task_environment.h +++ b/base/test/scoped_task_environment.h
@@ -9,21 +9,16 @@ #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "base/task/lazy_task_runner.h" +#include "base/task/sequence_manager/sequence_manager.h" #include "base/time/time.h" #include "build/build_config.h" namespace base { -namespace internal { -class ScopedSetSequenceLocalStorageMapForCurrentThread; -class SequenceLocalStorageMap; -} // namespace internal class Clock; class FileDescriptorWatcher; -class MessageLoop; class TaskScheduler; -class TestMockTimeTaskRunner; class TickClock; namespace test { @@ -78,9 +73,18 @@ MOCK_TIME, // The main thread pumps UI messages. UI, + // The main thread pumps UI messages and uses a mock clock for delayed tasks + // (controllable via FastForward*() methods). + // TODO(gab@): Enable mock time on all threads and make MOCK_TIME + // configurable independent of MainThreadType. + UI_MOCK_TIME, // The main thread pumps asynchronous IO messages and supports the // FileDescriptorWatcher API on POSIX. IO, + // The main thread pumps IO messages and uses a mock clock for delayed tasks + // (controllable via FastForward*() methods). In addition it supports the + // FileDescriptorWatcher API on POSIX. + IO_MOCK_TIME, }; enum class ExecutionMode { @@ -96,6 +100,13 @@ MainThreadType main_thread_type = MainThreadType::DEFAULT, ExecutionMode execution_control_mode = ExecutionMode::ASYNC); + // Constructs a ScopedTaskEnvironment using a preexisting |sequence_manager|. + // |sequence_manager| must outlive this ScopedTaskEnvironment. + ScopedTaskEnvironment( + sequence_manager::SequenceManager* sequence_manager, + MainThreadType main_thread_type = MainThreadType::DEFAULT, + ExecutionMode execution_control_mode = ExecutionMode::ASYNC); + // Waits until no undelayed TaskScheduler tasks remain. Then, unregisters the // TaskScheduler and the (Thread|Sequenced)TaskRunnerHandle. ~ScopedTaskEnvironment(); @@ -165,24 +176,25 @@ TimeDelta NextMainThreadPendingTaskDelay() const; private: + class MockTimeDomain; class TestTaskTracker; + ScopedTaskEnvironment( + std::unique_ptr<sequence_manager::SequenceManager> owned_sequence_manager, + sequence_manager::SequenceManager* sequence_manager, + MainThreadType main_thread_type, + ExecutionMode execution_control_mode); + + scoped_refptr<sequence_manager::TaskQueue> CreateDefaultTaskQueue(); + const ExecutionMode execution_control_mode_; - // Exactly one of these will be non-null to provide the task environment on - // the main thread. Users of this class should NOT rely on the presence of a - // MessageLoop beyond (Thread|Sequenced)TaskRunnerHandle and RunLoop as - // the backing implementation of each MainThreadType may change over time. - const std::unique_ptr<MessageLoop> message_loop_; - const scoped_refptr<TestMockTimeTaskRunner> mock_time_task_runner_; + const std::unique_ptr<MockTimeDomain> mock_time_domain_; + const std::unique_ptr<sequence_manager::SequenceManager> + owned_sequence_manager_; + sequence_manager::SequenceManager* const sequence_manager_; - // Non-null in MOCK_TIME, where an explicit SequenceLocalStorageMap needs to - // be provided. TODO(gab): This can be removed once mock time support is added - // to MessageLoop directly. - const std::unique_ptr<internal::SequenceLocalStorageMap> slsm_for_mock_time_; - const std::unique_ptr< - internal::ScopedSetSequenceLocalStorageMapForCurrentThread> - slsm_registration_for_mock_time_; + scoped_refptr<sequence_manager::TaskQueue> task_queue_; // Only set for instances with a MOCK_TIME MainThreadType. const std::unique_ptr<Clock> mock_clock_;
diff --git a/base/test/scoped_task_environment_unittest.cc b/base/test/scoped_task_environment_unittest.cc index 2e89ade..b126704 100644 --- a/base/test/scoped_task_environment_unittest.cc +++ b/base/test/scoped_task_environment_unittest.cc
@@ -373,6 +373,10 @@ ScopedTaskEnvironmentTest, ::testing::Values(ScopedTaskEnvironment::MainThreadType::MOCK_TIME)); INSTANTIATE_TEST_CASE_P( + MainThreadUiMockTime, + ScopedTaskEnvironmentTest, + ::testing::Values(ScopedTaskEnvironment::MainThreadType::UI_MOCK_TIME)); +INSTANTIATE_TEST_CASE_P( MainThreadUI, ScopedTaskEnvironmentTest, ::testing::Values(ScopedTaskEnvironment::MainThreadType::UI)); @@ -587,6 +591,10 @@ MainThreadMockTime, ScopedTaskEnvironmentMockedTime, ::testing::Values(ScopedTaskEnvironment::MainThreadType::MOCK_TIME)); +INSTANTIATE_TEST_CASE_P( + MainThreadUiMockTime, + ScopedTaskEnvironmentMockedTime, + ::testing::Values(ScopedTaskEnvironment::MainThreadType::UI_MOCK_TIME)); } // namespace test } // namespace base
diff --git a/build/android/gyp/dex.py b/build/android/gyp/dex.py index 08f5515..3b9c404 100755 --- a/build/android/gyp/dex.py +++ b/build/android/gyp/dex.py
@@ -33,15 +33,6 @@ parser = optparse.OptionParser() build_utils.AddDepfileOption(parser) - parser.add_option( - '--desugar', - default=False, - action='store_true', - help='Use d8 desugaring.') - parser.add_option('--classpath', help='Classpaths necessary for desugaring.') - parser.add_option( - '--sdk-jars', - help='Path(s) to android sdk jar, necessary for desugaring.') parser.add_option('--output-directory', default=os.getcwd(), help='Path to the output build directory.') @@ -304,16 +295,7 @@ if options.multi_dex: input_paths.append(options.main_dex_list_path) - dex_cmd = ['java', '-jar', options.d8_jar_path] - if options.desugar: - options.sdk_jars = build_utils.ParseGnList(options.sdk_jars) - options.classpath = build_utils.ParseGnList(options.classpath) - for path in options.classpath: - dex_cmd += ['--classpath', path] - for path in options.sdk_jars: - dex_cmd += ['--lib', path] - else: - dex_cmd += ['--no-desugaring'] + dex_cmd = ['java', '-jar', options.d8_jar_path, '--no-desugaring'] if options.multi_dex: dex_cmd += ['--main-dex-list', options.main_dex_list_path] if options.release:
diff --git a/build/config/BUILD.gn b/build/config/BUILD.gn index 10f2fc8..da3b21c 100644 --- a/build/config/BUILD.gn +++ b/build/config/BUILD.gn
@@ -385,8 +385,6 @@ configs += [ "//build/config/ios:ios_dynamic_flags" ] } else if (is_chromecast) { configs += [ "//build/config/chromecast:shared_library_config" ] - } else if (is_linux || current_os == "aix") { - configs += [ "//build/config/gcc:shared_library_config" ] } # If we're using the prebuilt instrumented libraries with the sanitizers, we
diff --git a/build/config/android/internal_rules.gni b/build/config/android/internal_rules.gni index 54eb8a2..c9e28d3 100644 --- a/build/config/android/internal_rules.gni +++ b/build/config/android/internal_rules.gni
@@ -1256,18 +1256,6 @@ _rebased_output, ] - # Release builds use desugar.jar instead of d8 for desugaring. - if (is_java_debug) { - inputs += [ invoker.build_config ] - _rebased_build_config = - rebase_path(invoker.build_config, root_build_dir) - args += [ - "--desugar", - "--classpath=@FileArg($_rebased_build_config:deps_info:javac_full_interface_classpath)", - "--sdk-jars=@FileArg($_rebased_build_config:android:sdk_jars)", - ] - } - if (_proguard_enabled) { deps += [ ":${_proguard_target_name}" ] } @@ -1426,9 +1414,7 @@ # Turned off because of existing code which fails the assertion _enable_thread_annotations = false - # Only use desugar.jar for release builds, rely on dexing with d8 otherwise. - _desugar = defined(invoker.supports_android) && invoker.supports_android && - !is_java_debug + _desugar = defined(invoker.supports_android) && invoker.supports_android _emma_instrument = invoker.emma_instrument _enable_bytecode_rewriter = _enable_assert || _enable_custom_resources || _enable_thread_annotations @@ -3394,13 +3380,9 @@ if (defined(_dex_path)) { dex("${target_name}__dex") { - if (is_java_debug) { - build_config = _build_config - } input_jars = [ _final_jar_path ] output = _dex_path deps = [ - ":$_build_config_target_name", ":$_process_prebuilt_target_name", ] }
diff --git a/build/config/gcc/BUILD.gn b/build/config/gcc/BUILD.gn index 3f5756e..257cdc7 100644 --- a/build/config/gcc/BUILD.gn +++ b/build/config/gcc/BUILD.gn
@@ -84,24 +84,20 @@ } } -if (is_component_build && !is_android) { - # See the rpath_for... config above for why this is necessary for component - # builds. - executable_and_shared_library_configs_ = - [ ":rpath_for_built_shared_libraries" ] -} else { - executable_and_shared_library_configs_ = [] -} - # Settings for executables. config("executable_config") { - configs = executable_and_shared_library_configs_ ldflags = [ "-pie" ] if (is_android) { ldflags += [ "-Bdynamic", "-Wl,-z,nocopyreloc", ] + } else { + # See the rpath_for... config above for why this is necessary for component + # builds. + if (is_component_build) { + configs = [ ":rpath_for_built_shared_libraries" ] + } } if (!is_android && current_os != "aix") { @@ -120,8 +116,3 @@ ] } } - -# Settings for shared libraries. -config("shared_library_config") { - configs = executable_and_shared_library_configs_ -}
diff --git a/build/vs_toolchain.py b/build/vs_toolchain.py index 0372499..07057c0 100755 --- a/build/vs_toolchain.py +++ b/build/vs_toolchain.py
@@ -215,8 +215,14 @@ # ARM64 doesn't have a redist for the ucrt DLLs because they are always # present in the OS. if target_cpu != 'arm64': - ucrt_dll_dirs = os.path.join(win_sdk_dir, 'Redist', 'ucrt', 'DLLs', - target_cpu) + # Starting with the 10.0.17763 SDK the ucrt files are in a version-named + # directory - this handles both cases. + redist_dir = os.path.join(win_sdk_dir, 'Redist') + version_dirs = glob.glob(redist_dir + r'\10.*') + if len(version_dirs) > 0: + version_dirs.sort(reverse=True) + redist_dir = version_dirs[0] + ucrt_dll_dirs = os.path.join(redist_dir, 'ucrt', 'DLLs', target_cpu) ucrt_files = glob.glob(os.path.join(ucrt_dll_dirs, 'api-ms-win-*.dll')) assert len(ucrt_files) > 0 for ucrt_src_file in ucrt_files: @@ -387,7 +393,7 @@ # TODO(crbug.com/773476): remove version requirement. raise Exception('%s not found in "%s"\r\nYou must install the ' '"Debugging Tools for Windows" feature from the Windows' - ' 10 SDK. You must use v10.0.17134.0. of the SDK' + ' 10 SDK.' % (debug_file, full_path)) target_path = os.path.join(target_dir, debug_file) _CopyRuntimeImpl(target_path, full_path)
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 26fb7923..1695e9b 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -97,11 +97,14 @@ #include "components/viz/common/quads/texture_draw_quad.h" #include "components/viz/common/resources/bitmap_allocation.h" #include "components/viz/common/resources/platform_color.h" +#include "components/viz/common/resources/resource_sizes.h" #include "components/viz/common/traced_value.h" #include "gpu/GLES2/gl2extchromium.h" #include "gpu/command_buffer/client/context_support.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "gpu/command_buffer/client/raster_interface.h" +#include "gpu/command_buffer/client/shared_image_interface.h" +#include "gpu/command_buffer/common/shared_image_usage.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "third_party/skia/include/gpu/GrContext.h" #include "ui/gfx/geometry/point_conversions.h" @@ -3251,8 +3254,12 @@ // contexts. Flushing now helps ensure these are cleaned up quickly // preventing driver cache growth. See crbug.com/643251 if (layer_tree_frame_sink_) { - if (auto* compositor_context = layer_tree_frame_sink_->context_provider()) - compositor_context->ContextGL()->ShallowFlushCHROMIUM(); + if (auto* compositor_context = layer_tree_frame_sink_->context_provider()) { + // TODO(ericrk): Remove ordering barrier once |compositor_context| no + // longer uses GL. + compositor_context->ContextGL()->OrderingBarrierCHROMIUM(); + compositor_context->ContextSupport()->FlushPendingWork(); + } if (auto* worker_context = layer_tree_frame_sink_->worker_context_provider()) { viz::RasterContextProvider::ScopedRasterContextLock hold(worker_context); @@ -3277,6 +3284,8 @@ ClearUIResources(); if (layer_tree_frame_sink_->context_provider()) { + // TODO(ericrk): Remove this once all uses of ContextGL from LTFS are + // removed. auto* gl = layer_tree_frame_sink_->context_provider()->ContextGL(); gl->Finish(); } @@ -5187,9 +5196,13 @@ upload_size = gfx::ScaleToCeiledSize(source_size, scale, scale); } - // For gpu compositing, a texture will be allocated and the UIResource - // will be uploaded into it. - viz::TextureAllocation texture_alloc; + // For gpu compositing, a SharedImage mailbox will be allocated and the + // UIResource will be uploaded into it. + gpu::Mailbox mailbox; + uint32_t shared_image_usage = gpu::SHARED_IMAGE_USAGE_DISPLAY; + // For gpu compositing, we also calculate the GL texture target. + // TODO(ericrk): Remove references to GL from this code. + GLenum texture_target = GL_TEXTURE_2D; // For software compositing, shared memory will be allocated and the // UIResource will be copied into it. std::unique_ptr<base::SharedMemory> shared_memory; @@ -5198,10 +5211,16 @@ if (layer_tree_frame_sink_->context_provider()) { viz::ContextProvider* context_provider = layer_tree_frame_sink_->context_provider(); - texture_alloc = viz::TextureAllocation::MakeTextureId( - context_provider->ContextGL(), context_provider->ContextCapabilities(), - format, settings_.resource_settings.use_gpu_memory_buffer_resources, - /*for_framebuffer_attachment=*/false); + const auto& caps = context_provider->ContextCapabilities(); + bool overlay_candidate = + settings_.resource_settings.use_gpu_memory_buffer_resources && + caps.texture_storage_image && + viz::IsGpuMemoryBufferFormatSupported(format); + if (overlay_candidate) { + shared_image_usage |= gpu::SHARED_IMAGE_USAGE_SCANOUT; + texture_target = gpu::GetBufferTextureTarget(gfx::BufferUsage::SCANOUT, + BufferFormat(format), caps); + } } else { shared_memory = viz::bitmap_allocation::AllocateMappedBitmap(upload_size, format); @@ -5212,10 +5231,15 @@ // If not scaled, we can copy the pixels 1:1 from the source bitmap to our // destination backing of a texture or shared bitmap. if (layer_tree_frame_sink_->context_provider()) { - viz::TextureAllocation::UploadStorage( - layer_tree_frame_sink_->context_provider()->ContextGL(), - layer_tree_frame_sink_->context_provider()->ContextCapabilities(), - format, upload_size, texture_alloc, color_space, bitmap.GetPixels()); + viz::ContextProvider* context_provider = + layer_tree_frame_sink_->context_provider(); + auto* sii = context_provider->SharedImageInterface(); + size_t size_to_send = + viz::ResourceSizes::CheckedSizeInBytes<unsigned int>(upload_size, + format); + mailbox = sii->CreateSharedImage( + format, upload_size, color_space, shared_image_usage, + base::span<const uint8_t>(bitmap.GetPixels(), size_to_send)); } else { DCHECK_EQ(bitmap.GetFormat(), UIResourceBitmap::RGBA8); SkImageInfo src_info = @@ -5274,10 +5298,14 @@ if (layer_tree_frame_sink_->context_provider()) { SkPixmap pixmap; scaled_surface->peekPixels(&pixmap); - viz::TextureAllocation::UploadStorage( - layer_tree_frame_sink_->context_provider()->ContextGL(), - layer_tree_frame_sink_->context_provider()->ContextCapabilities(), - format, upload_size, texture_alloc, color_space, pixmap.addr()); + viz::ContextProvider* context_provider = + layer_tree_frame_sink_->context_provider(); + auto* sii = context_provider->SharedImageInterface(); + mailbox = sii->CreateSharedImage( + format, upload_size, color_space, shared_image_usage, + base::span<const uint8_t>( + reinterpret_cast<const uint8_t*>(pixmap.addr()), + pixmap.computeByteSize())); } } @@ -5290,16 +5318,12 @@ // allocated in this method above. viz::TransferableResource transferable; if (layer_tree_frame_sink_->context_provider()) { - gpu::gles2::GLES2Interface* gl = - layer_tree_frame_sink_->context_provider()->ContextGL(); - gpu::Mailbox mailbox; - gl->ProduceTextureDirectCHROMIUM(texture_alloc.texture_id, mailbox.name); - gpu::SyncToken sync_token = - viz::ClientResourceProvider::GenerateSyncTokenHelper(gl); + gpu::SyncToken sync_token = layer_tree_frame_sink_->context_provider() + ->SharedImageInterface() + ->GenUnverifiedSyncToken(); transferable = viz::TransferableResource::MakeGLOverlay( - mailbox, GL_LINEAR, texture_alloc.texture_target, sync_token, - upload_size, texture_alloc.overlay_candidate); + mailbox, GL_LINEAR, texture_target, sync_token, upload_size, false); transferable.format = format; } else { mojo::ScopedSharedBufferHandle memory_handle = @@ -5325,7 +5349,7 @@ data.format = format; data.shared_bitmap_id = shared_bitmap_id; data.shared_memory = std::move(shared_memory); - data.texture_id = texture_alloc.texture_id; + data.mailbox = mailbox; data.resource_id_for_export = id; ui_resource_map_[uid] = std::move(data); @@ -5352,15 +5376,13 @@ UIResourceData data, const gpu::SyncToken& sync_token) { // Resources are either software or gpu backed, not both. - DCHECK(!(data.shared_memory && data.texture_id)); + DCHECK(!(data.shared_memory && !data.mailbox.IsZero())); if (data.shared_memory) layer_tree_frame_sink_->DidDeleteSharedBitmap(data.shared_bitmap_id); - if (data.texture_id) { - gpu::gles2::GLES2Interface* gl = - layer_tree_frame_sink_->context_provider()->ContextGL(); - if (sync_token.HasData()) - gl->WaitSyncTokenCHROMIUM(sync_token.GetConstData()); - gl->DeleteTextures(1, &data.texture_id); + if (!data.mailbox.IsZero()) { + auto* sii = + layer_tree_frame_sink_->context_provider()->SharedImageInterface(); + sii->DestroySharedImage(sync_token, data.mailbox); } // |data| goes out of scope and deletes anything it owned. }
diff --git a/cc/trees/layer_tree_host_impl.h b/cc/trees/layer_tree_host_impl.h index b932defe..d8dd156 100644 --- a/cc/trees/layer_tree_host_impl.h +++ b/cc/trees/layer_tree_host_impl.h
@@ -211,7 +211,7 @@ viz::SharedBitmapId shared_bitmap_id; std::unique_ptr<base::SharedMemory> shared_memory; // Backing for gpu compositing. - uint32_t texture_id; + gpu::Mailbox mailbox; // The name with which to refer to the resource in frames submitted to the // display compositor.
diff --git a/cc/trees/layer_tree_host_impl_unittest.cc b/cc/trees/layer_tree_host_impl_unittest.cc index 13a15e66..42331cc 100644 --- a/cc/trees/layer_tree_host_impl_unittest.cc +++ b/cc/trees/layer_tree_host_impl_unittest.cc
@@ -9949,58 +9949,56 @@ } TEST_F(LayerTreeHostImplTest, UIResourceManagement) { - auto gl_owned = std::make_unique<viz::TestGLES2Interface>(); - viz::TestGLES2Interface* gl = gl_owned.get(); + auto test_context_provider = viz::TestContextProvider::Create(); + viz::TestSharedImageInterface* sii = + test_context_provider->SharedImageInterface(); + CreateHostImpl(DefaultSettings(), FakeLayerTreeFrameSink::Create3d( + std::move(test_context_provider))); - std::unique_ptr<FakeLayerTreeFrameSink> layer_tree_frame_sink = - FakeLayerTreeFrameSink::Create3d(std::move(gl_owned)); - CreateHostImpl(DefaultSettings(), std::move(layer_tree_frame_sink)); - - EXPECT_EQ(0u, gl->NumTextures()); + EXPECT_EQ(0u, sii->shared_image_count()); UIResourceId ui_resource_id = 1; bool is_opaque = false; UIResourceBitmap bitmap(gfx::Size(1, 1), is_opaque); host_impl_->CreateUIResource(ui_resource_id, bitmap); - EXPECT_EQ(1u, gl->NumTextures()); + EXPECT_EQ(1u, sii->shared_image_count()); viz::ResourceId id1 = host_impl_->ResourceIdForUIResource(ui_resource_id); EXPECT_NE(0u, id1); // Multiple requests with the same id is allowed. The previous texture is // deleted. host_impl_->CreateUIResource(ui_resource_id, bitmap); - EXPECT_EQ(1u, gl->NumTextures()); + EXPECT_EQ(1u, sii->shared_image_count()); viz::ResourceId id2 = host_impl_->ResourceIdForUIResource(ui_resource_id); EXPECT_NE(0u, id2); EXPECT_NE(id1, id2); // Deleting invalid UIResourceId is allowed and does not change state. host_impl_->DeleteUIResource(-1); - EXPECT_EQ(1u, gl->NumTextures()); + EXPECT_EQ(1u, sii->shared_image_count()); // Should return zero for invalid UIResourceId. Number of textures should // not change. EXPECT_EQ(0u, host_impl_->ResourceIdForUIResource(-1)); - EXPECT_EQ(1u, gl->NumTextures()); + EXPECT_EQ(1u, sii->shared_image_count()); host_impl_->DeleteUIResource(ui_resource_id); EXPECT_EQ(0u, host_impl_->ResourceIdForUIResource(ui_resource_id)); - EXPECT_EQ(0u, gl->NumTextures()); + EXPECT_EQ(0u, sii->shared_image_count()); // Should not change state for multiple deletion on one UIResourceId host_impl_->DeleteUIResource(ui_resource_id); - EXPECT_EQ(0u, gl->NumTextures()); + EXPECT_EQ(0u, sii->shared_image_count()); } TEST_F(LayerTreeHostImplTest, CreateETC1UIResource) { - auto gl_owned = std::make_unique<viz::TestGLES2Interface>(); - gl_owned->set_support_compressed_texture_etc1(true); - viz::TestGLES2Interface* gl = gl_owned.get(); + auto test_context_provider = viz::TestContextProvider::Create(); + viz::TestSharedImageInterface* sii = + test_context_provider->SharedImageInterface(); + CreateHostImpl(DefaultSettings(), FakeLayerTreeFrameSink::Create3d( + std::move(test_context_provider))); - CreateHostImpl(DefaultSettings(), - FakeLayerTreeFrameSink::Create3d(std::move(gl_owned))); - - EXPECT_EQ(0u, gl->NumTextures()); + EXPECT_EQ(0u, sii->shared_image_count()); gfx::Size size(4, 4); // SkImageInfo has no support for ETC1. The |info| below contains the right @@ -10013,7 +10011,7 @@ UIResourceBitmap bitmap(std::move(pixel_ref), size); UIResourceId ui_resource_id = 1; host_impl_->CreateUIResource(ui_resource_id, bitmap); - EXPECT_EQ(1u, gl->NumTextures()); + EXPECT_EQ(1u, sii->shared_image_count()); viz::ResourceId id1 = host_impl_->ResourceIdForUIResource(ui_resource_id); EXPECT_NE(0u, id1); }
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index f360fd7..f23b40f 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -4300,32 +4300,32 @@ } void DidActivateTreeOnThread(LayerTreeHostImpl* impl) override { - auto* context = static_cast<viz::TestContextProvider*>( - impl->layer_tree_frame_sink()->context_provider()) - ->TestContextGL(); + auto* sii = static_cast<viz::TestContextProvider*>( + impl->layer_tree_frame_sink()->context_provider()) + ->SharedImageInterface(); int frame = impl->active_tree()->source_frame_number(); switch (frame) { case 0: - ASSERT_EQ(0u, context->NumTextures()); + ASSERT_EQ(0u, sii->shared_image_count()); break; case 1: // Created two textures. - ASSERT_EQ(2u, context->NumTextures()); + ASSERT_EQ(2u, sii->shared_image_count()); break; case 2: // One texture left after one deletion. - ASSERT_EQ(1u, context->NumTextures()); + ASSERT_EQ(1u, sii->shared_image_count()); break; case 3: // Resource manager state should not change when delete is called on an // invalid id. - ASSERT_EQ(1u, context->NumTextures()); + ASSERT_EQ(1u, sii->shared_image_count()); break; case 4: // Creation after deletion: two more creates should total up to // three textures. - ASSERT_EQ(3u, context->NumTextures()); + ASSERT_EQ(3u, sii->shared_image_count()); break; } }
diff --git a/cc/trees/layer_tree_host_unittest_context.cc b/cc/trees/layer_tree_host_unittest_context.cc index a871ac9..bc8bbcf 100644 --- a/cc/trees/layer_tree_host_unittest_context.cc +++ b/cc/trees/layer_tree_host_unittest_context.cc
@@ -107,6 +107,8 @@ GL_INNOCENT_CONTEXT_RESET_ARB); } + sii_ = provider->SharedImageInterface(); + return LayerTreeTest::CreateLayerTreeFrameSink( renderer_settings, refresh_rate, std::move(provider), std::move(worker_context_provider)); @@ -162,6 +164,7 @@ // CreateDisplayLayerTreeFrameSink can both use it on different threads. base::Lock gl_lock_; viz::TestGLES2Interface* gl_ = nullptr; + viz::TestSharedImageInterface* sii_ = nullptr; int times_to_fail_create_; int times_to_lose_during_commit_; @@ -1494,7 +1497,7 @@ void DidSetVisibleOnImplTree(LayerTreeHostImpl* impl, bool visible) override { if (!visible) { // All resources should have been evicted. - ASSERT_EQ(0u, gl_->NumTextures()); + ASSERT_EQ(0u, sii_->shared_image_count()); EXPECT_EQ(0u, impl->ResourceIdForUIResource(ui_resource_->id())); EXPECT_EQ(0u, impl->ResourceIdForUIResource(ui_resource2_->id())); EXPECT_EQ(0u, impl->ResourceIdForUIResource(ui_resource3_->id())); @@ -1514,7 +1517,7 @@ case 1: // The first two resources should have been created on LTHI after the // commit. - ASSERT_EQ(2u, gl_->NumTextures()); + ASSERT_EQ(2u, sii_->shared_image_count()); EXPECT_NE(0u, impl->ResourceIdForUIResource(ui_resource_->id())); EXPECT_NE(0u, impl->ResourceIdForUIResource(ui_resource2_->id())); EXPECT_EQ(1, ui_resource_->resource_create_count); @@ -1522,7 +1525,7 @@ EXPECT_TRUE(impl->CanDraw()); // Evict all UI resources. This will trigger a commit. impl->EvictAllUIResources(); - ASSERT_EQ(0u, gl_->NumTextures()); + ASSERT_EQ(0u, sii_->shared_image_count()); EXPECT_EQ(0u, impl->ResourceIdForUIResource(ui_resource_->id())); EXPECT_EQ(0u, impl->ResourceIdForUIResource(ui_resource2_->id())); EXPECT_EQ(1, ui_resource_->resource_create_count); @@ -1531,7 +1534,7 @@ break; case 2: // The first two resources should have been recreated. - ASSERT_EQ(2u, gl_->NumTextures()); + ASSERT_EQ(2u, sii_->shared_image_count()); EXPECT_NE(0u, impl->ResourceIdForUIResource(ui_resource_->id())); EXPECT_EQ(2, ui_resource_->resource_create_count); EXPECT_EQ(1, ui_resource_->lost_resource_count); @@ -1543,7 +1546,7 @@ case 3: // The first resource should have been recreated after visibility was // restored. - ASSERT_EQ(2u, gl_->NumTextures()); + ASSERT_EQ(2u, sii_->shared_image_count()); EXPECT_NE(0u, impl->ResourceIdForUIResource(ui_resource_->id())); EXPECT_EQ(3, ui_resource_->resource_create_count); EXPECT_EQ(2, ui_resource_->lost_resource_count); @@ -1585,7 +1588,7 @@ case 0: // The UIResource has been created and a gpu resource made for it. EXPECT_NE(0u, impl->ResourceIdForUIResource(ui_resource_->id())); - EXPECT_EQ(1u, gl_->NumTextures()); + EXPECT_EQ(1u, sii_->shared_image_count()); // Lose the LayerTreeFrameSink connection. The UI resource should // be replaced and the old texture should be destroyed. impl->DidLoseLayerTreeFrameSink(); @@ -1594,7 +1597,7 @@ // The UIResource has been recreated, the old texture is not kept // around. EXPECT_NE(0u, impl->ResourceIdForUIResource(ui_resource_->id())); - EXPECT_EQ(1u, gl_->NumTextures()); + EXPECT_EQ(1u, sii_->shared_image_count()); MainThreadTaskRunner()->PostTask( FROM_HERE, base::BindOnce(
diff --git a/chrome/VERSION b/chrome/VERSION index c9f9730..61247ea 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=73 MINOR=0 -BUILD=3637 +BUILD=3638 PATCH=0
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedRefreshTask.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedRefreshTask.java index d14851f5..2c65866 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedRefreshTask.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedRefreshTask.java
@@ -8,6 +8,7 @@ import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; +import org.chromium.base.annotations.UsedByReflection; import org.chromium.chrome.browser.background_task_scheduler.NativeBackgroundTask; import org.chromium.components.background_task_scheduler.BackgroundTaskScheduler; import org.chromium.components.background_task_scheduler.BackgroundTaskSchedulerFactory; @@ -21,6 +22,7 @@ * A task implementation that loads native and then tries to refresh the Feed's articles. Failures * or interruptions are not retried or rescheduled. */ +@UsedByReflection("BackgroundTaskReflection.java") public class FeedRefreshTask extends NativeBackgroundTask { // The amount of "flex" to add around the fetching periods, as a ratio of the period. private static final double FLEX_FACTOR = 0.1;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategory.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategory.java index be02525..3b4eb97 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategory.java
@@ -26,6 +26,8 @@ // The ID to use when creating the More button, that should not scroll the ESP when clicked. public static final int MORE_BUTTON_ID = -1; + static final int MAX_COLUMNS = 4; + // This enum must match the numbering for ExploreSites.CategoryClick in histograms.xml. Do not // reorder or remove items, only add new items before COUNT. @Retention(RetentionPolicy.SOURCE) @@ -69,6 +71,7 @@ private Drawable mDrawable; // Populated only for ESP. private List<ExploreSitesSite> mSites; + private int mNumBlacklisted; /** * Creates an explore sites category data structure. @@ -113,17 +116,36 @@ public void addSite(ExploreSitesSite site) { mSites.add(site); + if (site.getModel().get(ExploreSitesSite.BLACKLISTED_KEY)) { + mNumBlacklisted++; + } + } + + public int getNumDisplayed() { + return mSites.size() - mNumBlacklisted; + } + + public int getMaxRows() { + return mSites.size() / MAX_COLUMNS; } public boolean removeSite(int siteIndex) { if (siteIndex > mSites.size() || siteIndex < 0) return false; - mSites.remove(siteIndex); + mSites.get(siteIndex).getModel().set(ExploreSitesSite.BLACKLISTED_KEY, true); - // Reset the tile indices to account for removed tiles. + // Reset the tile indices to account for removed tile. + int tileIndex = mSites.get(siteIndex).getModel().get(ExploreSitesSite.TILE_INDEX_KEY); + mSites.get(siteIndex).getModel().set( + ExploreSitesSite.TILE_INDEX_KEY, ExploreSitesSite.DEFAULT_TILE_INDEX); + for (int i = siteIndex; i < mSites.size(); ++i) { ExploreSitesSite site = mSites.get(i); - site.getModel().set(ExploreSitesSite.TILE_INDEX_KEY, i); + if (!mSites.get(siteIndex).getModel().get(ExploreSitesSite.BLACKLISTED_KEY)) { + site.getModel().set(ExploreSitesSite.TILE_INDEX_KEY, tileIndex); + tileIndex++; + } } + mNumBlacklisted++; return true; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java index 7d5418c..87b8c25 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryCardView.java
@@ -38,7 +38,6 @@ public class ExploreSitesCategoryCardView extends LinearLayout { private static final String TAG = "ExploreSitesCategoryCardView"; private static final int MAX_TILE_COUNT = 8; - private static final int MAX_COLUMNS = 4; private static final int MAX_ROWS = 2; private TextView mTitleView; @@ -92,7 +91,8 @@ // Update the view This may add any sites that we didn't have room for before. It // should reset the tile indexeds for views we keep. - updateTileViews(mCategory.getSites()); + updateTileViews( + mCategory.getSites(), mCategory.getNumDisplayed(), mCategory.getMaxRows()); } @Override public String getUrl() { @@ -146,8 +146,7 @@ super.onFinishInflate(); mTitleView = findViewById(R.id.category_title); mTileView = findViewById(R.id.category_sites); - mTileView.setMaxColumns(MAX_COLUMNS); - mTileView.setMaxRows(MAX_ROWS); + mTileView.setMaxColumns(ExploreSitesCategory.MAX_COLUMNS); } public void setCategory(ExploreSitesCategory category, int categoryCardIndex, @@ -161,14 +160,14 @@ mCategory = category; updateTitle(category.getTitle()); - updateTileViews(category.getSites()); + updateTileViews(category.getSites(), category.getNumDisplayed(), category.getMaxRows()); } public void updateTitle(String categoryTitle) { mTitleView.setText(categoryTitle); } - public void updateTileViews(List<ExploreSitesSite> sites) { + public void updateTileViews(List<ExploreSitesSite> sites, int numSitesToShow, int maxRows) { // Clear observers. for (PropertyModelChangeProcessor<PropertyModel, ExploreSitesTileView, PropertyKey> observer : mModelChangeProcessors) { @@ -176,13 +175,18 @@ } mModelChangeProcessors.clear(); - // Remove extra tiles if too many. - if (mTileView.getChildCount() > sites.size()) { - mTileView.removeViews(sites.size(), mTileView.getChildCount() - sites.size()); - } + // Only show rows that would be fully populated by original list of sites. This is + // calculated within the category. + mTileView.setMaxRows(maxRows); - // Maximum number of sites to show. - int tileMax = Math.min(MAX_TILE_COUNT, sites.size()); + // Maximum number of sites that can be shown, defined as min of + // numSitesToShow and maxRows * maxCols. + int tileMax = Math.min(maxRows * ExploreSitesCategory.MAX_COLUMNS, numSitesToShow); + + // Remove extra tiles if too many. + if (mTileView.getChildCount() > tileMax) { + mTileView.removeViews(tileMax, mTileView.getChildCount() - tileMax); + } // Add tiles if too few if (mTileView.getChildCount() < tileMax) { @@ -194,19 +198,27 @@ } // Initialize all the non-empty tiles again to update. - for (int i = 0; i < tileMax; i++) { - ExploreSitesTileView tileView = (ExploreSitesTileView) mTileView.getChildAt(i); - final PropertyModel site = sites.get(i).getModel(); + int tileIndex = 0; + for (ExploreSitesSite site : sites) { + if (tileIndex >= tileMax) break; + final PropertyModel siteModel = site.getModel(); + // Skip blacklisted sites. + if (siteModel.get(ExploreSitesSite.BLACKLISTED_KEY)) continue; + + ExploreSitesTileView tileView = (ExploreSitesTileView) mTileView.getChildAt(tileIndex); tileView.initialize(mIconGenerator); + siteModel.set(ExploreSitesSite.TILE_INDEX_KEY, tileIndex); + mModelChangeProcessors.add(PropertyModelChangeProcessor.create( - site, tileView, new ExploreSitesSiteViewBinder())); + siteModel, tileView, new ExploreSitesSiteViewBinder())); // Fetch icon if not present already. - if (site.get(ExploreSitesSite.ICON_KEY) == null) { - ExploreSitesBridge.getSiteImage(mProfile, site.get(ExploreSitesSite.ID_KEY), - (Bitmap icon) -> site.set(ExploreSitesSite.ICON_KEY, icon)); + if (siteModel.get(ExploreSitesSite.ICON_KEY) == null) { + ExploreSitesBridge.getSiteImage(mProfile, siteModel.get(ExploreSitesSite.ID_KEY), + (Bitmap icon) -> siteModel.set(ExploreSitesSite.ICON_KEY, icon)); } + tileIndex++; } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java index ce00a94..7cab79a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPage.java
@@ -170,7 +170,14 @@ mModel.set(STATUS_KEY, CatalogLoadingState.SUCCESS); ListModel<ExploreSitesCategory> categoryListModel = mModel.get(CATEGORY_LIST_KEY); - categoryListModel.set(categoryList); + + // Filter empty categories and categories with fewer sites originally than would fill a row. + for (ExploreSitesCategory category : categoryList) { + if ((category.getNumDisplayed() > 0) && (category.getMaxRows() > 0)) { + categoryListModel.add(category); + } + } + Parcelable savedScrollPosition = getLayoutManagerStateFromNavigationEntry(); if (savedScrollPosition != null) { mLayoutManager.onRestoreInstanceState(savedScrollPosition);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSection.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSection.java index fe24fee..a0e2cb4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSection.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSection.java
@@ -179,6 +179,8 @@ int tileCount = 0; for (final ExploreSitesCategory category : categoryList) { if (tileCount >= MAX_CATEGORIES) break; + // Skip empty categories from being shown on NTP. + if (category.getNumDisplayed() == 0) continue; createTileView(tileCount, category); tileCount++; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSite.java b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSite.java index 8fcd427..0165271 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSite.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/explore_sites/ExploreSitesSite.java
@@ -13,6 +13,7 @@ * An object encapsulating info for a website. */ public class ExploreSitesSite { + static final int DEFAULT_TILE_INDEX = -1; static final PropertyModel.ReadableIntPropertyKey ID_KEY = new PropertyModel.ReadableIntPropertyKey(); static final PropertyModel.WritableIntPropertyKey TILE_INDEX_KEY = @@ -23,15 +24,20 @@ new PropertyModel.ReadableObjectPropertyKey<>(); static final PropertyModel.WritableObjectPropertyKey<Bitmap> ICON_KEY = new PropertyModel.WritableObjectPropertyKey<>(); + static final PropertyModel.WritableBooleanPropertyKey BLACKLISTED_KEY = + new PropertyModel.WritableBooleanPropertyKey(); private PropertyModel mModel; - public ExploreSitesSite(int id, int tileIndex, String title, String url) { - mModel = new PropertyModel.Builder(ID_KEY, TILE_INDEX_KEY, TITLE_KEY, URL_KEY, ICON_KEY) + public ExploreSitesSite(int id, String title, String url, boolean isBlacklisted) { + mModel = new PropertyModel + .Builder(ID_KEY, TILE_INDEX_KEY, TITLE_KEY, URL_KEY, ICON_KEY, + BLACKLISTED_KEY) .with(ID_KEY, id) - .with(TILE_INDEX_KEY, tileIndex) .with(TITLE_KEY, title) .with(URL_KEY, url) + .with(BLACKLISTED_KEY, isBlacklisted) + .with(TILE_INDEX_KEY, DEFAULT_TILE_INDEX) .build(); } @@ -40,10 +46,9 @@ } @CalledByNative - private static void createSiteInCategory( - int siteId, String title, String url, ExploreSitesCategory category) { - ExploreSitesSite site = - new ExploreSitesSite(siteId, category.getSites().size(), title, url); + private static void createSiteInCategory(int siteId, String title, String url, + boolean isBlacklisted, ExploreSitesCategory category) { + ExploreSitesSite site = new ExploreSitesSite(siteId, title, url, isBlacklisted); category.addSite(site); } }
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index cd8ef90..beab490 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -1228,7 +1228,7 @@ since <ph name="date">%1$s<ex>Feb 28</ex></ph> </message> <message name="IDS_DATA_REDUCTION_BENEFITS_DESCRIPTION" desc="Description text about the benefits of the Lite mode feature. Seen only before the user has enabled the feature."> - In Lite mode, Chrome loads pages faster and uses up to 60% less data. + In Lite mode, Chrome loads pages faster and uses up to 60\% less data. </message> <message name="IDS_DATA_REDUCTION_DESCRIPTION" desc="Text describing how the Lite mode feature works. Seen only before the user has enabled the feature."> When Lite mode is on, Chrome uses Google servers to make pages load faster. Lite mode rewrites very slow pages to load only essential content. Lite mode does not apply to Incognito tabs. @@ -1305,7 +1305,7 @@ Browse faster. Use less data. </message> <message name="IDS_DATA_REDUCTION_PROMO_SUMMARY" desc="Description for the promo inviting users to enable Lite mode" > - In Lite mode, Chrome loads pages faster and uses up to 60% less data. Google's cloud technology optimizes the pages you visit. + In Lite mode, Chrome loads pages faster and uses up to 60\% less data. Google's cloud technology optimizes the pages you visit. </message> <message name="IDS_DATA_REDUCTION_ENABLE_BUTTON" desc="Button the user presses if they want to enable Lite mode" > Turn on Lite mode
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageTest.java index 4ff3cce..b692212c 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageTest.java
@@ -54,7 +54,7 @@ new ExploreSitesCategory(i, i, "Category #" + Integer.toString(i)); for (int j = 0; j < 8; j++) { ExploreSitesSite site = new ExploreSitesSite( - i * 8 + j, j, "Site #" + Integer.toString(j), "https://example.com/"); + i * 8 + j, "Site #" + Integer.toString(j), "https://example.com/", false); category.addSite(site); } categoryList.add(category);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java index 746bce5..290e9aba 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/OAuth2TokenServiceIntegrationTest.java
@@ -20,6 +20,7 @@ import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.test.util.ApplicationData; +import org.chromium.chrome.test.util.browser.signin.SigninTestUtil; import org.chromium.components.signin.AccountIdProvider; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.ChromeSigninController; @@ -88,6 +89,7 @@ mOAuth2TokenService.validateAccounts(false); }); SigninHelper.resetSharedPrefs(); + SigninTestUtil.resetSigninState(); } private void mapAccountNamesToIds() {
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryUnitTest.java index ccd1f74..4afc8be 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesCategoryUnitTest.java
@@ -5,6 +5,8 @@ package org.chromium.chrome.browser.explore_sites; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; @@ -19,7 +21,6 @@ @Test public void testAddSite() { final int id = 1; - final int tileIndex = 3; @ExploreSitesCategory.CategoryType final int type = ExploreSitesCategory.CategoryType.SCIENCE; final int siteId = 100; @@ -28,15 +29,17 @@ final String categoryTitle = "Movies"; ExploreSitesCategory category = new ExploreSitesCategory(id, type, categoryTitle); - category.addSite(new ExploreSitesSite(siteId, tileIndex, title, url)); + category.addSite(new ExploreSitesSite(siteId, title, url, true)); // blacklisted + category.addSite(new ExploreSitesSite(siteId, title, url, false)); // not blacklisted assertEquals(id, category.getId()); assertEquals(type, category.getType()); - assertEquals(1, category.getSites().size()); + assertEquals(2, category.getSites().size()); + assertEquals(1, category.getNumDisplayed()); assertEquals(siteId, category.getSites().get(0).getModel().get(ExploreSitesSite.ID_KEY)); - assertEquals(tileIndex, - category.getSites().get(0).getModel().get(ExploreSitesSite.TILE_INDEX_KEY)); assertEquals(title, category.getSites().get(0).getModel().get(ExploreSitesSite.TITLE_KEY)); assertEquals(url, category.getSites().get(0).getModel().get(ExploreSitesSite.URL_KEY)); + assertTrue(category.getSites().get(0).getModel().get(ExploreSitesSite.BLACKLISTED_KEY)); + assertFalse(category.getSites().get(1).getModel().get(ExploreSitesSite.BLACKLISTED_KEY)); } }
diff --git a/chrome/android/profiles/newest.txt b/chrome/android/profiles/newest.txt index 2a9dbb0..1d10f5a 100644 --- a/chrome/android/profiles/newest.txt +++ b/chrome/android/profiles/newest.txt
@@ -1 +1 @@ -chromeos-chrome-amd64-73.0.3636.0_rc-r1.afdo.bz2 \ No newline at end of file +chromeos-chrome-amd64-73.0.3637.0_rc-r1.afdo.bz2 \ No newline at end of file
diff --git a/chrome/app/app_management_strings.grdp b/chrome/app/app_management_strings.grdp index badceea..978271d 100644 --- a/chrome/app/app_management_strings.grdp +++ b/chrome/app/app_management_strings.grdp
@@ -4,8 +4,11 @@ <message name="IDS_APP_MANAGEMENT_APP_LIST_TITLE" desc="Title of app list card on main app management page."> Recently opened apps </message> + <message name="IDS_APP_MANAGEMENT_LESS_APPS" desc="Show less for apps."> + Show less + </message> <message name="IDS_APP_MANAGEMENT_MORE_APPS" desc="Label for more apps button at bottom of app list card."> - See more apps + Show <ph name="NUMBER_OF_MORE_APPS">$1<ex>4</ex></ph> more apps </message> <message name="IDS_APP_MANAGEMENT_SEARCH_PROMPT" desc="Prompt in search bar of main app management page."> Search Settings
diff --git a/chrome/app_shim/app_shim_controller.mm b/chrome/app_shim/app_shim_controller.mm index 35dc669e..2e9a22ce 100644 --- a/chrome/app_shim/app_shim_controller.mm +++ b/chrome/app_shim/app_shim_controller.mm
@@ -201,7 +201,7 @@ } void AppShimController::Close() { - [NSApp terminate:nil]; + [delegate_ terminateNow]; } bool AppShimController::SendFocusApp(apps::AppShimFocusType focus_type,
diff --git a/chrome/app_shim/app_shim_delegate.h b/chrome/app_shim/app_shim_delegate.h index b4d4babb..235e7c3 100644 --- a/chrome/app_shim/app_shim_delegate.h +++ b/chrome/app_shim/app_shim_delegate.h
@@ -18,6 +18,8 @@ : NSObject<NSApplicationDelegate, NSUserInterfaceValidations> { @private AppShimController* appShimController_; // Weak, initially NULL. + BOOL terminateNow_; + BOOL terminateRequested_; std::vector<base::FilePath> filesToOpenAtStartup_; } @@ -34,6 +36,10 @@ // Takes an array of NSString*. - (void)openFiles:(NSArray*)filename; +// Terminate immediately. This is necessary as we override terminate: to send +// a QuitApp message. +- (void)terminateNow; + @end #endif // CHROME_APP_SHIM_APP_SHIM_DELEGATE_H_
diff --git a/chrome/app_shim/app_shim_delegate.mm b/chrome/app_shim/app_shim_delegate.mm index 40ff6f1e..fb3d80e 100644 --- a/chrome/app_shim/app_shim_delegate.mm +++ b/chrome/app_shim/app_shim_delegate.mm
@@ -67,11 +67,13 @@ - (NSApplicationTerminateReply)applicationShouldTerminate: (NSApplication*)sender { - // Send a last message to the host indicating that the host should close all - // associated browser windows. - if (appShimController_) - appShimController_->host()->QuitApp(); - return NSTerminateNow; + if (terminateNow_ || !appShimController_) + return NSTerminateNow; + + appShimController_->host()->QuitApp(); + // Wait for the channel to close before terminating. + terminateRequested_ = YES; + return NSTerminateLater; } - (void)applicationWillHide:(NSNotification*)notification { @@ -84,6 +86,16 @@ appShimController_->host()->SetAppHidden(false); } +- (void)terminateNow { + if (terminateRequested_) { + [NSApp replyToApplicationShouldTerminate:NSTerminateNow]; + return; + } + + terminateNow_ = YES; + [NSApp terminate:nil]; +} + - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item { return NO; }
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index f4d9dd5..0a665bcf 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -5009,7 +5009,6 @@ "//chrome/browser/engagement:mojo_bindings_js", "//chrome/browser/media:mojo_bindings_js", "//chrome/browser/resources/ssl/ssl_error_assistant:make_ssl_error_assistant_protobuf", - "//chrome/browser/ui/webui/app_management:mojo_bindings_js", "//chrome/browser/ui/webui/bluetooth_internals:mojo_bindings_js", "//chrome/browser/ui/webui/interventions_internals:mojo_bindings_js", "//chrome/browser/ui/webui/md_downloads:mojo_bindings_js", @@ -5058,6 +5057,8 @@ "//chrome/browser/ui/webui/eoc_internals:mojo_bindings_js", "//chrome/browser/ui/webui/snippets_internals:mojo_bindings_js", ] + } else { + deps += [ "//chrome/browser/ui/webui/app_management:mojo_bindings_js" ] } if (!is_android && optimize_webui) {
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index a6ed925..fdd59a7 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -4435,6 +4435,13 @@ FEATURE_VALUE_TYPE( autofill::features::kAutofillAlwaysShowServerCardsInSyncTransport)}, #endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) + +#if BUILDFLAG(ENABLE_PRINT_PREVIEW) && defined(OS_MACOSX) + {"enable-custom-mac-paper-sizes", + flag_descriptions::kEnableCustomMacPaperSizesName, + flag_descriptions::kEnableCustomMacPaperSizesDescription, kOsMac, + FEATURE_VALUE_TYPE(printing::features::kEnableCustomMacPaperSizes)}, +#endif }; class FlagsStateSingleton {
diff --git a/chrome/browser/android/download/download_controller.cc b/chrome/browser/android/download/download_controller.cc index c65e261..166981e1 100644 --- a/chrome/browser/android/download/download_controller.cc +++ b/chrome/browser/android/download/download_controller.cc
@@ -301,6 +301,7 @@ } void DownloadController::AboutToResumeDownload(DownloadItem* download_item) { + download_item->RemoveObserver(this); download_item->AddObserver(this); // If a download is resumed from an interrupted state, record its strong @@ -411,8 +412,6 @@ switch (item->GetState()) { case DownloadItem::IN_PROGRESS: { Java_DownloadController_onDownloadUpdated(env, j_item); - if (item->IsPaused()) - item->RemoveObserver(this); break; } case DownloadItem::COMPLETE: @@ -438,7 +437,6 @@ // resume in this case. Java_DownloadController_onDownloadInterrupted(env, j_item, IsInterruptedDownloadAutoResumable(item)); - item->RemoveObserver(this); break; case DownloadItem::MAX_DOWNLOAD_STATE: NOTREACHED();
diff --git a/chrome/browser/android/explore_sites/explore_sites_bridge.cc b/chrome/browser/android/explore_sites/explore_sites_bridge.cc index 2418eb8..0e805b3 100644 --- a/chrome/browser/android/explore_sites/explore_sites_bridge.cc +++ b/chrome/browser/android/explore_sites/explore_sites_bridge.cc
@@ -57,7 +57,8 @@ for (auto& site : category.sites) { Java_ExploreSitesSite_createSiteInCategory( env, site.site_id, ConvertUTF8ToJavaString(env, site.title), - ConvertUTF8ToJavaString(env, site.url.spec()), j_category); + ConvertUTF8ToJavaString(env, site.url.spec()), site.is_blacklisted, + j_category); } } base::android::RunObjectCallbackAndroid(j_callback_obj, j_result_obj);
diff --git a/chrome/browser/android/explore_sites/explore_sites_service_impl_unittest.cc b/chrome/browser/android/explore_sites/explore_sites_service_impl_unittest.cc index 8687d97..3ca81ba 100644 --- a/chrome/browser/android/explore_sites/explore_sites_service_impl_unittest.cc +++ b/chrome/browser/android/explore_sites/explore_sites_service_impl_unittest.cc
@@ -539,7 +539,9 @@ &ExploreSitesServiceImplTest::CatalogCallback, base::Unretained(this))); PumpLoop(); - EXPECT_EQ(1U, database_categories()->at(0).sites.size()); + EXPECT_EQ(2U, database_categories()->at(0).sites.size()); + EXPECT_TRUE(database_categories()->at(0).sites.at(0).is_blacklisted); + EXPECT_FALSE(database_categories()->at(0).sites.at(1).is_blacklisted); } } // namespace explore_sites
diff --git a/chrome/browser/android/explore_sites/explore_sites_types.cc b/chrome/browser/android/explore_sites/explore_sites_types.cc index a483e08..50d9385 100644 --- a/chrome/browser/android/explore_sites/explore_sites_types.cc +++ b/chrome/browser/android/explore_sites/explore_sites_types.cc
@@ -9,8 +9,13 @@ ExploreSitesSite::ExploreSitesSite(int site_id, int category_id, GURL url, - std::string title) - : site_id(site_id), category_id(category_id), url(url), title(title) {} + std::string title, + bool is_blacklisted) + : site_id(site_id), + category_id(category_id), + url(url), + title(title), + is_blacklisted(is_blacklisted) {} ExploreSitesSite::ExploreSitesSite(ExploreSitesSite&& other) = default;
diff --git a/chrome/browser/android/explore_sites/explore_sites_types.h b/chrome/browser/android/explore_sites/explore_sites_types.h index 3844da5..4d52159 100644 --- a/chrome/browser/android/explore_sites/explore_sites_types.h +++ b/chrome/browser/android/explore_sites/explore_sites_types.h
@@ -22,7 +22,11 @@ // Image data is not represented here because it is requested separately from // the UI layer. struct ExploreSitesSite { - ExploreSitesSite(int site_id, int category_id, GURL url, std::string title); + ExploreSitesSite(int site_id, + int category_id, + GURL url, + std::string title, + bool is_blacklisted); ExploreSitesSite(ExploreSitesSite&& other); virtual ~ExploreSitesSite(); @@ -30,6 +34,7 @@ int category_id; GURL url; std::string title; + bool is_blacklisted; DISALLOW_COPY_AND_ASSIGN(ExploreSitesSite); };
diff --git a/chrome/browser/android/explore_sites/get_catalog_task.cc b/chrome/browser/android/explore_sites/get_catalog_task.cc index 816b81c..580e728f 100644 --- a/chrome/browser/android/explore_sites/get_catalog_task.cc +++ b/chrome/browser/android/explore_sites/get_catalog_task.cc
@@ -18,10 +18,12 @@ WHERE version_token = ? ORDER BY category_id ASC;)"; -static const char kSelectSiteSql[] = R"(SELECT site_id, sites.url, title +static const char kSelectSiteSql[] = + R"(SELECT site_id, sites.url, title, + site_blacklist.url IS NOT NULL as blacklisted FROM sites LEFT JOIN site_blacklist ON (sites.url = site_blacklist.url) -WHERE category_id = ? AND site_blacklist.url IS NULL;)"; +WHERE category_id = ? ;)"; const char kDeleteSiteSql[] = R"(DELETE FROM sites WHERE category_id NOT IN @@ -134,10 +136,12 @@ site_statement.BindInt64(0, category.category_id); while (site_statement.Step()) { - category.sites.emplace_back(site_statement.ColumnInt(0), // site_id - category.category_id, - GURL(site_statement.ColumnString(1)), // url - site_statement.ColumnString(2)); // title + category.sites.emplace_back( + site_statement.ColumnInt(0), // site_id + category.category_id, + GURL(site_statement.ColumnString(1)), // url + site_statement.ColumnString(2), // title + site_statement.ColumnBool(3)); // is_blacklisted } if (!site_statement.Succeeded()) return std::make_pair(GetCatalogStatus::kFailed, nullptr);
diff --git a/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc b/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc index a210f04..f324f31e 100644 --- a/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc +++ b/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc
@@ -29,7 +29,7 @@ EXPECT_EQ(2U, catalog->size()); ExploreSitesCategory* cat = &catalog->at(0); - EXPECT_EQ(3, cat->category_id); + EXPECT_EQ(4, cat->category_id); EXPECT_EQ("5678", cat->version_token); EXPECT_EQ(1, cat->category_type); EXPECT_EQ("label_1", cat->label); @@ -37,11 +37,12 @@ EXPECT_EQ(1U, cat->sites.size()); ExploreSitesSite* site = &cat->sites[0]; EXPECT_EQ("https://www.example.com/1", site->url.spec()); - EXPECT_EQ(3, site->category_id); + EXPECT_EQ(4, site->category_id); EXPECT_EQ("example_1", site->title); + EXPECT_FALSE(site->is_blacklisted); cat = &catalog->at(1); - EXPECT_EQ(4, cat->category_id); + EXPECT_EQ(5, cat->category_id); EXPECT_EQ("5678", cat->version_token); EXPECT_EQ(2, cat->category_type); EXPECT_EQ("label_2", cat->label); @@ -49,17 +50,18 @@ EXPECT_EQ(1U, cat->sites.size()); site = &cat->sites[0]; EXPECT_EQ("https://www.example.com/2", site->url.spec()); - EXPECT_EQ(4, site->category_id); + EXPECT_EQ(5, site->category_id); EXPECT_EQ("example_2", site->title); + EXPECT_FALSE(site->is_blacklisted); } -// Same as above, categories with no sites left after blacklisting are removed. +// Same as above, sites blacklisted are clearly marked. void ValidateBlacklistTestingCatalog(GetCatalogTask::CategoryList* catalog) { EXPECT_FALSE(catalog == nullptr); - EXPECT_EQ(1U, catalog->size()); + EXPECT_EQ(2U, catalog->size()); ExploreSitesCategory* cat = &catalog->at(0); - EXPECT_EQ(3, cat->category_id); + EXPECT_EQ(4, cat->category_id); EXPECT_EQ("5678", cat->version_token); EXPECT_EQ(1, cat->category_type); EXPECT_EQ("label_1", cat->label); @@ -67,8 +69,22 @@ EXPECT_EQ(1U, cat->sites.size()); ExploreSitesSite* site = &cat->sites[0]; EXPECT_EQ("https://www.example.com/1", site->url.spec()); - EXPECT_EQ(3, site->category_id); + EXPECT_EQ(4, site->category_id); EXPECT_EQ("example_1", site->title); + EXPECT_FALSE(site->is_blacklisted); + + cat = &catalog->at(1); + EXPECT_EQ(5, cat->category_id); + EXPECT_EQ("5678", cat->version_token); + EXPECT_EQ(2, cat->category_type); + EXPECT_EQ("label_2", cat->label); + + EXPECT_EQ(1U, cat->sites.size()); + site = &cat->sites[0]; + EXPECT_EQ("https://www.example.com/2", site->url.spec()); + EXPECT_EQ(5, site->category_id); + EXPECT_EQ("example_2", site->title); + EXPECT_TRUE(site->is_blacklisted); } void ExpectSuccessGetCatalogResult( @@ -135,9 +151,9 @@ }; void ExploreSitesGetCatalogTaskTest::PopulateTestingCatalog() { - // Populate a catalog with test data. There are two out-dated categories and - // two current categories. Each category (of the 4) has a site, but only the - // current categories should be returned. + // Populate a catalog with test data. There are three out-dated categories + // and three current categories. Each category (of the 6) has a site except + // two, but only the current categories should be returned. ExecuteSync(base::BindLambdaForTesting([](sql::Database* db) { sql::MetaTable meta_table; ExploreSitesSchema::InitMetaTable(db, &meta_table); @@ -149,8 +165,10 @@ VALUES (1, "1234", 1, "label_1"), -- older catalog (2, "1234", 2, "label_2"), -- older catalog -(3, "5678", 1, "label_1"), -- current catalog -(4, "5678", 2, "label_2"); -- current catalog)")); +(3, "1234", 3, "label_3"), -- older catalog +(4, "5678", 1, "label_1"), -- current catalog +(5, "5678", 2, "label_2"), -- current catalog +(6, "5678", 3, "label_3"); -- current catalog)")); if (!insert.Run()) return false; @@ -160,8 +178,8 @@ VALUES (1, "https://www.example.com/1", 1, "example_old_1"), (2, "https://www.example.com/2", 2, "example_old_2"), -(3, "https://www.example.com/1", 3, "example_1"), -(4, "https://www.example.com/2", 4, "example_2"); +(3, "https://www.example.com/1", 4, "example_1"), +(4, "https://www.example.com/2", 5, "example_2"); )")); return insert_sites.Run(); })); @@ -257,13 +275,13 @@ RunTask(&task); // Since |update_current| is false, we should not have changed any rows in the // DB. - EXPECT_EQ(4, GetNumberOfCategoriesInDB()); + EXPECT_EQ(6, GetNumberOfCategoriesInDB()); EXPECT_EQ(4, GetNumberOfSitesInDB()); } // This tests that sites on the blacklist do not show up when we do a get // catalog task. -TEST_F(ExploreSitesGetCatalogTaskTest, BlasklistedSitesDoNotAppear) { +TEST_F(ExploreSitesGetCatalogTaskTest, BlasklistedSitesMarkedBlacklisted) { BlacklistSite("https://www.example.com/2"); PopulateTestingCatalog(); GetCatalogTask task(store(), false, @@ -283,7 +301,7 @@ EXPECT_EQ(std::make_pair(std::string("5678"), std::string()), GetCurrentAndDownloadingVersion()); // The task should have pruned the database. - EXPECT_EQ(2, GetNumberOfCategoriesInDB()); + EXPECT_EQ(3, GetNumberOfCategoriesInDB()); EXPECT_EQ(2, GetNumberOfSitesInDB()); } @@ -298,7 +316,7 @@ EXPECT_EQ(std::make_pair(std::string("5678"), std::string("1234")), GetCurrentAndDownloadingVersion()); - EXPECT_EQ(4, GetNumberOfCategoriesInDB()); + EXPECT_EQ(6, GetNumberOfCategoriesInDB()); EXPECT_EQ(4, GetNumberOfSitesInDB()); }
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 96cc832..5c9e355 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -179,6 +179,8 @@ <include name="IDR_MD_DOWNLOADS_CONSTANTS_JS" file="resources\md_downloads\constants.js" type="BINDATA" /> <include name="IDR_MD_DOWNLOADS_DOWNLOADS_JS" file="resources\md_downloads\downloads.js" type="BINDATA" /> <include name="IDR_MD_DOWNLOADS_I18N_SETUP_HTML" file="resources\md_downloads\i18n_setup.html" type="BINDATA" /> + <include name="IDR_MD_DOWNLOADS_ICON_LOADER_HTML" file="resources\md_downloads\icon_loader.html" type="BINDATA" /> + <include name="IDR_MD_DOWNLOADS_ICON_LOADER_JS" file="resources\md_downloads\icon_loader.js" type="BINDATA" /> <include name="IDR_MD_DOWNLOADS_ICONS_HTML" file="resources\md_downloads\icons.html" type="BINDATA" /> <include name="IDR_MD_DOWNLOADS_ITEM_HTML" file="resources\md_downloads\item.html" type="BINDATA" /> <include name="IDR_MD_DOWNLOADS_ITEM_JS" file="resources\md_downloads\item.js" type="BINDATA" /> @@ -215,15 +217,25 @@ </if> <!-- App Management. --> - <include name="IDR_APP_MANAGEMENT_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\app_management\app_management.mojom-lite.js" use_base_dir="false" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_APP_HTML" file="resources\app_management\app.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_APP_JS" file="resources\app_management\app.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML" file="resources\app_management\browser_proxy.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_JS" file="resources\app_management\browser_proxy.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS" file="resources\app_management\fake_page_handler.js" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_INDEX_HTML" file="resources\app_management\index.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_MAIN_VIEW_HTML" file="resources\app_management\main_view.html" type="BINDATA" /> - <include name="IDR_APP_MANAGEMENT_MAIN_VIEW_JS" file="resources\app_management\main_view.js" type="BINDATA" /> + <if expr="not is_android"> + <include name="IDR_APP_MANAGEMENT_BIG_BUFFER_MOJO_LITE_JS" file="${root_gen_dir}\mojo\public\mojom\base\big_buffer.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\interfaces\bitmap.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS" file="${root_gen_dir}\skia\public\interfaces\image_info.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS" file="${root_gen_dir}\ui\gfx\image\mojo\image.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_MOJO_LITE_JS" file="${root_gen_dir}\chrome\browser\ui\webui\app_management\app_management.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS" file="${root_gen_dir}\chrome\services\app_service\public\mojom\types.mojom-lite.js" use_base_dir="false" type="BINDATA" /> + + <include name="IDR_APP_MANAGEMENT_APP_HTML" file="resources\app_management\app.html" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_APP_JS" file="resources\app_management\app.js" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML" file="resources\app_management\browser_proxy.html" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_BROWSER_PROXY_JS" file="resources\app_management\browser_proxy.js" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_CONSTANTS_HTML" file="resources\app_management\constants.html" type="BINDATA"/> + <include name="IDR_APP_MANAGEMENT_CONSTANTS_JS" file="resources\app_management\constants.js" type="BINDATA"/> + <include name="IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS" file="resources\app_management\fake_page_handler.js" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_INDEX_HTML" file="resources\app_management\index.html" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_MAIN_VIEW_HTML" file="resources\app_management\main_view.html" type="BINDATA" /> + <include name="IDR_APP_MANAGEMENT_MAIN_VIEW_JS" file="resources\app_management\main_view.js" type="BINDATA" /> + </if> <if expr="not is_android"> <!-- MD Bookmarks. -->
diff --git a/chrome/browser/chrome_service_worker_browsertest.cc b/chrome/browser/chrome_service_worker_browsertest.cc index 640ba0c..86dd477f 100644 --- a/chrome/browser/chrome_service_worker_browsertest.cc +++ b/chrome/browser/chrome_service_worker_browsertest.cc
@@ -282,6 +282,15 @@ " event.waitUntil(self.clients.claim());" "};" "this.onfetch = function(event) {" + // Ignore the default favicon request. The default favicon request + // is sent after the page loading is finished, and we can't + // control the timing of the request. If the request is sent after + // clients.claim() is called, fetch event for the default favicon + // request is triggered and the tests become flaky. See + // https://crbug.com/912543. + " if (event.request.url.endsWith('/favicon.ico')) {" + " return;" + " }" " event.respondWith(" " self.clients.matchAll().then(function(clients) {" " clients.forEach(function(client) {"
diff --git a/chrome/browser/chromeos/arc/tracing/DEPS b/chrome/browser/chromeos/arc/tracing/DEPS new file mode 100644 index 0000000..af06dabc --- /dev/null +++ b/chrome/browser/chromeos/arc/tracing/DEPS
@@ -0,0 +1,4 @@ +include_rules = [ + "+third_party/perfetto/include", + "+third_party/perfetto/protos", +]
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc index f45bb39d..13e23fd 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.cc
@@ -4,11 +4,14 @@ #include "chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h" +#include <set> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file.h" #include "base/logging.h" #include "base/memory/singleton.h" +#include "base/no_destructor.h" #include "base/posix/unix_domain_socket.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" @@ -21,6 +24,14 @@ #include "content/public/browser/browser_thread.h" #include "content/public/common/service_manager_connection.h" #include "mojo/public/cpp/system/platform_handle.h" +#include "services/tracing/public/mojom/constants.mojom.h" +#include "services/tracing/public/mojom/perfetto_service.mojom.h" +#include "third_party/perfetto/include/perfetto/tracing/core/trace_writer.h" +#include "third_party/perfetto/protos/perfetto/trace/chrome/chrome_trace_event.pbzero.h" +#include "third_party/perfetto/protos/perfetto/trace/trace_packet.pbzero.h" + +using ChromeEventBundleHandle = + protozero::MessageHandle<perfetto::protos::pbzero::ChromeEventBundle>; namespace arc { @@ -57,6 +68,211 @@ ~ArcTracingBridgeFactory() override = default; }; +// Perfetto data source which coordinates ARC tracing sessions with perfetto's +// ProducerClient when perfetto is used as the tracing backend. +class ArcTracingDataSource : public tracing::ProducerClient::DataSourceBase { + public: + static ArcTracingDataSource* GetInstance() { + static base::NoDestructor<ArcTracingDataSource> instance; + return instance.get(); + } + + // Called after constructing |bridge|. + void RegisterBridgeOnUI(ArcTracingBridge* bridge) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(ArcTracingBridge::State::kDisabled, bridge->state()); + bool success = bridges_.insert(bridge).second; + DCHECK(success); + + if (producer_client_) { + // We're currently tracing, so start the new bridge, too. + // |this| never gets destructed, so it's OK to bind an unretained pointer. + bridge->StartTracing( + data_source_config_.trace_config, + base::BindOnce(&ArcTracingDataSource::OnTracingStartedOnUI, + base::Unretained(this))); + } + } + + // Called when destructing |bridge|. + void UnregisterBridgeOnUI(ArcTracingBridge* bridge) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + const size_t erase_count = bridges_.erase(bridge); + DCHECK_EQ(1u, erase_count); + + // Make sure we don't continue to wait for any of the bridge's callbacks. + OnTracingStartedOnUI(false /*success*/); + OnTraceDataOnUI(std::string() /*data*/); + } + + private: + friend class base::NoDestructor<ArcTracingDataSource>; + + ArcTracingDataSource() + : DataSourceBase(tracing::mojom::kArcTraceDataSourceName), + perfetto_task_runner_(tracing::ProducerClient::Get()->GetTaskRunner()) { + tracing::ProducerClient::Get()->AddDataSource(this); + } + + // Note that ArcTracingDataSource is a singleton that's never destroyed. + ~ArcTracingDataSource() override = default; + + // tracing::ProducerClient::DataSourceBase. + void StartTracing( + tracing::ProducerClient* producer_client, + const tracing::mojom::DataSourceConfig& data_source_config) override { + // |this| never gets destructed, so it's OK to bind an unretained pointer. + // |producer_client| is a singleton that is never destroyed. + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ArcTracingDataSource::StartTracingOnUI, + base::Unretained(this), producer_client, + data_source_config)); + } + + void StopTracing(base::OnceClosure stop_complete_callback) override { + // |this| never gets destructed, so it's OK to bind an unretained pointer. + base::PostTaskWithTraits( + FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&ArcTracingDataSource::StopTracingOnUI, + base::Unretained(this), + std::move(stop_complete_callback))); + } + + void Flush(base::RepeatingClosure flush_complete_callback) override { + // ARC's tracing service doesn't currently support flushing while recording. + flush_complete_callback.Run(); + } + + // Starts all registered data sources. + void StartTracingOnUI( + tracing::ProducerClient* producer_client, + const tracing::mojom::DataSourceConfig& data_source_config) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + DCHECK(!producer_client_); + producer_client_ = producer_client; + data_source_config_ = data_source_config; + + for (ArcTracingBridge* bridge : bridges_) { + // |this| never gets destructed, so it's OK to bind an unretained pointer. + bridge->StartTracing( + data_source_config_.trace_config, + base::BindOnce(&ArcTracingDataSource::OnTracingStartedOnUI, + base::Unretained(this))); + } + } + + // Stops all registered data sources. Calls |stop_complete_callback| when all + // data sources have stopped. + void StopTracingOnUI(base::OnceClosure stop_complete_callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + // We may receive a StopTracing without StartTracing. + if (!producer_client_) + return; + + // We may still be in startup. In this case, store a callback to rerun + // StopTracingOnUI() once startup is complete. + if (IsAnyBridgeStarting()) { + DCHECK(!pending_stop_tracing_); + pending_stop_tracing_ = base::BindOnce( + &ArcTracingDataSource::StopTracingOnUI, base::Unretained(this), + std::move(stop_complete_callback)); + return; + } + + stop_complete_callback_ = std::move(stop_complete_callback); + + bool did_request_stop = false; + for (ArcTracingBridge* bridge : bridges_) { + if (bridge->state() != ArcTracingBridge::State::kEnabled) + continue; + // |this| never gets destructed, so it's OK to bind an unretained pointer. + bridge->StopAndFlush(base::BindOnce( + &ArcTracingDataSource::OnTraceDataOnUI, base::Unretained(this))); + did_request_stop = true; + } + + // There may not have been any bridges left in State::kEnabled. + if (!did_request_stop) { + perfetto_task_runner_->PostTask(FROM_HERE, + std::move(stop_complete_callback_)); + } + } + + // Called by each bridge when it has started tracing. Also called when a + // bridge is unregisted. + void OnTracingStartedOnUI(bool success) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (!IsAnyBridgeStarting() && pending_stop_tracing_) + std::move(pending_stop_tracing_).Run(); + } + + // Called by each bridge when it has stopped tracing. Also called when a + // bridge is unregisted. Records the supplied |data| into the + // |producer_client_|'s buffer. + void OnTraceDataOnUI(const std::string& data) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + // When a bridge unregisters, we may not actually be stopping. + if (!stop_complete_callback_) + return; + + DCHECK(producer_client_); + + if (!data.empty()) { + std::unique_ptr<perfetto::TraceWriter> trace_writer = + producer_client_->CreateTraceWriter( + data_source_config_.target_buffer); + DCHECK(trace_writer); + perfetto::TraceWriter::TracePacketHandle trace_packet_handle = + trace_writer->NewTracePacket(); + ChromeEventBundleHandle event_bundle = + ChromeEventBundleHandle(trace_packet_handle->set_chrome_events()); + auto* legacy_json_trace = event_bundle->add_legacy_json_trace(); + legacy_json_trace->set_type( + perfetto::protos::pbzero::ChromeLegacyJsonTrace::USER_TRACE); + legacy_json_trace->set_data(data.data(), data.length()); + } + + if (AreAllBridgesStopped()) { + producer_client_ = nullptr; + perfetto_task_runner_->PostTask(FROM_HERE, + std::move(stop_complete_callback_)); + } + } + + bool IsAnyBridgeStarting() const { + for (ArcTracingBridge* bridge : bridges_) { + if (bridge->state() == ArcTracingBridge::State::kStarting) + return true; + } + return false; + } + + bool AreAllBridgesStopped() const { + for (ArcTracingBridge* bridge : bridges_) { + if (bridge->state() != ArcTracingBridge::State::kDisabled) + return false; + } + return true; + } + + base::SequencedTaskRunner* perfetto_task_runner_; + std::set<ArcTracingBridge*> bridges_; + // In case StopTracing() is called before tracing was started for all bridges, + // this stores a callback to StopTracing() that's executed when all bridges + // have started. + base::OnceClosure pending_stop_tracing_; + // Called when all bridges have completed stopping, notifying ProducerClient. + base::OnceClosure stop_complete_callback_; + tracing::ProducerClient* producer_client_ = nullptr; + tracing::mojom::DataSourceConfig data_source_config_; + + DISALLOW_COPY_AND_ASSIGN(ArcTracingDataSource); +}; + } // namespace struct ArcTracingBridge::Category { @@ -74,18 +290,23 @@ ArcTracingBridge::ArcTracingBridge(content::BrowserContext* context, ArcBridgeService* bridge_service) - : BaseAgent( - content::ServiceManagerConnection::GetForProcess()->GetConnector(), - kChromeTraceEventLabel, - tracing::mojom::TraceDataType::ARRAY, - base::kNullProcessId), - arc_bridge_service_(bridge_service), + : arc_bridge_service_(bridge_service), + agent_(this), + reader_(std::make_unique<ArcTracingReader>()), weak_ptr_factory_(this) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); arc_bridge_service_->tracing()->AddObserver(this); + ArcTracingDataSource::GetInstance()->RegisterBridgeOnUI(this); } ArcTracingBridge::~ArcTracingBridge() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + ArcTracingDataSource::GetInstance()->UnregisterBridgeOnUI(this); arc_bridge_service_->tracing()->RemoveObserver(this); + + // Delete the reader on the IO thread. + base::CreateSingleThreadTaskRunnerWithTraits({content::BrowserThread::IO}) + ->DeleteSoon(FROM_HERE, reader_.release()); } void ArcTracingBridge::OnConnectionReady() { @@ -115,10 +336,16 @@ } void ArcTracingBridge::StartTracing(const std::string& config, - base::TimeTicks coordinator_time, - Agent::StartTracingCallback callback) { + SuccessCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + if (state_ != State::kDisabled) { + DLOG(WARNING) << "Cannot start tracing, it is already enabled."; + std::move(callback).Run(false /*success*/); + return; + } + state_ = State::kStarting; + base::trace_event::TraceConfig trace_config(config); base::ScopedFD write_fd, read_fd; @@ -126,20 +353,14 @@ trace_config.IsSystraceEnabled() && CreateSocketPair(&read_fd, &write_fd); if (!success) { - // Use PostTask as the convention of TracingAgent. The caller expects - // callback to be called after this function returns. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), false /* success */)); + std::move(callback).Run(false /*success*/); return; } mojom::TracingInstance* tracing_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->tracing(), StartTracing); if (!tracing_instance) { - // Use PostTask as the convention of TracingAgent. The caller expects - // callback to be called after this function returns. - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(std::move(callback), false)); + std::move(callback).Run(false /*success*/); return; } @@ -149,59 +370,111 @@ selected_categories.push_back(category.name); } - tracing_instance->StartTracing(selected_categories, - mojo::WrapPlatformFile(write_fd.release()), - std::move(callback)); + tracing_instance->StartTracing( + selected_categories, mojo::WrapPlatformFile(write_fd.release()), + base::BindOnce(&ArcTracingBridge::OnArcTracingStarted, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + // |reader_| will be destroyed after us on the IO thread, so it's OK to use an + // unretained pointer. base::PostTaskWithTraits( FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&ArcTracingReader::StartTracing, reader_.GetWeakPtr(), - std::move(read_fd))); + base::BindOnce(&ArcTracingReader::StartTracing, + base::Unretained(reader_.get()), std::move(read_fd))); } -void ArcTracingBridge::StopAndFlush(tracing::mojom::RecorderPtr recorder) { +void ArcTracingBridge::OnArcTracingStarted(SuccessCallback callback, + bool success) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(State::kStarting, state_); + state_ = success ? State::kEnabled : State::kDisabled; + std::move(callback).Run(success); +} + +void ArcTracingBridge::StopAndFlush(TraceDataCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (is_stopping_) { - DLOG(WARNING) << "Already working on stopping ArcTracingAgent."; + if (state_ != State::kEnabled) { + DLOG(WARNING) << "Cannot stop tracing, it is not enabled."; + std::move(callback).Run(std::string()); return; } - is_stopping_ = true; - recorder_ = std::move(recorder); + state_ = State::kStopping; mojom::TracingInstance* tracing_instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->tracing(), StopTracing); if (!tracing_instance) { - OnArcTracingStopped(false); + OnArcTracingStopped(std::move(callback), false); return; } - tracing_instance->StopTracing(base::BindOnce( - &ArcTracingBridge::OnArcTracingStopped, weak_ptr_factory_.GetWeakPtr())); + tracing_instance->StopTracing( + base::BindOnce(&ArcTracingBridge::OnArcTracingStopped, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } -void ArcTracingBridge::OnArcTracingStopped(bool success) { +void ArcTracingBridge::OnArcTracingStopped( + TraceDataCallback tracing_stopped_callback, + bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(State::kStopping, state_); if (!success) { - DLOG(WARNING) << "Failed to stop ARC tracing."; - is_stopping_ = false; - return; + DLOG(WARNING) << "Failed to stop ARC tracing, closing file anyway."; } - base::PostTaskWithTraits( + // |reader_| will be destroyed after us on the IO thread, so it's OK to use an + // unretained pointer. + base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&ArcTracingReader::StopTracing, reader_.GetWeakPtr(), - base::BindOnce(&ArcTracingBridge::OnTracingReaderStopped, - weak_ptr_factory_.GetWeakPtr()))); + base::BindOnce(&ArcTracingReader::StopTracing, + base::Unretained(reader_.get())), + base::BindOnce(&ArcTracingBridge::OnTracingReaderStopped, + weak_ptr_factory_.GetWeakPtr(), + std::move(tracing_stopped_callback))); } -void ArcTracingBridge::OnTracingReaderStopped(const std::string& data) { +void ArcTracingBridge::OnTracingReaderStopped( + TraceDataCallback tracing_stopped_callback, + const std::string& data) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_EQ(State::kStopping, state_); + state_ = State::kDisabled; + std::move(tracing_stopped_callback).Run(data); +} + +ArcTracingBridge::ArcTracingAgent::ArcTracingAgent(ArcTracingBridge* bridge) + : BaseAgent( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), + kChromeTraceEventLabel, + tracing::mojom::TraceDataType::ARRAY, + base::kNullProcessId), + bridge_(bridge) {} + +ArcTracingBridge::ArcTracingAgent::~ArcTracingAgent() = default; + +void ArcTracingBridge::ArcTracingAgent::StartTracing( + const std::string& config, + base::TimeTicks coordinator_time, + Agent::StartTracingCallback callback) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + bridge_->StartTracing(config, std::move(callback)); +} + +void ArcTracingBridge::ArcTracingAgent::StopAndFlush( + tracing::mojom::RecorderPtr recorder) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + recorder_ = std::move(recorder); + // |bridge_| owns us, so it's OK to pass an unretained pointer. + bridge_->StopAndFlush( + base::BindOnce(&ArcTracingAgent::OnTraceData, base::Unretained(this))); +} + +void ArcTracingBridge::ArcTracingAgent::OnTraceData(const std::string& data) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(recorder_); recorder_->AddChunk(data); recorder_.reset(); - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - is_stopping_ = false; } -ArcTracingBridge::ArcTracingReader::ArcTracingReader() - : weak_ptr_factory_(this) {} +ArcTracingBridge::ArcTracingReader::ArcTracingReader() = default; ArcTracingBridge::ArcTracingReader::~ArcTracingReader() { DCHECK(!fd_watcher_); @@ -210,9 +483,7 @@ void ArcTracingBridge::ArcTracingReader::StartTracing(base::ScopedFD read_fd) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); read_fd_ = std::move(read_fd); - // We don't use the weak pointer returned by |GetWeakPtr| to avoid using it - // on different task runner. Instead, we use |base::Unretained| here as - // |fd_watcher_| is always destroyed before |this| is destroyed. + // We own |fd_watcher_|, so it's OK to use an unretained pointer. fd_watcher_ = base::FileDescriptorWatcher::WatchReadable( read_fd_.get(), base::BindRepeating(&ArcTracingReader::OnTraceDataAvailable, @@ -248,8 +519,7 @@ ring_buffer_.SaveToBuffer(std::string(buf, n)); } -void ArcTracingBridge::ArcTracingReader::StopTracing( - base::OnceCallback<void(const std::string&)> callback) { +std::string ArcTracingBridge::ArcTracingReader::StopTracing() { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); fd_watcher_.reset(); read_fd_.reset(); @@ -265,13 +535,7 @@ } ring_buffer_.Clear(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(std::move(callback), data)); -} - -base::WeakPtr<ArcTracingBridge::ArcTracingReader> -ArcTracingBridge::ArcTracingReader::GetWeakPtr() { - return weak_ptr_factory_.GetWeakPtr(); + return data; } } // namespace arc
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h index 52791da..8b96821 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_bridge.h
@@ -19,6 +19,7 @@ #include "components/arc/connection_observer.h" #include "components/keyed_service/core/keyed_service.h" #include "services/tracing/public/cpp/base_agent.h" +#include "services/tracing/public/cpp/perfetto/producer_client.h" #include "services/tracing/public/mojom/tracing.mojom.h" namespace content { @@ -31,7 +32,6 @@ // This class provides the interface to trigger tracing in the container. class ArcTracingBridge : public KeyedService, - public tracing::BaseAgent, public ConnectionObserver<mojom::TracingInstance> { public: // Returns singleton instance for the given BrowserContext, @@ -46,64 +46,92 @@ // ConnectionObserver<mojom::TracingInstance> overrides: void OnConnectionReady() override; + // State of the tracing activity of the bridge. + enum class State { kDisabled, kStarting, kEnabled, kStopping }; + State state() const { return state_; } + + using SuccessCallback = base::OnceCallback<void(bool)>; + using TraceDataCallback = base::OnceCallback<void(const std::string& data)>; + + // Starts tracing and calls |callback| when started indicating whether tracing + // was started successfully via its parameter. + void StartTracing(const std::string& config, SuccessCallback callback); + + // Stops tracing and calls |callback| with the recorded trace data once + // stopped. If unsuccessful, calls |callback| with an empty data string. + void StopAndFlush(TraceDataCallback callback); + private: + // TODO(crbug.com/839086): Remove once we have replaced the legacy tracing + // service with perfetto. + class ArcTracingAgent : public tracing::BaseAgent { + public: + explicit ArcTracingAgent(ArcTracingBridge* bridge); + ~ArcTracingAgent() override; + + private: + // tracing::mojom::Agent. + void StartTracing(const std::string& config, + base::TimeTicks coordinator_time, + Agent::StartTracingCallback callback) override; + void StopAndFlush(tracing::mojom::RecorderPtr recorder) override; + + void OnTraceData(const std::string& data); + + ArcTracingBridge* const bridge_; + tracing::mojom::RecorderPtr recorder_; + + DISALLOW_COPY_AND_ASSIGN(ArcTracingAgent); + }; + // A helper class for reading trace data from the client side. We separate // this from |ArcTracingAgentImpl| to isolate the logic that runs on browser's - // IO thread. All the functions in this class except for constructor, - // destructor, and |GetWeakPtr| are expected to be run on browser's IO thread. + // IO thread. All the functions in this class except for constructor are + // expected to be run on browser's IO thread. class ArcTracingReader { public: ArcTracingReader(); ~ArcTracingReader(); + // Starts reading trace data from the given file descriptor. void StartTracing(base::ScopedFD read_fd); - void OnTraceDataAvailable(); - void StopTracing(base::OnceCallback<void(const std::string&)> callback); - base::WeakPtr<ArcTracingReader> GetWeakPtr(); + // Stops reading and returns the collected trace data. + std::string StopTracing(); private: + void OnTraceDataAvailable(); + // Number of events for the ring buffer. static constexpr size_t kTraceEventBufferSize = 64000; base::ScopedFD read_fd_; std::unique_ptr<base::FileDescriptorWatcher::Controller> fd_watcher_; base::RingBuffer<std::string, kTraceEventBufferSize> ring_buffer_; - // NOTE: Weak pointers must be invalidated before all other member variables - // so it must be the last member. - base::WeakPtrFactory<ArcTracingReader> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ArcTracingReader); }; struct Category; - // tracing::mojom::Agent. - void StartTracing(const std::string& config, - base::TimeTicks coordinator_time, - Agent::StartTracingCallback callback) override; - void StopAndFlush(tracing::mojom::RecorderPtr recorder) override; - // Callback for QueryAvailableCategories. void OnCategoriesReady(const std::vector<std::string>& categories); - void OnArcTracingStopped(bool success); - void OnTracingReaderStopped(const std::string& data); + void OnArcTracingStarted(SuccessCallback callback, bool success); + void OnArcTracingStopped(TraceDataCallback tracing_stopped_callback, + bool success); + void OnTracingReaderStopped(TraceDataCallback tracing_stopped_callback, + const std::string& data); ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. // List of available categories. std::vector<Category> categories_; - // We use |reader_.GetWeakPtr()| when binding callbacks with its functions. - // Notes that the weak pointer returned by it can only be deferenced or - // invalided in the same task runner to avoid racing condition. The - // destruction of |reader_| is also a source of invalidation. However, we're - // lucky as we're using |ArcTracingAgentImpl| as a singleton, the - // destruction is always performed after all MessageLoops are destroyed, and - // thus there are no race conditions in such situation. - ArcTracingReader reader_; - bool is_stopping_ = false; - tracing::mojom::RecorderPtr recorder_; + ArcTracingAgent agent_; + + std::unique_ptr<ArcTracingReader> reader_; + + State state_ = State::kDisabled; // NOTE: Weak pointers must be invalidated before all other member variables // so it must be the last member.
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc index 3fb253b..fcf50c7 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.cc
@@ -36,7 +36,10 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" +#include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" +#include "chrome/browser/ui/ash/launcher/shelf_spinner_controller.h" #include "chrome/browser/ui/ash/login_screen_client.h" #include "chrome/browser/ui/views/crostini/crostini_installer_view.h" #include "chrome/browser/ui/views/crostini/crostini_uninstaller_view.h" @@ -47,6 +50,7 @@ #include "chromeos/printing/printer_configuration.h" #include "chromeos/services/machine_learning/public/cpp/service_connection.h" #include "components/arc/arc_prefs.h" +#include "components/arc/metrics/arc_metrics_constants.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/histogram_fetcher.h" #include "content/public/common/service_manager_connection.h" @@ -677,8 +681,10 @@ const ash::ShelfItem* item = controller->GetItem(ash::ShelfID(params->app_id)); + // App must be running and not pending in deferred launch. const bool window_attached = - item && item->status == ash::ShelfItemStatus::STATUS_RUNNING; + item && item->status == ash::ShelfItemStatus::STATUS_RUNNING && + !controller->GetShelfSpinnerController()->HasApp(params->app_id); return RespondNow( OneArgument(std::make_unique<base::Value>(window_attached))); } @@ -698,6 +704,117 @@ } /////////////////////////////////////////////////////////////////////////////// +// AutotestPrivateGetArcPackageFunction +/////////////////////////////////////////////////////////////////////////////// + +AutotestPrivateGetArcAppFunction::~AutotestPrivateGetArcAppFunction() = default; + +ExtensionFunction::ResponseAction AutotestPrivateGetArcAppFunction::Run() { + std::unique_ptr<api::autotest_private::GetArcApp::Params> params( + api::autotest_private::GetArcApp::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + DVLOG(1) << "AutotestPrivateGetArcAppFunction " << params->app_id; + + ArcAppListPrefs* const prefs = + ArcAppListPrefs::Get(Profile::FromBrowserContext(browser_context())); + if (!prefs) + return RespondNow(Error("ARC is not available")); + + const std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = + prefs->GetApp(params->app_id); + if (!app_info) + return RespondNow(Error("App is not available")); + + auto app_value = std::make_unique<base::DictionaryValue>(); + + app_value->SetKey("name", base::Value(app_info->name)); + app_value->SetKey("packageName", base::Value(app_info->package_name)); + app_value->SetKey("activity", base::Value(app_info->activity)); + app_value->SetKey("intentUri", base::Value(app_info->intent_uri)); + app_value->SetKey("iconResourceId", base::Value(app_info->icon_resource_id)); + app_value->SetKey("lastLaunchTime", + base::Value(app_info->last_launch_time.ToJsTime())); + app_value->SetKey("installTime", + base::Value(app_info->install_time.ToJsTime())); + app_value->SetKey("sticky", base::Value(app_info->sticky)); + app_value->SetKey("notificationsEnabled", + base::Value(app_info->notifications_enabled)); + app_value->SetKey("ready", base::Value(app_info->ready)); + app_value->SetKey("suspended", base::Value(app_info->suspended)); + app_value->SetKey("showInLauncher", base::Value(app_info->show_in_launcher)); + app_value->SetKey("shortcut", base::Value(app_info->shortcut)); + app_value->SetKey("launchable", base::Value(app_info->launchable)); + + return RespondNow(OneArgument(std::move(app_value))); +} + +/////////////////////////////////////////////////////////////////////////////// +// AutotestPrivateGetArcPackageFunction +/////////////////////////////////////////////////////////////////////////////// + +AutotestPrivateGetArcPackageFunction::~AutotestPrivateGetArcPackageFunction() = + default; + +ExtensionFunction::ResponseAction AutotestPrivateGetArcPackageFunction::Run() { + std::unique_ptr<api::autotest_private::GetArcPackage::Params> params( + api::autotest_private::GetArcPackage::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + DVLOG(1) << "AutotestPrivateGetArcPackageFunction " << params->package_name; + + ArcAppListPrefs* const prefs = + ArcAppListPrefs::Get(Profile::FromBrowserContext(browser_context())); + if (!prefs) + return RespondNow(Error("ARC is not available")); + + const std::unique_ptr<ArcAppListPrefs::PackageInfo> package_info = + prefs->GetPackage(params->package_name); + if (!package_info) + return RespondNow(Error("Package is not available")); + + auto package_value = std::make_unique<base::DictionaryValue>(); + package_value->SetKey("packageName", base::Value(package_info->package_name)); + package_value->SetKey("packageVersion", + base::Value(package_info->package_version)); + package_value->SetKey( + "lastBackupAndroidId", + base::Value(base::Int64ToString(package_info->last_backup_android_id))); + package_value->SetKey("lastBackupTime", + base::Value(base::Time::FromDeltaSinceWindowsEpoch( + base::TimeDelta::FromMicroseconds( + package_info->last_backup_time)) + .ToJsTime())); + package_value->SetKey("shouldSync", base::Value(package_info->should_sync)); + package_value->SetKey("system", base::Value(package_info->system)); + package_value->SetKey("vpnProvider", base::Value(package_info->vpn_provider)); + return RespondNow(OneArgument(std::move(package_value))); +} + +/////////////////////////////////////////////////////////////////////////////// +// AutotestPrivateLaunchArcIntentFunction +/////////////////////////////////////////////////////////////////////////////// + +AutotestPrivateLaunchArcAppFunction::~AutotestPrivateLaunchArcAppFunction() = + default; + +ExtensionFunction::ResponseAction AutotestPrivateLaunchArcAppFunction::Run() { + std::unique_ptr<api::autotest_private::LaunchArcApp::Params> params( + api::autotest_private::LaunchArcApp::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + DVLOG(1) << "AutotestPrivateLaunchArcIntentFunction " << params->app_id << "/" + << params->intent; + + base::Optional<std::string> launch_intent; + if (!params->intent.empty()) + launch_intent = params->intent; + const bool result = arc::LaunchAppWithIntent( + Profile::FromBrowserContext(browser_context()), params->app_id, + launch_intent, 0 /* event_flags */, + arc::UserInteractionType::APP_STARTED_FROM_EXTENSION_API, + 0 /* display_id */); + return RespondNow(OneArgument(std::make_unique<base::Value>(result))); +} + +/////////////////////////////////////////////////////////////////////////////// // AutotestPrivateLaunchAppFunction /////////////////////////////////////////////////////////////////////////////// @@ -714,13 +831,33 @@ if (!controller) return RespondNow(Error("Controller not available")); controller->LaunchApp(ash::ShelfID(params->app_id), - ash::ShelfLaunchSource::LAUNCH_FROM_APP_LIST, + ash::ShelfLaunchSource::LAUNCH_FROM_UNKNOWN, 0, /* event_flags */ display::Screen::GetScreen()->GetPrimaryDisplay().id()); return RespondNow(NoArguments()); } /////////////////////////////////////////////////////////////////////////////// +// AutotestPrivateLaunchAppFunction +/////////////////////////////////////////////////////////////////////////////// + +AutotestPrivateCloseAppFunction::~AutotestPrivateCloseAppFunction() = default; + +ExtensionFunction::ResponseAction AutotestPrivateCloseAppFunction::Run() { + std::unique_ptr<api::autotest_private::CloseApp::Params> params( + api::autotest_private::CloseApp::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + DVLOG(1) << "AutotestPrivateCloseAppFunction " << params->app_id; + + ChromeLauncherController* const controller = + ChromeLauncherController::instance(); + if (!controller) + return RespondNow(Error("Controller not available")); + controller->Close(ash::ShelfID(params->app_id)); + return RespondNow(NoArguments()); +} + +/////////////////////////////////////////////////////////////////////////////// // AutotestPrivateSetCrostiniEnabledFunction ///////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h index 221652f..39939e2 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h
@@ -267,6 +267,36 @@ ResponseAction Run() override; }; +class AutotestPrivateGetArcAppFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("autotestPrivate.getArcApp", + AUTOTESTPRIVATE_GETARCAPP) + + private: + ~AutotestPrivateGetArcAppFunction() override; + ResponseAction Run() override; +}; + +class AutotestPrivateGetArcPackageFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("autotestPrivate.getArcPackage", + AUTOTESTPRIVATE_GETARCPACKAGE) + + private: + ~AutotestPrivateGetArcPackageFunction() override; + ResponseAction Run() override; +}; + +class AutotestPrivateLaunchArcAppFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("autotestPrivate.launchArcApp", + AUTOTESTPRIVATE_LAUNCHARCAPP) + + private: + ~AutotestPrivateLaunchArcAppFunction() override; + ResponseAction Run() override; +}; + class AutotestPrivateLaunchAppFunction : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("autotestPrivate.launchApp", @@ -277,6 +307,16 @@ ResponseAction Run() override; }; +class AutotestPrivateCloseAppFunction : public UIThreadExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("autotestPrivate.closeApp", + AUTOTESTPRIVATE_CLOSEAPP) + + private: + ~AutotestPrivateCloseAppFunction() override; + ResponseAction Run() override; +}; + class AutotestPrivateSetCrostiniEnabledFunction : public UIThreadExtensionFunction { public:
diff --git a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_apitest.cc b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_apitest.cc index 5b23f82..855177f 100644 --- a/chrome/browser/chromeos/extensions/autotest_private/autotest_private_apitest.cc +++ b/chrome/browser/chromeos/extensions/autotest_private/autotest_private_apitest.cc
@@ -6,10 +6,15 @@ #include "build/build_config.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" +#include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/extensions/autotest_private/autotest_private_api.h" #include "chrome/browser/extensions/extension_apitest.h" +#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_util.h" +#include "components/arc/connection_holder.h" +#include "components/arc/test/connection_holder_util.h" +#include "components/arc/test/fake_app_instance.h" namespace extensions { @@ -42,16 +47,46 @@ << message_; } -IN_PROC_BROWSER_TEST_F(AutotestPrivateApiTest, AutotestPrivateArcProvisioned) { +// Set of tests where ARC is enabled and test apps and packages are registered. +IN_PROC_BROWSER_TEST_F(AutotestPrivateApiTest, AutotestPrivateArcEnabled) { // Turn on testing mode so we don't kill the browser. AutotestPrivateAPI::GetFactoryInstance() ->Get(browser()->profile()) ->set_test_mode(true); + + ArcAppListPrefs* const prefs = ArcAppListPrefs::Get(browser()->profile()); + ASSERT_TRUE(prefs); + + arc::SetArcPlayStoreEnabledForProfile(profile(), true); // Provisioning is completed. browser()->profile()->GetPrefs()->SetBoolean(arc::prefs::kArcSignedIn, true); + + std::unique_ptr<arc::FakeAppInstance> app_instance; + app_instance.reset(new arc::FakeAppInstance(prefs)); + prefs->app_connection_holder()->SetInstance(app_instance.get()); + arc::WaitForInstanceReady(prefs->app_connection_holder()); + + arc::mojom::AppInfo app; + app.name = "Fake App"; + app.package_name = "fake.package"; + app.activity = "fake.package.activity"; + app_instance->SendRefreshAppList(std::vector<arc::mojom::AppInfo>(1, app)); + + std::vector<arc::mojom::ArcPackageInfoPtr> packages; + packages.emplace_back(arc::mojom::ArcPackageInfo::New( + app.package_name, 10 /* package_version */, + 100 /* last_backup_android_id */, + base::Time::Now() + .ToDeltaSinceWindowsEpoch() + .InMicroseconds() /* last_backup_time */, + true /* sync */)); + app_instance->SendRefreshPackageList(std::move(packages)); + ASSERT_TRUE( - RunComponentExtensionTestWithArg("autotest_private", "arcProvisioned")) + RunComponentExtensionTestWithArg("autotest_private", "arcEnabled")) << message_; + + arc::SetArcPlayStoreEnabledForProfile(profile(), false); } } // namespace extensions
diff --git a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc index 75cc3aa..6b52ea9 100644 --- a/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc +++ b/chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc
@@ -498,6 +498,10 @@ names_.end()) { field_mask |= ProvidedFileSystemInterface::METADATA_FIELD_THUMBNAIL; } + if (!field_mask) { + OnGetMetadataCompleted(nullptr, base::File::FILE_OK); + return; + } parser.file_system()->GetMetadata( parser.file_path(), field_mask,
diff --git a/chrome/browser/chromeos/file_manager/file_manager_jstest.cc b/chrome/browser/chromeos/file_manager/file_manager_jstest.cc index 8cfccd0..dba38b9 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_jstest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_jstest.cc
@@ -179,6 +179,10 @@ RunGeneratedTest("/common/js/files_app_entry_types_unittest.html"); } +IN_PROC_BROWSER_TEST_F(FileManagerJsTest, FileType) { + RunGeneratedTest("/common/js/file_type_unittest.html"); +} + IN_PROC_BROWSER_TEST_F(FileManagerJsTest, UtilTest) { RunGeneratedTest("/common/js/util_unittest.html"); }
diff --git a/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.cc b/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.cc index b60214e..e4a163f 100644 --- a/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.cc +++ b/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.cc
@@ -90,48 +90,4 @@ return nullptr; } -std::unique_ptr<cryptauth::CryptAuthClientFactory> -ChromeProximityAuthClient::CreateCryptAuthClientFactory() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return GetCryptAuthService()->CreateCryptAuthClientFactory(); -} - -cryptauth::DeviceClassifier ChromeProximityAuthClient::GetDeviceClassifier() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return GetCryptAuthService()->GetDeviceClassifier(); -} - -std::string ChromeProximityAuthClient::GetAccountId() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return GetCryptAuthService()->GetAccountId(); -} - -cryptauth::CryptAuthEnrollmentManager* -ChromeProximityAuthClient::GetCryptAuthEnrollmentManager() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return GetCryptAuthService()->GetCryptAuthEnrollmentManager(); -} - -cryptauth::CryptAuthDeviceManager* -ChromeProximityAuthClient::GetCryptAuthDeviceManager() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return GetCryptAuthService()->GetCryptAuthDeviceManager(); -} - -std::string ChromeProximityAuthClient::GetLocalDevicePublicKey() { - return GetDeviceSyncClient()->GetLocalDeviceMetadata()->public_key(); -} - -cryptauth::CryptAuthService* ChromeProximityAuthClient::GetCryptAuthService() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return ChromeCryptAuthServiceFactory::GetInstance()->GetForBrowserContext( - profile_); -} - -device_sync::DeviceSyncClient* -ChromeProximityAuthClient::GetDeviceSyncClient() { - DCHECK(base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - return device_sync::DeviceSyncClientFactory::GetForProfile(profile_); -} - } // namespace chromeos
diff --git a/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.h b/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.h index 4bf24221..7ccf242f 100644 --- a/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.h +++ b/chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.h
@@ -10,16 +10,8 @@ class Profile; -namespace cryptauth { -class CryptAuthService; -} // namespace cryptauth - namespace chromeos { -namespace device_sync { -class DeviceSyncClient; -} // namespace device_sync - // A Chrome-specific implementation of the ProximityAuthClient interface. // There is one |ChromeProximityAuthClient| per |Profile|. class ChromeProximityAuthClient : public proximity_auth::ProximityAuthClient { @@ -38,19 +30,8 @@ const std::string& nonce, base::Callback<void(const std::string& challenge)> callback) override; proximity_auth::ProximityAuthPrefManager* GetPrefManager() override; - std::unique_ptr<cryptauth::CryptAuthClientFactory> - CreateCryptAuthClientFactory() override; - cryptauth::DeviceClassifier GetDeviceClassifier() override; - std::string GetAccountId() override; - cryptauth::CryptAuthEnrollmentManager* GetCryptAuthEnrollmentManager() - override; - cryptauth::CryptAuthDeviceManager* GetCryptAuthDeviceManager() override; - std::string GetLocalDevicePublicKey() override; private: - cryptauth::CryptAuthService* GetCryptAuthService(); - device_sync::DeviceSyncClient* GetDeviceSyncClient(); - Profile* const profile_; DISALLOW_COPY_AND_ASSIGN(ChromeProximityAuthClient);
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc index c0ae7d1..4f303b6 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc
@@ -111,7 +111,6 @@ device_sync::DeviceSyncClient* device_sync_client, multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client) : EasyUnlockService(profile, secure_channel_client), - scoped_crypt_auth_device_manager_observer_(this), will_unlock_using_easy_unlock_(false), lock_screen_last_shown_timestamp_(base::TimeTicks::Now()), deferring_device_load_(false), @@ -120,21 +119,16 @@ multidevice_setup_client_(multidevice_setup_client), shown_pairing_changed_notification_(false), weak_ptr_factory_(this) { - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - // If |device_sync_client_| is not ready yet, wait for it to call back on - // OnReady(). - if (device_sync_client_->is_ready()) - OnReady(); + // If |device_sync_client_| is not ready yet, wait for it to call back on + // OnReady(). + if (device_sync_client_->is_ready()) + OnReady(); - device_sync_client_->AddObserver(this); + device_sync_client_->AddObserver(this); - if (base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup)) { - OnFeatureStatesChanged(multidevice_setup_client_->GetFeatureStates()); + OnFeatureStatesChanged(multidevice_setup_client_->GetFeatureStates()); - multidevice_setup_client_->AddObserver(this); - } - } + multidevice_setup_client_->AddObserver(this); } EasyUnlockServiceRegular::~EasyUnlockServiceRegular() = default; @@ -143,8 +137,7 @@ // that SmartLock setup has completed successfully. Make this signal more // explicit. void EasyUnlockServiceRegular::LoadRemoteDevices() { - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) && - !device_sync_client_->is_ready()) { + if (!device_sync_client_->is_ready()) { // OnEnrollmentFinished() or OnNewDevicesSynced() will call back on this // method once |device_sync_client_| is ready. PA_LOG(VERBOSE) << "DeviceSyncClient is not ready yet, delaying " @@ -160,9 +153,7 @@ is_in_legacy_host_mode && feature_state_ == multidevice_setup::mojom::FeatureState::kUnavailableNoVerifiedHost; - if (base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup) && - feature_state_ != + if (feature_state_ != multidevice_setup::mojom::FeatureState::kEnabledByUser && !is_in_valid_legacy_host_state) { // OnFeatureStatesChanged() will call back on this method when feature state @@ -174,11 +165,7 @@ } bool has_unlock_keys; - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - has_unlock_keys = !GetUnlockKeys().empty(); - } else { - has_unlock_keys = !GetCryptAuthDeviceManager()->GetUnlockKeys().empty(); - } + has_unlock_keys = !GetUnlockKeys().empty(); // TODO(jhawkins): The enabled pref should not be tied to whether unlock keys // exist; instead, both of these variables should be used to determine @@ -212,34 +199,7 @@ return; } - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - UseLoadedRemoteDevices(GetUnlockKeys()); - } else { - remote_device_loader_.reset(new cryptauth::RemoteDeviceLoader( - GetCryptAuthDeviceManager()->GetUnlockKeys(), - proximity_auth_client()->GetAccountId(), - GetCryptAuthEnrollmentManager()->GetUserPrivateKey(), - cryptauth::SecureMessageDelegateImpl::Factory::NewInstance())); - - // OnRemoteDevicesLoaded() will call on UseLoadedRemoteDevices() with the - // devices it receives. - remote_device_loader_->Load( - base::Bind(&EasyUnlockServiceRegular::OnRemoteDevicesLoaded, - weak_ptr_factory_.GetWeakPtr())); - } -} - -void EasyUnlockServiceRegular::OnRemoteDevicesLoaded( - const multidevice::RemoteDeviceList& remote_devices) { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - - multidevice::RemoteDeviceRefList remote_device_refs; - for (auto& remote_device : remote_devices) { - remote_device_refs.push_back(multidevice::RemoteDeviceRef( - std::make_shared<multidevice::RemoteDevice>(remote_device))); - } - - UseLoadedRemoteDevices(remote_device_refs); + UseLoadedRemoteDevices(GetUnlockKeys()); } void EasyUnlockServiceRegular::UseLoadedRemoteDevices( @@ -252,20 +212,15 @@ // We need to store a copy of |local_and_remote_devices| in the TPM, so it can // be retrieved on the sign-in screen when a user session has not been started - // yet. - // If |chromeos::features::kMultiDeviceApi| is enabled, it will expect a final - // size of 2 (the one remote device, and the local device). - // If |chromeos::features::kMultiDeviceApi| is disabled, it will expect a - // final size of 1 (just the remote device). + // yet. This expects a final size of 2 (the one remote device, and the local + // device). // TODO(crbug.com/856380): For historical reasons, the local and remote device // are persisted together in a list. This is awkward and hacky; they should // be persisted in a dictionary. multidevice::RemoteDeviceRefList local_and_remote_devices; local_and_remote_devices.push_back(remote_devices[0]); - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - local_and_remote_devices.push_back( - *device_sync_client_->GetLocalDeviceMetadata()); - } + local_and_remote_devices.push_back( + *device_sync_client_->GetLocalDeviceMetadata()); std::unique_ptr<base::ListValue> device_list(new base::ListValue()); for (const auto& device : local_and_remote_devices) { @@ -283,18 +238,11 @@ // TODO(jhawkins): Remove the bluetoothAddress field from this proto. dict->SetString(key_names::kKeyBluetoothAddress, std::string()); - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - dict->SetString( - key_names::kKeyPermitPermitId, - base::StringPrintf( - key_names::kPermitPermitIdFormat, - gaia::CanonicalizeEmail(GetAccountId().GetUserEmail()).c_str())); - } else { - dict->SetString( - key_names::kKeyPermitPermitId, - base::StringPrintf(key_names::kPermitPermitIdFormat, - proximity_auth_client()->GetAccountId().c_str())); - } + dict->SetString( + key_names::kKeyPermitPermitId, + base::StringPrintf( + key_names::kPermitPermitIdFormat, + gaia::CanonicalizeEmail(GetAccountId().GetUserEmail()).c_str())); dict->SetString(key_names::kKeyPermitId, b64_public_key); dict->SetString(key_names::kKeyPermitType, key_names::kPermitTypeLicence); @@ -432,11 +380,6 @@ GetAccountId()); } - if (!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - scoped_crypt_auth_device_manager_observer_.Add( - GetCryptAuthDeviceManager()); - } - LoadRemoteDevices(); } @@ -452,20 +395,11 @@ proximity_auth::ScreenlockBridge::Get()->RemoveObserver(this); - if (!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - scoped_crypt_auth_device_manager_observer_.RemoveAll(); - } - registrar_.RemoveAll(); - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { - device_sync_client_->RemoveObserver(this); + device_sync_client_->RemoveObserver(this); - if (base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup)) { - multidevice_setup_client_->RemoveObserver(this); - } - } + multidevice_setup_client_->RemoveObserver(this); } bool EasyUnlockServiceRegular::IsAllowedInternal() const { @@ -482,10 +416,8 @@ if (!ProfileHelper::IsPrimaryProfile(profile())) return false; - if (base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup) && - feature_state_ == - multidevice_setup::mojom::FeatureState::kProhibitedByPolicy) { + if (feature_state_ == + multidevice_setup::mojom::FeatureState::kProhibitedByPolicy) { return false; } @@ -497,9 +429,7 @@ bool EasyUnlockServiceRegular::IsEnabled() const { // TODO(crbug.com/894585): Remove the legacy special case after M71. - if (base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup) && - !IsInLegacyHostMode()) { + if (!IsInLegacyHostMode()) { return feature_state_ == multidevice_setup::mojom::FeatureState::kEnabledByUser; } @@ -512,9 +442,6 @@ } bool EasyUnlockServiceRegular::IsInLegacyHostMode() const { - if (!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) - return false; - if (!device_sync_client_->is_ready()) { PA_LOG(WARNING) << "EasyUnlockServiceRegular::IsInLegacyHostMode: " << "DeviceSyncClient not ready. Returning false."; @@ -556,38 +483,6 @@ lock_screen_last_shown_timestamp_ = base::TimeTicks::Now(); } -void EasyUnlockServiceRegular::OnSyncStarted() { - unlock_keys_before_sync_ = GetCryptAuthDeviceManager()->GetUnlockKeys(); -} - -void EasyUnlockServiceRegular::OnSyncFinished( - cryptauth::CryptAuthDeviceManager::SyncResult sync_result, - cryptauth::CryptAuthDeviceManager::DeviceChangeResult - device_change_result) { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - - if (sync_result == cryptauth::CryptAuthDeviceManager::SyncResult::FAILURE) - return; - - std::set<std::string> public_keys_before_sync; - for (const auto& device_info : unlock_keys_before_sync_) { - public_keys_before_sync.insert(device_info.public_key()); - } - unlock_keys_before_sync_.clear(); - - std::vector<cryptauth::ExternalDeviceInfo> unlock_keys_after_sync = - GetCryptAuthDeviceManager()->GetUnlockKeys(); - std::set<std::string> public_keys_after_sync; - for (const auto& device_info : unlock_keys_after_sync) { - public_keys_after_sync.insert(device_info.public_key()); - } - - ShowNotificationIfNewDevicePresent(public_keys_before_sync, - public_keys_after_sync); - - LoadRemoteDevices(); -} - void EasyUnlockServiceRegular::OnReady() { // If the local device and synced devices are ready for the first time, // establish what the unlock keys were before the next sync. This is necessary @@ -603,11 +498,6 @@ } void EasyUnlockServiceRegular::OnNewDevicesSynced() { - // This method copies EasyUnlockServiceRegular::OnSyncFinished(). - // TODO(crbug.com/848956): Remove EasyUnlockServiceRegular::OnSyncFinished(). - - DCHECK(base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - std::set<std::string> public_keys_before_sync; for (const auto& remote_device : remote_device_unlock_keys_before_sync_) { public_keys_before_sync.insert(remote_device.public_key()); @@ -658,10 +548,6 @@ } void EasyUnlockServiceRegular::ShowChromebookAddedNotification() { - DCHECK(base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) && - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup)); - // The user may have decided to disable Smart Lock or the whole multidevice // suite immediately after completing setup, so ensure that Smart Lock is // enabled. @@ -684,9 +570,6 @@ // if EasyUnlock was enabled through the setup app. if (!public_keys_after_sync.empty()) { if (public_keys_before_sync.empty()) { - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) && - base::FeatureList::IsEnabled( - chromeos::features::kEnableUnifiedMultiDeviceSetup)) { multidevice_setup::MultiDeviceSetupDialog* multidevice_setup_dialog = multidevice_setup::MultiDeviceSetupDialog::Get(); if (multidevice_setup_dialog) { @@ -697,7 +580,6 @@ weak_ptr_factory_.GetWeakPtr())); return; } - } notification_controller_->ShowChromebookAddedNotification(); } else { @@ -792,30 +674,6 @@ // Nothing to do. } -cryptauth::CryptAuthEnrollmentManager* -EasyUnlockServiceRegular::GetCryptAuthEnrollmentManager() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - - cryptauth::CryptAuthEnrollmentManager* manager = - ChromeCryptAuthServiceFactory::GetInstance() - ->GetForBrowserContext(profile()) - ->GetCryptAuthEnrollmentManager(); - DCHECK(manager); - return manager; -} - -cryptauth::CryptAuthDeviceManager* -EasyUnlockServiceRegular::GetCryptAuthDeviceManager() { - DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); - - cryptauth::CryptAuthDeviceManager* manager = - ChromeCryptAuthServiceFactory::GetInstance() - ->GetForBrowserContext(profile()) - ->GetCryptAuthDeviceManager(); - DCHECK(manager); - return manager; -} - void EasyUnlockServiceRegular::RefreshCryptohomeKeysIfPossible() { CheckCryptohomeKeysAndMaybeHardlock(); }
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.h b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.h index 91d7528..81f04875 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.h +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.h
@@ -19,7 +19,6 @@ #include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "chromeos/services/device_sync/public/cpp/device_sync_client.h" #include "chromeos/services/multidevice_setup/public/cpp/multidevice_setup_client.h" -#include "components/cryptauth/cryptauth_device_manager.h" #include "components/cryptauth/network_request_error.h" #include "components/prefs/pref_change_registrar.h" @@ -28,8 +27,6 @@ } // namespace base namespace cryptauth { -class CryptAuthDeviceManager; -class CryptAuthEnrollmentManager; class RemoteDeviceLoader; } // namespace cryptauth @@ -52,7 +49,6 @@ class EasyUnlockServiceRegular : public EasyUnlockService, public proximity_auth::ScreenlockBridge::Observer, - public cryptauth::CryptAuthDeviceManager::Observer, public device_sync::DeviceSyncClient::Observer, public multidevice_setup::MultiDeviceSetupClient::Observer { public: @@ -77,10 +73,6 @@ // ProximityAuthSystem. void LoadRemoteDevices(); - // Called when |remote_device_loader_| completes. - void OnRemoteDevicesLoaded( - const multidevice::RemoteDeviceList& remote_devices); - void UseLoadedRemoteDevices( const multidevice::RemoteDeviceRefList& remote_devices); @@ -111,12 +103,6 @@ void OnWillFinalizeUnlock(bool success) override; void OnSuspendDoneInternal() override; - // CryptAuthDeviceManager::Observer: - void OnSyncStarted() override; - void OnSyncFinished(cryptauth::CryptAuthDeviceManager::SyncResult sync_result, - cryptauth::CryptAuthDeviceManager::DeviceChangeResult - device_change_result) override; - // device_sync::DeviceSyncClient::Observer: void OnReady() override; void OnEnrollmentFinished() override; @@ -149,23 +135,12 @@ EasyUnlockScreenlockStateHandler::HardlockState state_on_success, bool success); - // Returns the CryptAuthEnrollmentManager, which manages the profile's - // CryptAuth enrollment. - cryptauth::CryptAuthEnrollmentManager* GetCryptAuthEnrollmentManager(); - - // Returns the CryptAuthEnrollmentManager, which manages the profile's - // synced devices from CryptAuth. - cryptauth::CryptAuthDeviceManager* GetCryptAuthDeviceManager(); - // Refreshes the ChromeOS cryptohome keys if the user has reauthed recently. // Otherwise, hardlock the device. void RefreshCryptohomeKeysIfPossible(); multidevice::RemoteDeviceRefList GetUnlockKeys(); - ScopedObserver<cryptauth::CryptAuthDeviceManager, EasyUnlockServiceRegular> - scoped_crypt_auth_device_manager_observer_; - // True if the user just unlocked the screen using Easy Unlock. Reset once // the screen unlocks. Used to distinguish Easy Unlock-powered unlocks from // password-based unlocks for metrics.
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc index 8df7f61b..6d9a43f8 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc
@@ -547,13 +547,8 @@ remote_device.GetDeviceId()); } - // If |chromeos::features::kMultiDeviceApi| is enabled, both a remote device - // and local device are expected, and this service cannot continue unless - // both are present. - // - // If the flag is disabled, just one device, the remote device, is expected to - // be passed along -- if a second device is present, it can simply be ignored. - // + // Both a remote device and local device are expected, and this service cannot + // continue unless both are present. // TODO(crbug.com/856380): The remote and local devices need to be passed in a // less hacky way. if (remote_devices.size() > 2u) { @@ -565,8 +560,7 @@ return; } - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) && - remote_devices.size() != 2u) { + if (remote_devices.size() != 2u) { PA_LOG(ERROR) << "Expected a device list of size 2, received list of size " << remote_devices.size(); SetHardlockStateForUser(account_id, @@ -622,10 +616,7 @@ return; } - // Likewise, a similar issue could exist when the kMultiDeviceApi flag is - // enabled. - if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) && - !local_device) { + if (!local_device) { SetHardlockStateForUser(account_id, EasyUnlockScreenlockStateHandler::NO_PAIRING); return;
diff --git a/chrome/browser/extensions/activity_log/counting_policy.cc b/chrome/browser/extensions/activity_log/counting_policy.cc index 34454c4..397104e 100644 --- a/chrome/browser/extensions/activity_log/counting_policy.cc +++ b/chrome/browser/extensions/activity_log/counting_policy.cc
@@ -443,7 +443,7 @@ where_next = " AND "; } if (!api_name.empty()) { - where_str += where_next + "api_name=?"; + where_str += where_next + "api_name LIKE ?"; where_next = " AND "; } if (type != Action::ACTION_ANY) { @@ -473,7 +473,7 @@ if (!extension_id.empty()) query.BindString(++i, extension_id); if (!api_name.empty()) - query.BindString(++i, api_name); + query.BindString(++i, api_name + "%"); if (type != Action::ACTION_ANY) query.BindInt(++i, static_cast<int>(type)); if (!page_url.empty())
diff --git a/chrome/browser/extensions/activity_log/counting_policy_unittest.cc b/chrome/browser/extensions/activity_log/counting_policy_unittest.cc index e353d11..8240ebe 100644 --- a/chrome/browser/extensions/activity_log/counting_policy_unittest.cc +++ b/chrome/browser/extensions/activity_log/counting_policy_unittest.cc
@@ -574,6 +574,20 @@ base::BindOnce( &CountingPolicyTest::RetrieveActions_FetchFilteredActions1)); + // Test for case insensitive matching for api_call. + CheckReadFilteredData( + policy, extension->id(), Action::ACTION_API_CALL, "tabs.testmethod", "", + "", -1, + base::BindOnce( + &CountingPolicyTest::RetrieveActions_FetchFilteredActions1)); + + // Test for prefix matching for api_call. + CheckReadFilteredData( + policy, extension->id(), Action::ACTION_API_CALL, "tabs.testM", "", "", + -1, + base::BindOnce( + &CountingPolicyTest::RetrieveActions_FetchFilteredActions1)); + CheckReadFilteredData( policy, "", Action::ACTION_DOM_ACCESS, "", "", "", -1, base::BindOnce(
diff --git a/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc b/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc index a1a9308..9604dd4 100644 --- a/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc +++ b/chrome/browser/extensions/activity_log/fullstream_ui_policy.cc
@@ -143,7 +143,7 @@ where_next = " AND "; } if (!api_name.empty()) { - where_str += where_next + "api_name=?"; + where_str += where_next + "api_name LIKE ?"; where_next = " AND "; } if (type != Action::ACTION_ANY) { @@ -170,7 +170,7 @@ if (!extension_id.empty()) query.BindString(++i, extension_id); if (!api_name.empty()) - query.BindString(++i, api_name); + query.BindString(++i, api_name + "%"); if (type != Action::ACTION_ANY) query.BindInt(++i, static_cast<int>(type)); if (!page_url.empty())
diff --git a/chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc b/chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc index 4150fc36..4cf2834 100644 --- a/chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc +++ b/chrome/browser/extensions/activity_log/fullstream_ui_policy_unittest.cc
@@ -427,6 +427,20 @@ base::BindOnce( &FullStreamUIPolicyTest::RetrieveActions_FetchFilteredActions1)); + // Test for case insensitive matching for api_call. + CheckReadFilteredData( + policy, extension->id(), Action::ACTION_API_CALL, "tabs.testmethod", "", + "", -1, + base::BindOnce( + &FullStreamUIPolicyTest::RetrieveActions_FetchFilteredActions1)); + + // Test for prefix matching for api_call. + CheckReadFilteredData( + policy, extension->id(), Action::ACTION_API_CALL, "tabs.testM", "", "", + -1, + base::BindOnce( + &FullStreamUIPolicyTest::RetrieveActions_FetchFilteredActions1)); + CheckReadFilteredData( policy, "", Action::ACTION_DOM_ACCESS, "", "", "", -1, base::BindOnce(
diff --git a/chrome/browser/extensions/api/automation/automation_apitest.cc b/chrome/browser/extensions/api/automation/automation_apitest.cc index eaac524..16c761d4 100644 --- a/chrome/browser/extensions/api/automation/automation_apitest.cc +++ b/chrome/browser/extensions/api/automation/automation_apitest.cc
@@ -132,7 +132,8 @@ << message_; } -IN_PROC_BROWSER_TEST_F(AutomationApiTest, BoundsForRange) { +// TODO(https://crbug.com/908509): sarakato to investigate cause of flakiness. +IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_BoundsForRange) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "bounds_for_range.html"))
diff --git a/chrome/browser/extensions/api/storage/settings_apitest.cc b/chrome/browser/extensions/api/storage/settings_apitest.cc index 207804b..4805dfc 100644 --- a/chrome/browser/extensions/api/storage/settings_apitest.cc +++ b/chrome/browser/extensions/api/storage/settings_apitest.cc
@@ -35,6 +35,7 @@ #include "extensions/browser/api/storage/settings_namespace.h" #include "extensions/browser/api/storage/storage_frontend.h" #include "extensions/browser/extension_system.h" +#include "extensions/common/extension_features.h" #include "extensions/common/value_builder.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" @@ -570,4 +571,39 @@ << message_; } +class StorageAreaApiTest : public ExtensionSettingsApiTest, + public ::testing::WithParamInterface<bool> { + public: + StorageAreaApiTest() = default; + ~StorageAreaApiTest() override = default; + + void SetUp() override { + if (GetParam()) { + scoped_feature_list_.InitAndEnableFeature( + extensions_features::kNativeCrxBindings); + } else { + scoped_feature_list_.InitAndDisableFeature( + extensions_features::kNativeCrxBindings); + } + ExtensionSettingsApiTest::SetUp(); + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; + + DISALLOW_COPY_AND_ASSIGN(StorageAreaApiTest); +}; + +IN_PROC_BROWSER_TEST_P(StorageAreaApiTest, StorageAreaOnChanged) { + ASSERT_TRUE(RunExtensionTest("settings/storage_area")) << message_; +} + +INSTANTIATE_TEST_CASE_P(StorageAreaNativeBindings, + StorageAreaApiTest, + ::testing::Values(true)); + +INSTANTIATE_TEST_CASE_P(StorageAreaJSBindings, + StorageAreaApiTest, + ::testing::Values(false)); + } // namespace extensions
diff --git a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc index 547855e3..7fec215 100644 --- a/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc +++ b/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc
@@ -54,7 +54,6 @@ using webrtc_event_logging::kStartRemoteLoggingFailureFeatureDisabled; using webrtc_event_logging::kStartRemoteLoggingFailureMaxSizeTooLarge; using webrtc_event_logging::kStartRemoteLoggingFailureMaxSizeTooSmall; -using webrtc_event_logging::kStartRemoteLoggingFailureOutputPeriodMsIsNegative; using webrtc_event_logging::kStartRemoteLoggingFailureOutputPeriodMsTooLarge; using webrtc_event_logging:: kStartRemoteLoggingFailureUnknownOrInactivePeerConnection; @@ -767,19 +766,6 @@ IN_PROC_BROWSER_TEST_F( WebrtcLoggingPrivateApiStartEventLoggingTestFeatureAndPolicyEnabled, - StartEventLoggingWithNegativeOutputPeriodMsFails) { - const std::string peer_connection_id = "id"; - SetUpPeerConnection(peer_connection_id); - const int output_period_ms = -1; - constexpr bool expect_success = false; - const std::string error_message = - kStartRemoteLoggingFailureOutputPeriodMsIsNegative; - StartEventLogging(peer_connection_id, kMaxRemoteLogFileSizeBytes, - output_period_ms, kWebAppId, expect_success, error_message); -} - -IN_PROC_BROWSER_TEST_F( - WebrtcLoggingPrivateApiStartEventLoggingTestFeatureAndPolicyEnabled, StartEventLoggingWithTooLargeOutputPeriodMsFails) { const std::string peer_connection_id = "id"; SetUpPeerConnection(peer_connection_id);
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index a8edd79..59cac9af 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -1034,6 +1034,11 @@ "expiry_milestone": 76 }, { + "name": "enable-custom-mac-paper-sizes", + "owners": [ "//printing/OWNERS" ], + "expiry_milestone": 76 + }, + { "name": "enable-data-reduction-proxy-main-menu", // "owners": [ "your-team" ], "expiry_milestone": 76
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index c8f037b..4be0fac1 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3031,6 +3031,10 @@ "Create native windows the app shim process, instead of of the browser " "process."; +const char kEnableCustomMacPaperSizesName[] = "Enable custom paper sizes"; +const char kEnableCustomMacPaperSizesDescription[] = + "Allow use of custom paper sizes in Print Preview."; + const char kMacTouchBarName[] = "Hardware Touch Bar"; const char kMacTouchBarDescription[] = "Control the use of the Touch Bar.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index f7e5f41..79781d9 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1801,6 +1801,9 @@ extern const char kCreateAppWindowsInAppShimProcessName[]; extern const char kCreateAppWindowsInAppShimProcessDescription[]; +extern const char kEnableCustomMacPaperSizesName[]; +extern const char kEnableCustomMacPaperSizesDescription[]; + extern const char kMacTouchBarName[]; extern const char kMacTouchBarDescription[];
diff --git a/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc b/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc index 2a41b64..1d524564 100644 --- a/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc +++ b/chrome/browser/media/webrtc/webrtc_event_log_manager_common.cc
@@ -49,8 +49,6 @@ const char kStartRemoteLoggingFailureMaxSizeTooSmall[] = "Max size too small."; const char kStartRemoteLoggingFailureMaxSizeTooLarge[] = "Excessively large max log size."; -const char kStartRemoteLoggingFailureOutputPeriodMsIsNegative[] = - "Negative output period (ms)."; const char kStartRemoteLoggingFailureOutputPeriodMsTooLarge[] = "Excessively large output period (ms)."; const char kStartRemoteLoggingFailureIllegalWebAppId[] = "Illegal web-app ID.";
diff --git a/chrome/browser/media/webrtc/webrtc_event_log_manager_common.h b/chrome/browser/media/webrtc/webrtc_event_log_manager_common.h index 8eb54a3..4740325 100644 --- a/chrome/browser/media/webrtc/webrtc_event_log_manager_common.h +++ b/chrome/browser/media/webrtc/webrtc_event_log_manager_common.h
@@ -102,7 +102,6 @@ extern const char kStartRemoteLoggingFailureUnlimitedSizeDisallowed[]; extern const char kStartRemoteLoggingFailureMaxSizeTooSmall[]; extern const char kStartRemoteLoggingFailureMaxSizeTooLarge[]; -extern const char kStartRemoteLoggingFailureOutputPeriodMsIsNegative[]; extern const char kStartRemoteLoggingFailureOutputPeriodMsTooLarge[]; extern const char kStartRemoteLoggingFailureIllegalWebAppId[]; extern const char kStartRemoteLoggingFailureUnknownOrInactivePeerConnection[];
diff --git a/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc b/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc index 336dabd..047eebd 100644 --- a/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc +++ b/chrome/browser/media/webrtc/webrtc_event_log_manager_remote.cc
@@ -28,6 +28,7 @@ // issue where we read the entire file into memory. const size_t kMaxRemoteLogFileSizeBytes = 50000000u; +const int kDefaultOutputPeriodMs = 5000; const int kMaxOutputPeriodMs = 60000; namespace { @@ -405,6 +406,10 @@ DCHECK(error_message); DCHECK(error_message->empty()); + if (output_period_ms < 0) { + output_period_ms = kDefaultOutputPeriodMs; + } + if (!AreLogParametersValid(max_file_size_bytes, output_period_ms, web_app_id, error_message)) { // |error_message| will have been set by AreLogParametersValid(). @@ -659,12 +664,6 @@ return false; } - if (output_period_ms < 0) { - LOG(WARNING) << "Output period (ms) must be non-negative."; - *error_message = kStartRemoteLoggingFailureOutputPeriodMsIsNegative; - return false; - } - if (output_period_ms > kMaxOutputPeriodMs) { LOG(WARNING) << "Output period (ms) exceeds maximum allowed."; *error_message = kStartRemoteLoggingFailureOutputPeriodMsTooLarge;
diff --git a/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc b/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc index 218bc722..94ffa11 100644 --- a/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc +++ b/chrome/browser/media/webrtc/webrtc_event_log_manager_unittest.cc
@@ -2020,19 +2020,6 @@ } TEST_F(WebRtcEventLogManagerTest, - StartRemoteLoggingReturnsFalseIfOutputPeriodMsIsNegative) { - const auto key = GetPeerConnectionKey(rph_.get(), kLid); - const std::string id = "id"; // For explicitness' sake. - ASSERT_TRUE(PeerConnectionAdded(key, id)); - std::string error_message; - constexpr int output_period_ms = -1; - EXPECT_FALSE(StartRemoteLogging(key, id, kMaxRemoteLogFileSizeBytes, - output_period_ms, kWebAppId, nullptr, - &error_message)); - EXPECT_EQ(error_message, kStartRemoteLoggingFailureOutputPeriodMsIsNegative); -} - -TEST_F(WebRtcEventLogManagerTest, StartRemoteLoggingReturnsFalseIfExcessivelyLargeOutputPeriodMs) { const auto key = GetPeerConnectionKey(rph_.get(), kLid); const std::string id = "id"; // For explicitness' sake.
diff --git a/chrome/browser/picture_in_picture/OWNERS b/chrome/browser/picture_in_picture/OWNERS index dbec2ab..ed74af2 100644 --- a/chrome/browser/picture_in_picture/OWNERS +++ b/chrome/browser/picture_in_picture/OWNERS
@@ -1,2 +1 @@ -apacible@chromium.org -mlamouri@chromium.org +file://third_party/blink/renderer/modules/picture_in_picture/OWNERS
diff --git a/chrome/browser/resources/eoc_internals/.eslintrc.js b/chrome/browser/resources/.eslintrc.js similarity index 80% rename from chrome/browser/resources/eoc_internals/.eslintrc.js rename to chrome/browser/resources/.eslintrc.js index 2d14fd3..6e50809 100644 --- a/chrome/browser/resources/eoc_internals/.eslintrc.js +++ b/chrome/browser/resources/.eslintrc.js
@@ -3,11 +3,8 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { 'no-var': 'error', + 'prefer-const': 'error', }, -}; \ No newline at end of file +};
diff --git a/chrome/browser/resources/app_management/BUILD.gn b/chrome/browser/resources/app_management/BUILD.gn index a3f99ff..b5c6b4d 100644 --- a/chrome/browser/resources/app_management/BUILD.gn +++ b/chrome/browser/resources/app_management/BUILD.gn
@@ -5,46 +5,47 @@ import("//third_party/closure_compiler/compile_js.gni") import("../optimize_webui.gni") -js_type_check("closure_compile") { - deps = [ - ":app", - ":browser_proxy", - ":fake_page_handler", - ":main_view", - ] -} +if (!is_android) { + js_type_check("closure_compile") { + deps = [ + ":app", + ":browser_proxy", + ":constants", + ":fake_page_handler", + ":main_view", + ] + } -js_library("app") { - deps = [ - ":browser_proxy", - ":main_view", - ] -} + js_library("app") { + deps = [ + ":browser_proxy", + ":main_view", + ] + } -js_library("browser_proxy") { - deps = [ - ":externs", - ":fake_page_handler", - "//ui/webui/resources/js:cr", - ] -} + js_library("browser_proxy") { + deps = [ + ":fake_page_handler", + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//ui/webui/resources/js:cr", + ] + } -js_library("externs") { - sources = [] - extra_deps = [ "//chrome/browser/ui/webui/app_management:mojo_bindings_js" ] - externs_list = [ - "$root_gen_dir/chrome/browser/ui/webui/app_management/app_management.mojom-lite.externs.js", - "$externs_path/mojo.js", - ] -} + js_library("constants") { + } -js_library("fake_page_handler") { - deps = [ - ":externs", - "//ui/webui/resources/js:cr", - ] -} + js_library("fake_page_handler") { + deps = [ + "//chrome/browser/ui/webui/app_management:mojo_bindings_js_externs", + "//ui/webui/resources/js:cr", + ] + } -js_library("main_view") { - deps = [] + js_library("main_view") { + deps = [ + ":browser_proxy", + ":constants", + "//ui/webui/resources/js:load_time_data", + ] + } }
diff --git a/chrome/browser/resources/app_management/app.html b/chrome/browser/resources/app_management/app.html index be9002c..b9198de 100644 --- a/chrome/browser/resources/app_management/app.html +++ b/chrome/browser/resources/app_management/app.html
@@ -1,9 +1,15 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://apps/browser_proxy.html"> <link rel="import" href="chrome://apps/main_view.html"> - +<link rel="import" href="chrome://apps/constants.html"> +<link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> <dom-module id="app-management-app"> <template> + <style> + :host { + font-size: 13px; + } + </style> <app-management-main-view></app-management-main-view> </template> <script src="chrome://apps/app.js"></script>
diff --git a/chrome/browser/resources/app_management/browser_proxy.html b/chrome/browser/resources/app_management/browser_proxy.html index 0cda55070..8667e7b0 100644 --- a/chrome/browser/resources/app_management/browser_proxy.html +++ b/chrome/browser/resources/app_management/browser_proxy.html
@@ -2,4 +2,9 @@ <script src="browser_proxy.js"></script> <script src="fake_page_handler.js"></script> <script src="chrome://resources/js/mojo_bindings_lite.js"></script> +<script src="big_buffer.mojom-lite.js"></script> +<script src="image_info.mojom-lite.js"></script> +<script src="bitmap.mojom-lite.js"></script> +<script src="image.mojom-lite.js"></script> +<script src="types.mojom-lite.js"></script> <script src="app_management.mojom-lite.js"></script>
diff --git a/chrome/browser/resources/app_management/constants.html b/chrome/browser/resources/app_management/constants.html new file mode 100644 index 0000000..0512320 --- /dev/null +++ b/chrome/browser/resources/app_management/constants.html
@@ -0,0 +1 @@ +<script src="chrome://apps/constants.js"></script>
diff --git a/chrome/browser/resources/app_management/constants.js b/chrome/browser/resources/app_management/constants.js new file mode 100644 index 0000000..0f317adc --- /dev/null +++ b/chrome/browser/resources/app_management/constants.js
@@ -0,0 +1,6 @@ +// 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. + +/** @const {number} */ +const NUMBER_OF_APP_DISPLAYED_DEFAULT = 4;
diff --git a/chrome/browser/resources/app_management/fake_page_handler.js b/chrome/browser/resources/app_management/fake_page_handler.js index dc66470..ebac657 100644 --- a/chrome/browser/resources/app_management/fake_page_handler.js +++ b/chrome/browser/resources/app_management/fake_page_handler.js
@@ -8,18 +8,38 @@ constructor(page) { /** @type {appManagement.mojom.PageInterface} */ this.page = page; + + /** @type {!Array<appManagement.mojom.App>} */ + this.apps_ = [ + this.createApp('ahfgeienlihckogmohjhadlkjgocpleb'), + this.createApp( + 'aohghmighlieiainnegkcijnfilokake', + {type: apps.mojom.AppType.kArc}), + this.createApp('blpcfgokakmgnkcojhhkbfbldkacnbeo'), + this.createApp('pjkljhegncpnkpknbcohdijeoejaedia'), + this.createApp('aapocclcgogkmnckokdopfmhonfmgoek'), + ]; } getApps() { - const fakeAppIdList = [ - 'ahfgeienlihckogmohjhadlkjgocpleb', - 'aohghmighlieiainnegkcijnfilokake', - 'blpcfgokakmgnkcojhhkbfbldkacnbeo', - 'pjkljhegncpnkpknbcohdijeoejaedia', - 'aapocclcgogkmnckokdopfmhonfmgoek', - ]; + this.page.onAppsAdded(this.apps_); + } - this.page.onAppsAdded(fakeAppIdList); + /** + * @param {string} id + * @param {Object=} config + * @return {!appManagement.mojom.App} + */ + createApp(id, config) { + const app = /** @type {!appManagement.mojom.App} */ ({ + id: id, + type: apps.mojom.AppType.kUnknown, + title: 'App Title', + }); + if (config) + Object.assign(app, config); + + return app; } }
diff --git a/chrome/browser/resources/app_management/main_view.html b/chrome/browser/resources/app_management/main_view.html index cd6d891..83d82c05 100644 --- a/chrome/browser/resources/app_management/main_view.html +++ b/chrome/browser/resources/app_management/main_view.html
@@ -2,10 +2,14 @@ <link rel="import" href="chrome://resources/cr_elements/cr_toolbar/cr_toolbar.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> +<link rel="import" href="chrome://resources/html/icon.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html"> <dom-module id="app-management-main-view"> <template> - <style> + <style include="cr-hidden-style"> :host { --primary-text-color: rgba(0, 0, 0, 0.87); --secondary-text-color: rgba(0, 0, 0, 0.54); @@ -41,43 +45,81 @@ height: 64px; } - #app-icon { + .app-icon { height: 32px; margin-inline-end: 20px; margin-inline-start: 24px; width: 32px; } - #app-title { + .app-title { flex: 1; overflow: hidden; text-overflow: ellipsis; } - #subpage-arrow { + .subpage-arrow { margin-inline-end: 8px; padding: 12px; } + #app-list-title { + color: var(--card-title-text-color); + font-weight: 400; + padding: 16px 24px; + } + #more-apps { + align-items: center; border-top: 1px solid rgba(0, 0, 0, 0.12); color: var(--secondary-text-color); - padding: 16px 24px; + display: flex; + height: 50px; + justify-content: space-between; + padding-inline-start: 24px; + } + + #right-button { + height: 36px; + margin-inline-end: 12px; + width: 36px; } </style> <cr-toolbar page-name="$i18n{title}" search-prompt="$i18n{searchPrompt}"> </cr-toolbar> <div id="app-list"> <div id="app-list-title">$i18n{appListTitle}</div> - <template is="dom-repeat" items="[[apps_]]"> + <template is="dom-repeat" items="[[displayedApps_]]"> <div class="app-list-item"> - <img id="app-icon" src="[[iconUrlFromId_(item)]]"> - <div id="app-title">[[item]]</div> - <img id="subpage-arrow" + <img class="app-icon" src="[[iconUrlFromId_(item.id)]]"> + <div class="app-title">[[item.id]]</div> + <img class="subpage-arrow" src="chrome://resources/images/arrow_right.svg"> </div> </template> - <div id="more-apps">$i18n{moreApps}</div> + + <iron-collapse opened="[[listExpanded_]]"> + <div> + <template is="dom-repeat" items="[[collapsedApps_]]"> + <div class="app-list-item"> + <img class="app-icon" src="[[iconUrlFromId_(item)]]"> + <div class="app-title">[[item]]</div> + <img class="subpage-arrow" + src="chrome://resources/images/arrow_right.svg"> + </div> + </template> + </div> + </iron-collapse> + <div id="more-apps" on-click="toggleListExpanded_"> + <span>[[moreAppsString_(apps_.length, listExpanded_)]]</span> + <paper-icon-button-light id="right-button"> + <button id="collapse-button"> + <iron-icon icon="[[getCollapsedIcon_(listExpanded_)]]" + id="dropdown-indicator"> + </iron-icon> + </button> + </paper-icon-button-light> + </div> </div> </template> <script src="chrome://apps/main_view.js"></script>
diff --git a/chrome/browser/resources/app_management/main_view.js b/chrome/browser/resources/app_management/main_view.js index 6d6d966..94a2e09 100644 --- a/chrome/browser/resources/app_management/main_view.js +++ b/chrome/browser/resources/app_management/main_view.js
@@ -6,8 +6,40 @@ is: 'app-management-main-view', properties: { + /** + * List of all apps. + * @private {Array<string>} + */ apps_: { type: Array, + value: () => [], + observer: 'onAppsChanged_', + + }, + /** + * List of apps displayed before expanding the app list. + * @private {Array<string>} + */ + displayedApps_: { + type: Array, + value: () => [], + }, + + /** + * List of apps displayed after expanding app list. + * @private {Array<string>} + */ + collapsedApps_: { + type: Array, + value: () => [], + }, + + /** + * @private {boolean} + */ + listExpanded_: { + type: Boolean, + value: false, } }, @@ -24,7 +56,53 @@ this.listenerIds_.forEach((id) => callbackRouter.removeListener(id)); }, + /** + * @param {string} id + * @return {string} + * @private + */ iconUrlFromId_: function(id) { return `chrome://extension-icon/${id}/128/1`; - } + }, + + /** + * @param {number} numApps + * @param {boolean} listExpanded + * @return {string} + * @private + */ + moreAppsString_: function(numApps, listExpanded) { + return listExpanded ? + loadTimeData.getString('lessApps') : + loadTimeData.getStringF( + 'moreApps', numApps - NUMBER_OF_APP_DISPLAYED_DEFAULT); + }, + + /** + * @private + */ + toggleListExpanded_: function() { + this.listExpanded_ = !this.listExpanded_; + this.onAppsChanged_(); + }, + + /** + * @private + */ + onAppsChanged_: function() { + this.$['more-apps'].hidden = + this.apps_.length <= NUMBER_OF_APP_DISPLAYED_DEFAULT; + this.displayedApps_ = this.apps_.slice(0, NUMBER_OF_APP_DISPLAYED_DEFAULT); + this.collapsedApps_ = + this.apps_.slice(NUMBER_OF_APP_DISPLAYED_DEFAULT, this.apps_.length); + }, + + /** + * @param {boolean} listExpanded + * @return {string} + * @private + */ + getCollapsedIcon_: function(listExpanded) { + return listExpanded ? 'cr:expand-less' : 'cr:expand-more'; + }, });
diff --git a/chrome/browser/resources/discards/.eslintrc.js b/chrome/browser/resources/bluetooth_internals/.eslintrc.js similarity index 72% rename from chrome/browser/resources/discards/.eslintrc.js rename to chrome/browser/resources/bluetooth_internals/.eslintrc.js index 847d6e995..7a5ac71 100644 --- a/chrome/browser/resources/discards/.eslintrc.js +++ b/chrome/browser/resources/bluetooth_internals/.eslintrc.js
@@ -3,11 +3,8 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { - 'no-var': 'error', + 'no-var': 'off', + 'prefer-const': 'off', }, };
diff --git a/chrome/browser/resources/discards/.eslintrc.js b/chrome/browser/resources/chromeos/.eslintrc.js similarity index 72% copy from chrome/browser/resources/discards/.eslintrc.js copy to chrome/browser/resources/chromeos/.eslintrc.js index 847d6e995..7a5ac71 100644 --- a/chrome/browser/resources/discards/.eslintrc.js +++ b/chrome/browser/resources/chromeos/.eslintrc.js
@@ -3,11 +3,8 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { - 'no-var': 'error', + 'no-var': 'off', + 'prefer-const': 'off', }, };
diff --git a/chrome/browser/resources/chromeos/chromevox/.eslintrc.js b/chrome/browser/resources/chromeos/chromevox/.eslintrc.js index edc99c05..828d065 100644 --- a/chrome/browser/resources/chromeos/chromevox/.eslintrc.js +++ b/chrome/browser/resources/chromeos/chromevox/.eslintrc.js
@@ -3,10 +3,6 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { // Override restrictions for document.getElementById usage since, // chrome://resources/js/util.js is not accessible for chromevox.
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs index 7c7e329f..b53c461 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs
@@ -114,7 +114,8 @@ /** * Test feedback when an editable text field gets focus. */ -TEST_F('ChromeVoxEventWatcherUnitTest', 'TextFocusFeedback', function() { +// Flaky on Chromium OS: crbug.com/622387, crbug.com/912390. +TEST_F('ChromeVoxEventWatcherUnitTest', 'DISABLED_TextFocusFeedback', function() { this.loadHtml('<div>' + '<label for="mytext">Label</label>' + '<input id="mytext" value="Value" title="Title" />' + @@ -143,7 +144,8 @@ * Test feedback when an item in an dialog receives focus and then focus * leaves the dialog. */ -TEST_F('ChromeVoxEventWatcherUnitTest', 'DialogFeedback', function() { +// Flaky on Chromium OS: crbug.com/622387. +TEST_F('ChromeVoxEventWatcherUnitTest', 'DISABLED_DialogFeedback', function() { this.loadHtml('<div>' + '<button id="show">Show</button>' + '<div aria-label="compose message" role="dialog">' + @@ -190,7 +192,8 @@ * quickly - make sure the notification that we entered the dialog * isn't interrupted. */ -TEST_F('ChromeVoxEventWatcherUnitTest', 'DoubleFocusAlertDialogFeedback', +// Flaky on Chromium OS: crbug.com/622387, crbug.com/912390. +TEST_F('ChromeVoxEventWatcherUnitTest', 'DISABLED_DoubleFocusAlertDialogFeedback', function() { this.loadHtml('<div>' + '<div role="alertdialog">' + @@ -250,7 +253,8 @@ /** * Test feedback when a list box with an active descendant receives focus. */ -TEST_F('ChromeVoxEventWatcherUnitTest', 'ListBoxFeedback', function() { +// Flaky on Chromium OS: crbug.com/622387. +TEST_F('ChromeVoxEventWatcherUnitTest', 'DISABLED_ListBoxFeedback', function() { this.loadHtml('<div>' + '<p id="before">My listbox</p>' + '<div id="listbox" role="listbox" tabindex="0"' + @@ -680,7 +684,8 @@ * Test that ChromeVox speaks the correct state when a focused control * changes as the result of a key up, not just key down. */ -TEST_F('ChromeVoxEventWatcherUnitTest', 'ToggleOnKeyUp', function() { +// Flaky on Chromium OS: crbug.com/622387, crbug.com/912390. +TEST_F('ChromeVoxEventWatcherUnitTest', 'DISABLED_ToggleOnKeyUp', function() { this.loadHtml('<div>' + '<div tabIndex=0 id="pressable" role="button" aria-pressed="false">' + 'Toggle' +
diff --git a/chrome/browser/resources/chromeos/multidevice_setup/.eslintrc.js b/chrome/browser/resources/chromeos/multidevice_setup/.eslintrc.js deleted file mode 100644 index 25e21f9..0000000 --- a/chrome/browser/resources/chromeos/multidevice_setup/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/chromeos/select_to_speak/.eslintrc.js b/chrome/browser/resources/chromeos/select_to_speak/.eslintrc.js index 1521554..69265a6 100644 --- a/chrome/browser/resources/chromeos/select_to_speak/.eslintrc.js +++ b/chrome/browser/resources/chromeos/select_to_speak/.eslintrc.js
@@ -3,7 +3,6 @@ // found in the LICENSE file. module.exports = { - 'env': {'browser': true, 'es6': true}, 'rules': { // Override restrictions for document.getElementById usage since, // chrome://resources/js/util.js is not accessible for select_to_speak.
diff --git a/chrome/browser/resources/chromeos/switch_access/.eslintrc.js b/chrome/browser/resources/chromeos/switch_access/.eslintrc.js index 426c3ac5..fbf0dc3 100644 --- a/chrome/browser/resources/chromeos/switch_access/.eslintrc.js +++ b/chrome/browser/resources/chromeos/switch_access/.eslintrc.js
@@ -3,7 +3,6 @@ // found in the LICENSE file. module.exports = { - 'env': {'browser': true, 'es6': true}, 'rules': { // Override restrictions for document.getElementById usage since // chrome://resources/js/util.js is not accessible for switch_access.
diff --git a/chrome/browser/resources/eoc_internals/.eslintrc.js b/chrome/browser/resources/cryptotoken/.eslintrc.js similarity index 72% copy from chrome/browser/resources/eoc_internals/.eslintrc.js copy to chrome/browser/resources/cryptotoken/.eslintrc.js index 2d14fd3..d9797b1 100644 --- a/chrome/browser/resources/eoc_internals/.eslintrc.js +++ b/chrome/browser/resources/cryptotoken/.eslintrc.js
@@ -3,11 +3,8 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { - 'no-var': 'error', + 'no-var': 'off', + 'prefer-const': 'off', }, -}; \ No newline at end of file +};
diff --git a/chrome/browser/resources/cryptotoken/enroller.js b/chrome/browser/resources/cryptotoken/enroller.js index 473f178..a71b2b1 100644 --- a/chrome/browser/resources/cryptotoken/enroller.js +++ b/chrome/browser/resources/cryptotoken/enroller.js
@@ -830,6 +830,7 @@ if (v2Challenge && shouldUseWebAuthn) { // If we can proxy to WebAuthn, send the request via WebAuthn. + console.log('Proxying registration request to WebAuthn'); this.doRegisterWebAuthn_(enrollAppIds[0], v2Challenge, request); } else { self.handler_ =
diff --git a/chrome/browser/resources/cryptotoken/signer.js b/chrome/browser/resources/cryptotoken/signer.js index 9cbb78d..9e363927 100644 --- a/chrome/browser/resources/cryptotoken/signer.js +++ b/chrome/browser/resources/cryptotoken/signer.js
@@ -465,6 +465,7 @@ }).then(shouldUseWebAuthn => { if (shouldUseWebAuthn) { // If we can proxy to WebAuthn, send the request via WebAuthn. + console.log('Proxying sign request to WebAuthn'); return this.doSignWebAuthn_(encodedChallenges, challengeVal); } var request = makeSignHelperRequest(
diff --git a/chrome/browser/resources/hangout_services/manifest.json b/chrome/browser/resources/hangout_services/manifest.json index 163319d..8c0017e6 100644 --- a/chrome/browser/resources/hangout_services/manifest.json +++ b/chrome/browser/resources/hangout_services/manifest.json
@@ -5,7 +5,7 @@ "name": "Google Hangouts", // Note: Always update the version number when this file is updated. Chrome // triggers extension preferences update on the version increase. - "version": "1.3.11", + "version": "1.3.12", "manifest_version": 2, "externally_connectable": { "matches": [
diff --git a/chrome/browser/resources/hangout_services/thunk.js b/chrome/browser/resources/hangout_services/thunk.js index 471f7ac0..45ab2d7 100644 --- a/chrome/browser/resources/hangout_services/thunk.js +++ b/chrome/browser/resources/hangout_services/thunk.js
@@ -182,7 +182,7 @@ } else if (method == 'logging.startEventLogging') { const peerConnectionId = message['peerConnectionId'] || ''; const maxLogSizeBytes = message['maxLogSizeBytes'] || 0; - const outputPeriodMs = message['outputPeriodMs'] || 0; + const outputPeriodMs = message['outputPeriodMs'] || -1; const webAppId = message['webAppId'] || 0; chrome.webrtcLoggingPrivate.startEventLogging( requestInfo, origin, peerConnectionId, maxLogSizeBytes,
diff --git a/chrome/browser/resources/discards/.eslintrc.js b/chrome/browser/resources/local_ntp/.eslintrc.js similarity index 72% copy from chrome/browser/resources/discards/.eslintrc.js copy to chrome/browser/resources/local_ntp/.eslintrc.js index 847d6e995..7a5ac71 100644 --- a/chrome/browser/resources/discards/.eslintrc.js +++ b/chrome/browser/resources/local_ntp/.eslintrc.js
@@ -3,11 +3,8 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { - 'no-var': 'error', + 'no-var': 'off', + 'prefer-const': 'off', }, };
diff --git a/chrome/browser/resources/local_ntp/most_visited_single.css b/chrome/browser/resources/local_ntp/most_visited_single.css index 4bedf47..4f06496 100644 --- a/chrome/browser/resources/local_ntp/most_visited_single.css +++ b/chrome/browser/resources/local_ntp/most_visited_single.css
@@ -21,6 +21,7 @@ --md-tile-width: 112px; --md-title-font-size: 12px; --md-title-height: 24px; + --md-title-max-height: 28px; /* May be overridden by themes (on the body element). */ @@ -204,6 +205,7 @@ font-family: 'Roboto', arial, sans-serif; font-size: var(--md-title-font-size); font-weight: 500; + max-height: var(--md-title-max-height); overflow: hidden; text-align: center; text-overflow: ellipsis;
diff --git a/chrome/browser/resources/management/.eslintrc.js b/chrome/browser/resources/management/.eslintrc.js deleted file mode 100644 index 25e21f9..0000000 --- a/chrome/browser/resources/management/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/md_bookmarks/.eslintrc.js b/chrome/browser/resources/md_bookmarks/.eslintrc.js deleted file mode 100644 index 847d6e995..0000000 --- a/chrome/browser/resources/md_bookmarks/.eslintrc.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/md_downloads/.eslintrc.js b/chrome/browser/resources/md_downloads/.eslintrc.js deleted file mode 100644 index 847d6e995..0000000 --- a/chrome/browser/resources/md_downloads/.eslintrc.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/md_downloads/BUILD.gn b/chrome/browser/resources/md_downloads/BUILD.gn index f42010f..8d5c80c0 100644 --- a/chrome/browser/resources/md_downloads/BUILD.gn +++ b/chrome/browser/resources/md_downloads/BUILD.gn
@@ -25,7 +25,6 @@ ":browser_proxy", ":constants", ":downloads", - ":externs", ":item", ":manager", ":search_service", @@ -35,9 +34,10 @@ js_library("browser_proxy") { deps = [ - ":externs", + "//chrome/browser/ui/webui/md_downloads:mojo_bindings_js_externs", "//ui/webui/resources/js:cr", ] + externs_list = [ "externs.js" ] } js_library("constants") { @@ -53,11 +53,11 @@ ] } -js_library("externs") { - extra_deps = [ "//chrome/browser/ui/webui/md_downloads:mojo_bindings_js" ] - externs_list = [ - "$root_gen_dir/chrome/browser/ui/webui/md_downloads/md_downloads.mojom-lite.externs.js", - "$externs_path/mojo.js", +js_library("icon_loader") { + deps = [ + "//ui/webui/resources/js:assert", + "//ui/webui/resources/js:cr", + "//ui/webui/resources/js:icon", ] } @@ -65,7 +65,7 @@ deps = [ ":browser_proxy", ":constants", - ":externs", + ":icon_loader", "//third_party/polymer/v1_0/components-chromium/paper-behaviors:paper-inky-focus-behavior-extracted", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:load_time_data", @@ -76,7 +76,6 @@ js_library("manager") { deps = [ ":browser_proxy", - ":externs", ":item", ":search_service", ":toolbar", @@ -93,7 +92,6 @@ js_library("search_service") { deps = [ ":browser_proxy", - ":externs", "//ui/webui/resources/js:cr", "//ui/webui/resources/js:load_time_data", ]
diff --git a/chrome/browser/resources/md_downloads/icon_loader.html b/chrome/browser/resources/md_downloads/icon_loader.html new file mode 100644 index 0000000..d489d71 --- /dev/null +++ b/chrome/browser/resources/md_downloads/icon_loader.html
@@ -0,0 +1,4 @@ +<link rel="import" href="chrome://resources/html/assert.html"> +<link rel="import" href="chrome://resources/html/cr.html"> +<link rel="import" href="chrome://resources/html/icon.html"> +<script src="chrome://downloads/icon_loader.js"></script>
diff --git a/chrome/browser/resources/md_downloads/icon_loader.js b/chrome/browser/resources/md_downloads/icon_loader.js new file mode 100644 index 0000000..5cc35d9 --- /dev/null +++ b/chrome/browser/resources/md_downloads/icon_loader.js
@@ -0,0 +1,52 @@ +// 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. + +cr.define('downloads', function() { + class IconLoader { + constructor() { + /** @private {!Object<!PromiseResolver<boolean>>} */ + this.iconResolvers_ = {}; + + /** @private {!Set<!HTMLImageElement>} */ + this.listeningImages_ = new Set(); + } + + /** + * @param {!HTMLImageElement} imageEl + * @param {string} filePath + * @return {!Promise<boolean>} Whether or not the icon loaded successfully. + */ + loadIcon(imageEl, filePath) { + const url = cr.icon.getFileIconUrl(filePath); + + if (!this.iconResolvers_[url]) { + this.iconResolvers_[url] = new PromiseResolver(); + } + + if (!this.listeningImages_.has(imageEl)) { + imageEl.addEventListener('load', this.finishedLoading_.bind(this)); + imageEl.addEventListener('error', this.finishedLoading_.bind(this)); + this.listeningImages_.add(imageEl); + } + + imageEl.src = url; + + return assert(this.iconResolvers_[url]).promise; + } + + /** + * @param {!Event} e + * @private + */ + finishedLoading_(e) { + const resolver = assert(this.iconResolvers_[e.currentTarget.src]); + if (!resolver.isFulfilled) + resolver.resolve(e.type == 'load'); + } + } + + cr.addSingletonGetter(IconLoader); + + return {IconLoader: IconLoader}; +});
diff --git a/chrome/browser/resources/md_downloads/item.html b/chrome/browser/resources/md_downloads/item.html index 23f0a0e..97ae687 100644 --- a/chrome/browser/resources/md_downloads/item.html +++ b/chrome/browser/resources/md_downloads/item.html
@@ -16,6 +16,7 @@ <link rel="import" href="chrome://downloads/browser_proxy.html"> <link rel="import" href="chrome://downloads/constants.html"> <link rel="import" href="chrome://downloads/i18n_setup.html"> +<link rel="import" href="chrome://downloads/icon_loader.html"> <link rel="import" href="chrome://downloads/icons.html"> <dom-module id="downloads-item"> @@ -93,11 +94,16 @@ margin: 0 24px; } - .icon { + .icon, + #file-icon-wrapper { height: 32px; width: 32px; } + #file-icon-wrapper { + overflow: hidden; /* Reduces file icon flicker on initial load. */ + } + #content:-webkit-any(.show-progress, .dangerous) #file-icon-wrapper { /* TODO(dbeam): animate from top-aligned to centered when items finish? */ @@ -110,12 +116,11 @@ opacity: .5; } - #danger-icon { - height: 32px; - width: 32px; + #file-icon-wrapper iron-icon[icon='cr:insert-drive-file'] { + color: var(--paper-grey-400); } - #danger-icon[icon='cr:warning'], + #file-icon-wrapper iron-icon[icon='cr:warning'], .dangerous #description { color: var(--google-red-700); } @@ -233,10 +238,10 @@ <div id="content" on-dragstart="onDragStart_" class$="[[computeClass_(isActive_, isDangerous_, showProgress_)]]"> <div id="file-icon-wrapper" class="icon-wrapper"> - <img class="icon" id="file-icon" alt="" hidden="[[isDangerous_]]"> - <iron-icon id="danger-icon" - icon$="[[computeDangerIcon_(isDangerous_, data.dangerType)]]" - hidden="[[!isDangerous_]]"></iron-icon> + <img class="icon" id="file-icon" alt="" hidden="[[!useFileIcon_]]"> + <iron-icon class="icon" icon$="[[computeIcon_( + isDangerous_, data.dangerType, useFileIcon_)]]" + hidden="[[useFileIcon_]]"></iron-icon> </div> <div id="details">
diff --git a/chrome/browser/resources/md_downloads/item.js b/chrome/browser/resources/md_downloads/item.js index f08f18b..55542383 100644 --- a/chrome/browser/resources/md_downloads/item.js +++ b/chrome/browser/resources/md_downloads/item.js
@@ -85,6 +85,8 @@ type: Boolean, value: false, }, + + useFileIcon_: Boolean, }, observers: [ @@ -103,6 +105,11 @@ this.content = this.$.content; }, + /** @return {!HTMLElement} */ + getFileIcon: function() { + return assert(this.$['file-icon']); + }, + /** * @param {string} url * @return {string} A reasonably long URL. @@ -163,14 +170,6 @@ * @return {string} * @private */ - computeDangerIcon_: function() { - return this.isDangerous_ ? 'cr:warning' : ''; - }, - - /** - * @return {string} - * @private - */ computeDate_: function() { assert(typeof this.data.hideDate == 'boolean'); if (this.data.hideDate) @@ -214,6 +213,18 @@ }, /** + * @return {string} + * @private + */ + computeIcon_: function() { + if (this.isDangerous_) + return 'cr:warning'; + if (!this.useFileIcon_) + return 'cr:insert-drive-file'; + return ''; + }, + + /** * @return {boolean} * @private */ @@ -345,11 +356,16 @@ if (this.isDangerous_) { this.$.url.removeAttribute('href'); + this.useFileIcon_ = false; } else { this.$.url.href = assert(this.data.url); - const filePath = encodeURIComponent(this.data.filePath); - const scaleFactor = `?scale=${window.devicePixelRatio}x`; - this.$['file-icon'].src = `chrome://fileicon/${filePath}${scaleFactor}`; + const path = this.data.filePath; + downloads.IconLoader.getInstance() + .loadIcon(this.$['file-icon'], path) + .then(success => { + if (path == this.data.filePath) + this.useFileIcon_ = success; + }); } },
diff --git a/chrome/browser/resources/md_extensions/.eslintrc.js b/chrome/browser/resources/md_extensions/.eslintrc.js deleted file mode 100644 index 847d6e995..0000000 --- a/chrome/browser/resources/md_extensions/.eslintrc.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/md_history/.eslintrc.js b/chrome/browser/resources/md_history/.eslintrc.js deleted file mode 100644 index 25e21f9..0000000 --- a/chrome/browser/resources/md_history/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/md_user_manager/.eslintrc.js b/chrome/browser/resources/md_user_manager/.eslintrc.js deleted file mode 100644 index 25e21f9..0000000 --- a/chrome/browser/resources/md_user_manager/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/discards/.eslintrc.js b/chrome/browser/resources/media_router/.eslintrc.js similarity index 72% copy from chrome/browser/resources/discards/.eslintrc.js copy to chrome/browser/resources/media_router/.eslintrc.js index 847d6e995..7a5ac71 100644 --- a/chrome/browser/resources/discards/.eslintrc.js +++ b/chrome/browser/resources/media_router/.eslintrc.js
@@ -3,11 +3,8 @@ // found in the LICENSE file. module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, 'rules': { - 'no-var': 'error', + 'no-var': 'off', + 'prefer-const': 'off', }, };
diff --git a/chrome/browser/resources/omnibox/.eslintrc.js b/chrome/browser/resources/omnibox/.eslintrc.js deleted file mode 100644 index 25e21f9..0000000 --- a/chrome/browser/resources/omnibox/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/pdf/.eslintrc.js b/chrome/browser/resources/pdf/.eslintrc.js deleted file mode 100644 index b3c9604..0000000 --- a/chrome/browser/resources/pdf/.eslintrc.js +++ /dev/null
@@ -1,14 +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. - -module.exports = { - env: { - 'browser': true, - 'es6': true, - }, - rules: { - 'no-var': 'error', - 'prefer-const': 'error', - }, -};
diff --git a/chrome/browser/resources/print_preview/.eslintrc.js b/chrome/browser/resources/print_preview/.eslintrc.js deleted file mode 100644 index 847d6e995..0000000 --- a/chrome/browser/resources/print_preview/.eslintrc.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/print_preview/data/destination.js b/chrome/browser/resources/print_preview/data/destination.js index 07c5429..074a2bb 100644 --- a/chrome/browser/resources/print_preview/data/destination.js +++ b/chrome/browser/resources/print_preview/data/destination.js
@@ -666,7 +666,7 @@ return 'print-preview:save-to-drive'; } if (this.id_ == Destination.GooglePromotedId.SAVE_AS_PDF) { - return 'print-preview:insert-drive-file'; + return 'cr:insert-drive-file'; } if (this.isEnterprisePrinter) { return 'print-preview:business';
diff --git a/chrome/browser/resources/print_preview/icons.html b/chrome/browser/resources/print_preview/icons.html index fd95a48..c5b3efa5 100644 --- a/chrome/browser/resources/print_preview/icons.html +++ b/chrome/browser/resources/print_preview/icons.html
@@ -27,7 +27,6 @@ See http://goo.gl/Y1OdAq for instructions on adding additional icons. --> <g id="business"><path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"></path></g> - <g id="insert-drive-file"><path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z"></path></g> <g id="smartphone"><path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"></path></g> <g id="cloud-queue"><path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h.71C7.37 7.69 9.48 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3s-1.34 3-3 3z"></path></g> <g id="print"><path d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"></path></g>
diff --git a/chrome/browser/resources/print_preview/new/destination_dialog.html b/chrome/browser/resources/print_preview/new/destination_dialog.html index df15f8c4..be40d8e 100644 --- a/chrome/browser/resources/print_preview/new/destination_dialog.html +++ b/chrome/browser/resources/print_preview/new/destination_dialog.html
@@ -2,6 +2,7 @@ <link rel="import" href="chrome://resources/cr_elements/cr_dialog/cr_dialog.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/cr_elements/paper_button_style_css.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> /* The imports below are needed as an action-link is added to the promo-text
diff --git a/chrome/browser/resources/print_preview/new/destination_list_item.html b/chrome/browser/resources/print_preview/new/destination_list_item.html index 5011bea..f67e5b4 100644 --- a/chrome/browser/resources/print_preview/new/destination_list_item.html +++ b/chrome/browser/resources/print_preview/new/destination_list_item.html
@@ -1,6 +1,7 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/hidden_style_css.html"> +<link rel="import" href="chrome://resources/cr_elements/icons.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/html/load_time_data.html">
diff --git a/chrome/browser/resources/print_preview/new/pages_settings.html b/chrome/browser/resources/print_preview/new/pages_settings.html index 3231629..dbd3d2e 100644 --- a/chrome/browser/resources/print_preview/new/pages_settings.html +++ b/chrome/browser/resources/print_preview/new/pages_settings.html
@@ -23,11 +23,11 @@ --cr-input-error-display: none; } - :host([error-state_='1']) #customRadioButton, - :host([error-state_='2']) #customRadioButton { - /* Margin = -1 * error height = -1 * (16px + 2 lines * line-height) */ + :host #customRadioButton { --cr-radio-button-disc: { - margin-top: calc(-16px - 2 * .75rem); + align-self: baseline; + /* Margin = (38px row height - 16px disc size) / 2 */ + margin-top: 11px; }; }
diff --git a/chrome/browser/resources/settings/.eslintrc.js b/chrome/browser/resources/settings/.eslintrc.js deleted file mode 100644 index 847d6e995..0000000 --- a/chrome/browser/resources/settings/.eslintrc.js +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/resources/settings/autofill_page/password_list_item.html b/chrome/browser/resources/settings/autofill_page/password_list_item.html index d117558..acf1bc8 100644 --- a/chrome/browser/resources/settings/autofill_page/password_list_item.html +++ b/chrome/browser/resources/settings/autofill_page/password_list_item.html
@@ -30,6 +30,10 @@ font-family: inherit; font-size: inherit; line-height: inherit; + } + + #username, + #password:not([type='password']) { text-overflow: ellipsis; }
diff --git a/chrome/browser/resources/settings/people_page/sync_controls.html b/chrome/browser/resources/settings/people_page/sync_controls.html new file mode 100644 index 0000000..83839137 --- /dev/null +++ b/chrome/browser/resources/settings/people_page/sync_controls.html
@@ -0,0 +1,174 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/html/util.html"> +<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> +<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> +<link rel="import" href="sync_browser_proxy.html"> +<link rel="import" href="../settings_shared_css.html"> +<link rel="import" href="../settings_vars_css.html"> + +<dom-module id="settings-sync-controls"> + <template> + <style include="settings-shared"> + #sync-data-types .list-item:not([hidden]) ~ .list-item:not([hidden]) { + border-top: var(--settings-separator-line); + } + + .list-item { + display: flex; + } + + .list-item > div { + flex: 1; + } + </style> + + <div class="settings-box first"> + <div id="syncEverythingCheckboxLabel" class="start"> + $i18n{syncEverythingCheckboxLabel} + </div> + <cr-toggle id="syncAllDataTypesControl" + checked="{{syncPrefs.syncAllDataTypes}}" + on-change="onSyncAllDataTypesChanged_" + aria-labelledby="syncEverythingCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-frame" id="sync-data-types"> + <div class="list-item" hidden="[[!syncPrefs.appsRegistered]]"> + <div id="appCheckboxLabel"> + $i18n{appCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.appsSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.appsEnforced)]]" + aria-labelledby="appCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.bookmarksRegistered]]"> + <div id="bookmarksCheckboxLabel"> + $i18n{bookmarksCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.bookmarksSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.bookmarksEnforced)]]" + aria-labelledby="bookmarksCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.extensionsRegistered]]"> + <div id="extensionsCheckboxLabel"> + $i18n{extensionsCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.extensionsSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.extensionsEnforced)]]" + aria-labelledby="extensionsCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.typedUrlsRegistered]]"> + <div id="historyCheckboxLabel"> + $i18n{historyCheckboxLabel} + </div> + <!-- TypedUrls has a special on-change handler to deal with user + events. --> + <cr-toggle id="historyToggle" + checked="{{syncPrefs.typedUrlsSynced}}" + on-change="onTypedUrlsDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.typedUrlsEnforced)]]" + aria-labelledby="historyCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.preferencesRegistered]]"> + <div id="settingsCheckboxLabel"> + $i18n{settingsCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.preferencesSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, + syncPrefs.preferencesEnforced)]]" + aria-labelledby="settingsCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.themesRegistered]]"> + <div id="themesAndWallpapersCheckboxLabel"> + $i18n{themesAndWallpapersCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.themesSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.themesEnforced)]]" + aria-labelledby="themesAndWallpapersCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.tabsRegistered]]"> + <div id="openTabsCheckboxLabel"> + $i18n{openTabsCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.tabsSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.tabsEnforced)]]" + aria-labelledby="openTabsCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.passwordsRegistered]]"> + <div id="passwordsCheckboxLabel"> + $i18n{passwordsCheckboxLabel} + </div> + <cr-toggle checked="{{syncPrefs.passwordsSynced}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.passwordsEnforced)]]" + aria-labelledby="passwordsCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.autofillRegistered]]"> + <div id="autofillCheckboxLabel"> + $i18n{autofillCheckboxLabel} + </div> + <!-- Autofill has a special on-change handler to deal with + Payments integration. --> + <cr-toggle checked="{{syncPrefs.autofillSynced}}" + on-change="onAutofillDataTypeChanged_" + disabled="[[shouldSyncCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.autofillEnforced)]]" + aria-labelledby="autofillCheckboxLabel"> + </cr-toggle> + </div> + + <div class="list-item" hidden="[[!syncPrefs.autofillRegistered]]"> + <!-- The Payments integration checkbox is a special case in many + ways. It's visible only if autofill is registered. It's + disabled and unchecked if autofill is unchecked.--> + <div> + $i18n{enablePaymentsIntegrationCheckboxLabel} + <a href="$i18nRaw{autofillHelpURL}" target="_blank"> + $i18n{learnMore} + </a> + </div> + <cr-toggle checked="{{syncPrefs.paymentsIntegrationEnabled}}" + on-change="onSingleSyncDataTypeChanged_" + disabled="[[shouldPaymentsCheckboxBeDisabled_( + syncPrefs.syncAllDataTypes, syncPrefs.autofillSynced)]]" + aria-label="$i18n{enablePaymentsIntegrationCheckboxLabel}"> + </cr-toggle> + </div> + </div> + + </template> + <script src="sync_controls.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/settings/people_page/sync_controls.js b/chrome/browser/resources/settings/people_page/sync_controls.js new file mode 100644 index 0000000..61e5e7bd --- /dev/null +++ b/chrome/browser/resources/settings/people_page/sync_controls.js
@@ -0,0 +1,149 @@ +// 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. + +(function() { + +/** + * Names of the individual data type properties to be cached from + * settings.SyncPrefs when the user checks 'Sync All'. + * @type {!Array<string>} + */ +const SyncPrefsIndividualDataTypes = [ + 'appsSynced', + 'extensionsSynced', + 'preferencesSynced', + 'autofillSynced', + 'typedUrlsSynced', + 'themesSynced', + 'bookmarksSynced', + 'passwordsSynced', + 'tabsSynced', + 'paymentsIntegrationEnabled', +]; + +/** + * @fileoverview + * 'settings-sync-controls' contains all sync data type controls. + */ +Polymer({ + is: 'settings-sync-controls', + + behaviors: [WebUIListenerBehavior], + + properties: { + /** + * The current sync preferences, supplied by SyncBrowserProxy. + * @type {settings.SyncPrefs|undefined} + */ + syncPrefs: Object, + }, + + /** @private {?settings.SyncBrowserProxy} */ + browserProxy_: null, + + /** + * Caches the individually selected synced data types. This is used to + * be able to restore the selections after checking and unchecking Sync All. + * @private {?Object} + */ + cachedSyncPrefs_: null, + + /** @override */ + created: function() { + this.browserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); + }, + + /** @override */ + attached: function() { + this.addWebUIListener( + 'sync-prefs-changed', this.handleSyncPrefsChanged_.bind(this)); + }, + + /** + * Handler for when the sync preferences are updated. + * @private + */ + handleSyncPrefsChanged_: function(syncPrefs) { + this.syncPrefs = syncPrefs; + + // If autofill is not registered or synced, force Payments integration off. + if (!this.syncPrefs.autofillRegistered || !this.syncPrefs.autofillSynced) + this.set('syncPrefs.paymentsIntegrationEnabled', false); + }, + + /** + * Handler for when the sync all data types checkbox is changed. + * @param {!Event} event + * @private + */ + onSyncAllDataTypesChanged_: function(event) { + if (event.target.checked) { + this.set('syncPrefs.syncAllDataTypes', true); + + // Cache the previously selected preference before checking every box. + this.cachedSyncPrefs_ = {}; + for (const dataType of SyncPrefsIndividualDataTypes) { + // These are all booleans, so this shallow copy is sufficient. + this.cachedSyncPrefs_[dataType] = this.syncPrefs[dataType]; + + this.set(['syncPrefs', dataType], true); + } + } else if (this.cachedSyncPrefs_) { + // Restore the previously selected preference. + for (const dataType of SyncPrefsIndividualDataTypes) { + this.set(['syncPrefs', dataType], this.cachedSyncPrefs_[dataType]); + } + } + + this.onSingleSyncDataTypeChanged_(); + }, + + /** + * Handler for when any sync data type checkbox is changed (except autofill). + * @private + */ + onSingleSyncDataTypeChanged_: function() { + assert(this.syncPrefs); + this.browserProxy_.setSyncDatatypes(this.syncPrefs); + }, + + /** + * Handler for when the autofill data type checkbox is changed. + * @private + */ + onAutofillDataTypeChanged_: function() { + this.set( + 'syncPrefs.paymentsIntegrationEnabled', this.syncPrefs.autofillSynced); + + this.onSingleSyncDataTypeChanged_(); + }, + + /** + * Handler for when the autofill data type checkbox is changed. + * @private + */ + onTypedUrlsDataTypeChanged_: function() { + this.onSingleSyncDataTypeChanged_(); + }, + + /** + * @param {boolean} syncAllDataTypes + * @param {boolean} enforced + * @return {boolean} Whether the sync checkbox should be disabled. + */ + shouldSyncCheckboxBeDisabled_: function(syncAllDataTypes, enforced) { + return syncAllDataTypes || enforced; + }, + + /** + * @param {boolean} syncAllDataTypes + * @param {boolean} autofillSynced + * @return {boolean} Whether the sync checkbox should be disabled. + */ + shouldPaymentsCheckboxBeDisabled_: function( + syncAllDataTypes, autofillSynced) { + return syncAllDataTypes || !autofillSynced; + }, +}); +})();
diff --git a/chrome/browser/resources/settings/people_page/sync_page.html b/chrome/browser/resources/settings/people_page/sync_page.html index e510860..36bc482 100644 --- a/chrome/browser/resources/settings/people_page/sync_page.html +++ b/chrome/browser/resources/settings/people_page/sync_page.html
@@ -4,7 +4,6 @@ <link rel="import" href="chrome://resources/html/util.html"> <link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> <link rel="import" href="chrome://resources/cr_elements/cr_input/cr_input.html"> -<link rel="import" href="chrome://resources/cr_elements/cr_toggle/cr_toggle.html"> <link rel="import" href="chrome://resources/cr_elements/cr_radio_button/cr_radio_button.html"> <link rel="import" href="chrome://resources/cr_elements/cr_radio_group/cr_radio_group.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> @@ -12,6 +11,7 @@ <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button-light.html"> <link rel="import" href="sync_browser_proxy.html"> +<link rel="import" href="sync_controls.html"> <link rel="import" href="../icons.html"> <link rel="import" href="../privacy_page/personalization_options.html"> <link rel="import" href="../route.html"> @@ -61,10 +61,6 @@ align-items: center; } - #sync-data-types .list-item:not([hidden]) ~ .list-item:not([hidden]) { - border-top: var(--settings-separator-line); - } - #other-sync-items { padding-bottom: 8px; } @@ -165,7 +161,7 @@ <div id="[[pages_.CONFIGURE]]" hidden$="[[!isStatus_(pages_.CONFIGURE, pageStatus_)]]"> <!-- TODO(http://crbug.com/862983) Remove this section once the Unified - Consent feature is launched. --> + Consent feature is launched. --> <template is="dom-if" if="[[shouldShowExistingPassphraseInSyncSection_( unifiedConsentEnabled, syncPrefs.passphraseRequired)]]"> <div id="existingPassphrase" class="list-frame"> @@ -196,161 +192,7 @@ </div> </template> - <div class="settings-box first"> - <div id="syncEverythingCheckboxLabel" class="start"> - $i18n{syncEverythingCheckboxLabel} - </div> - <cr-toggle id="syncAllDataTypesControl" - checked="{{syncPrefs.syncAllDataTypes}}" - on-change="onSyncAllDataTypesChanged_" - aria-labelledby="syncEverythingCheckboxLabel"> - </cr-toggle> - </div> - - <div class="list-frame" id="sync-data-types"> - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.appsRegistered]]"> - <div id="appCheckboxLabel" class="flex"> - $i18n{appCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.appsSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.appsEnforced)]]" - aria-labelledby="appCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.bookmarksRegistered]]"> - <div id="bookmarksCheckboxLabel" class="flex"> - $i18n{bookmarksCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.bookmarksSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.bookmarksEnforced)]]" - aria-labelledby="bookmarksCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.extensionsRegistered]]"> - <div id="extensionsCheckboxLabel" class="flex"> - $i18n{extensionsCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.extensionsSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.extensionsEnforced)]]" - aria-labelledby="extensionsCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.typedUrlsRegistered]]"> - <div id="historyCheckboxLabel" class="flex"> - $i18n{historyCheckboxLabel} - </div> - <!-- TypedUrls has a special on-change handler to deal with user - events. --> - <cr-toggle id="historyToggle" - checked="{{syncPrefs.typedUrlsSynced}}" - on-change="onTypedUrlsDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.typedUrlsEnforced)]]" - aria-labelledby="historyCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.preferencesRegistered]]"> - <div id="settingsCheckboxLabel" class="flex"> - $i18n{settingsCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.preferencesSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, - syncPrefs.preferencesEnforced)]]" - aria-labelledby="settingsCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.themesRegistered]]"> - <div id="themesAndWallpapersCheckboxLabel" class="flex"> - $i18n{themesAndWallpapersCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.themesSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.themesEnforced)]]" - aria-labelledby="themesAndWallpapersCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.tabsRegistered]]"> - <div id="openTabsCheckboxLabel" class="flex"> - $i18n{openTabsCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.tabsSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.tabsEnforced)]]" - aria-labelledby="openTabsCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.passwordsRegistered]]"> - <div id="passwordsCheckboxLabel" class="flex"> - $i18n{passwordsCheckboxLabel} - </div> - <cr-toggle checked="{{syncPrefs.passwordsSynced}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.passwordsEnforced)]]" - aria-labelledby="passwordsCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.autofillRegistered]]"> - <div id="autofillCheckboxLabel" class="flex"> - $i18n{autofillCheckboxLabel} - </div> - <!-- Autofill has a special on-change handler to deal with - Payments integration. --> - <cr-toggle checked="{{syncPrefs.autofillSynced}}" - on-change="onAutofillDataTypeChanged_" - disabled="[[shouldSyncCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.autofillEnforced)]]" - aria-labelledby="autofillCheckboxLabel"> - </cr-toggle> - </div> - - <div class="layout horizontal list-item" - hidden="[[!syncPrefs.autofillRegistered]]"> - <!-- The Payments integration checkbox is a special case in many - ways. It's visible only if autofill is registered. It's - disabled and unchecked if autofill is unchecked.--> - <div class="flex"> - $i18n{enablePaymentsIntegrationCheckboxLabel} - <a href="$i18nRaw{autofillHelpURL}" target="_blank"> - $i18n{learnMore} - </a> - </div> - <cr-toggle - checked="{{syncPrefs.paymentsIntegrationEnabled}}" - on-change="onSingleSyncDataTypeChanged_" - disabled="[[shouldPaymentsCheckboxBeDisabled_( - syncPrefs.syncAllDataTypes, syncPrefs.autofillSynced)]]" - aria-label="$i18n{enablePaymentsIntegrationCheckboxLabel}"> - </cr-toggle> - </div> - </div> + <settings-sync-controls></settings-sync-controls> <div id="other-sync-items" class$="[[getListFrameClass_(unifiedConsentEnabled)]]"> @@ -455,6 +297,7 @@ </div> </div> </div> + <template is="dom-if" if="[[unifiedConsentEnabled]]"> <div class="settings-box first"> <h2>$i18n{nonPersonalizedServicesSectionLabel}</h2>
diff --git a/chrome/browser/resources/settings/people_page/sync_page.js b/chrome/browser/resources/settings/people_page/sync_page.js index 0822a2da..4596795 100644 --- a/chrome/browser/resources/settings/people_page/sync_page.js +++ b/chrome/browser/resources/settings/people_page/sync_page.js
@@ -15,24 +15,6 @@ }; /** - * Names of the individual data type properties to be cached from - * settings.SyncPrefs when the user checks 'Sync All'. - * @type {!Array<string>} - */ -const SyncPrefsIndividualDataTypes = [ - 'appsSynced', - 'extensionsSynced', - 'preferencesSynced', - 'autofillSynced', - 'typedUrlsSynced', - 'themesSynced', - 'bookmarksSynced', - 'passwordsSynced', - 'tabsSynced', - 'paymentsIntegrationEnabled', -]; - -/** * @fileoverview * 'settings-sync-page' is the settings page containing sync settings. */ @@ -187,13 +169,6 @@ */ didAbort_: false, - /** - * Caches the individually selected synced data types. This is used to - * be able to restore the selections after checking and unchecking Sync All. - * @private {?Object} - */ - cachedSyncPrefs_: null, - /** @override */ created: function() { this.browserProxy_ = settings.SyncBrowserProxyImpl.getInstance(); @@ -300,10 +275,6 @@ this.syncPrefs = syncPrefs; this.pageStatus_ = settings.PageStatus.CONFIGURE; - // If autofill is not registered or synced, force Payments integration off. - if (!this.syncPrefs.autofillRegistered || !this.syncPrefs.autofillSynced) - this.set('syncPrefs.paymentsIntegrationEnabled', false); - // Hide the new passphrase box if the sync data has been encrypted. if (this.syncPrefs.encryptAllData) this.creatingNewPassphrase_ = false; @@ -320,68 +291,12 @@ } }, - /** - * Handler for when the sync all data types checkbox is changed. - * @param {!Event} event - * @private - */ - onSyncAllDataTypesChanged_: function(event) { - if (event.target.checked) { - this.set('syncPrefs.syncAllDataTypes', true); - - // Cache the previously selected preference before checking every box. - this.cachedSyncPrefs_ = {}; - for (const dataType of SyncPrefsIndividualDataTypes) { - // These are all booleans, so this shallow copy is sufficient. - this.cachedSyncPrefs_[dataType] = this.syncPrefs[dataType]; - - this.set(['syncPrefs', dataType], true); - } - } else if (this.cachedSyncPrefs_) { - // Restore the previously selected preference. - for (const dataType of SyncPrefsIndividualDataTypes) { - this.set(['syncPrefs', dataType], this.cachedSyncPrefs_[dataType]); - } - } - - this.onSingleSyncDataTypeChanged_(); - }, - - /** - * Handler for when any sync data type checkbox is changed (except autofill). - * @private - */ - onSingleSyncDataTypeChanged_: function() { - assert(this.syncPrefs); - this.browserProxy_.setSyncDatatypes(this.syncPrefs) - .then(this.handlePageStatusChanged_.bind(this)); - }, - /** @private */ onActivityControlsTap_: function() { this.browserProxy_.openActivityControlsUrl(); }, /** - * Handler for when the autofill data type checkbox is changed. - * @private - */ - onAutofillDataTypeChanged_: function() { - this.set( - 'syncPrefs.paymentsIntegrationEnabled', this.syncPrefs.autofillSynced); - - this.onSingleSyncDataTypeChanged_(); - }, - - /** - * Handler for when the autofill data type checkbox is changed. - * @private - */ - onTypedUrlsDataTypeChanged_: function() { - this.onSingleSyncDataTypeChanged_(); - }, - - /** * @param {string} passphrase The passphrase input field value * @param {string} confirmation The passphrase confirmation input field value. * @return {boolean} Whether the passphrase save button should be enabled. @@ -497,25 +412,6 @@ }, /** - * @param {boolean} syncAllDataTypes - * @param {boolean} enforced - * @return {boolean} Whether the sync checkbox should be disabled. - */ - shouldSyncCheckboxBeDisabled_: function(syncAllDataTypes, enforced) { - return syncAllDataTypes || enforced; - }, - - /** - * @param {boolean} syncAllDataTypes - * @param {boolean} autofillSynced - * @return {boolean} Whether the sync checkbox should be disabled. - */ - shouldPaymentsCheckboxBeDisabled_: function( - syncAllDataTypes, autofillSynced) { - return syncAllDataTypes || !autofillSynced; - }, - - /** * Checks the supplied passphrases to ensure that they are not empty and that * they match each other. Additionally, displays error UI if they are invalid. * @return {boolean} Whether the check was successful (i.e., that the
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd index 83686579..e92e342 100644 --- a/chrome/browser/resources/settings/settings_resources.grd +++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -1139,7 +1139,16 @@ type="chrome_html" preprocess="true" allowexternalscript="true" /> - <structure name="IDR_SETTINGS_SYNC_PAGE_JS" + <structure name="IDR_SETTINGS_SYNC_CONTROLS_JS" + file="people_page/sync_controls.js" + type="chrome_html" + preprocess="true" /> + <structure name="IDR_SETTINGS_SYNC_CONTROLS_HTML" + file="people_page/sync_controls.html" + type="chrome_html" + preprocess="true" + allowexternalscript="true" /> + <structure name="IDR_SETTINGS_SYNC_PAGE_JS" file="people_page/sync_page.js" type="chrome_html" preprocess="true" />
diff --git a/chrome/browser/resources/snippets_internals/.eslintrc.js b/chrome/browser/resources/snippets_internals/.eslintrc.js deleted file mode 100644 index 2d14fd3..0000000 --- a/chrome/browser/resources/snippets_internals/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -}; \ No newline at end of file
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/.eslintrc.js b/chrome/browser/resources/welcome/onboarding_welcome/.eslintrc.js deleted file mode 100644 index 25e21f9..0000000 --- a/chrome/browser/resources/welcome/onboarding_welcome/.eslintrc.js +++ /dev/null
@@ -1,13 +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. - -module.exports = { - 'env': { - 'browser': true, - 'es6': true, - }, - 'rules': { - 'no-var': 'error', - }, -};
diff --git a/chrome/browser/supervised_user/supervised_user_url_filter.cc b/chrome/browser/supervised_user/supervised_user_url_filter.cc index df15087..9e63e58 100644 --- a/chrome/browser/supervised_user/supervised_user_url_filter.cc +++ b/chrome/browser/supervised_user/supervised_user_url_filter.cc
@@ -8,10 +8,10 @@ #include <stdint.h> #include <set> +#include <unordered_map> #include <utility> #include "base/containers/flat_set.h" -#include "base/containers/hash_tables.h" #include "base/files/file_path.h" #include "base/json/json_file_value_serializer.h" #include "base/macros.h" @@ -74,9 +74,10 @@ struct SupervisedUserURLFilter::Contents { URLMatcher url_matcher; - base::hash_multimap<HostnameHash, - scoped_refptr<SupervisedUserSiteList>, - HashHostnameHash> hostname_hashes; + std::unordered_multimap<HostnameHash, + scoped_refptr<SupervisedUserSiteList>, + HashHostnameHash> + hostname_hashes; // This only tracks pattern lists. std::map<URLMatcherConditionSet::ID, scoped_refptr<SupervisedUserSiteList>> site_lists_by_matcher_id;
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 4a9910f7..ed15dd9 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
@@ -9,6 +9,7 @@ #include "base/test/scoped_feature_list.h" #include "chrome/browser/sessions/session_service.h" #include "chrome/browser/sessions/session_tab_helper.h" +#include "chrome/browser/signin/gaia_cookie_manager_service_factory.h" #include "chrome/browser/sync/session_sync_service_factory.h" #include "chrome/browser/sync/sessions/sync_sessions_router_tab_helper.h" #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" @@ -22,6 +23,7 @@ #include "chrome/common/url_constants.h" #include "components/history/core/browser/history_types.h" #include "components/sessions/core/session_types.h" +#include "components/signin/core/browser/gaia_cookie_manager_service.h" #include "components/sync/base/time.h" #include "components/sync/protocol/proto_value_conversions.h" #include "components/sync/test/fake_server/sessions_hierarchy.h" @@ -77,8 +79,10 @@ std::unique_ptr<HistogramSamples> samples = histogram_tester.GetHistogramSamplesSinceCreation(name); int sample_count = samples->GetCount(sample); - EXPECT_GE(sample_count, expected_inclusive_lower_bound); - EXPECT_EQ(sample_count, samples->TotalCount()); + EXPECT_GE(sample_count, expected_inclusive_lower_bound) + << " for histogram " << name << " sample " << sample; + EXPECT_EQ(sample_count, samples->TotalCount()) + << " for histogram " << name << " sample " << sample; } class IsHistoryURLSyncedChecker : public SingleClientStatusChangeChecker { @@ -636,11 +640,18 @@ // It is possible that multiple sync cycles occurred during the call to // OpenTab, which would cause multiple identical samples. ExpectUniqueSampleGE(histogram_tester, "Sync.CookieJarMatchOnNavigation", - false, 1); + /*sample=*/false, + /*expected_inclusive_lower_bound=*/1); ExpectUniqueSampleGE(histogram_tester, "Sync.CookieJarEmptyOnMismatch", - true, 1); + /*sample=*/true, + /*expected_inclusive_lower_bound=*/1); } + // Avoid interferences from actual GaiaCookieManagerService trying to fetch + // gaia account information, which would exercise + // ProfileSyncService::OnGaiaAccountsInCookieUpdated(). + GaiaCookieManagerServiceFactory::GetForProfile(GetProfile(0))->CancelAll(); + // Trigger a cookie jar change (user signing in to content area). // Updating the cookie jar has to travel to the sync engine. It is possible // something is already running or scheduled to run on the sync thread. We @@ -670,7 +681,7 @@ // Verify the histograms were recorded properly. ExpectUniqueSampleGE(histogram_tester, "Sync.CookieJarMatchOnNavigation", - true, 1); + /*sample=*/true, /*expected_inclusive_lower_bound=*/1); histogram_tester.ExpectTotalCount("Sync.CookieJarEmptyOnMismatch", 0); } }
diff --git a/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc b/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc index 976589c..46eb00c 100644 --- a/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_autofill_sync_test.cc
@@ -4,11 +4,13 @@ #include "base/macros.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/time/time.h" #include "chrome/browser/sync/test/integration/autofill_helper.h" #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/sync_test.h" +#include "chrome/browser/sync/test/integration/updated_progress_marker_checker.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/personal_data_manager.h" @@ -38,6 +40,17 @@ using autofill_helper::SetCreditCards; using autofill_helper::UpdateProfile; +// Copied from data_type_debug_info_emitter.cc. +enum ModelTypeEntityChange { + LOCAL_DELETION = 0, + LOCAL_CREATION = 1, + LOCAL_UPDATE = 2, + REMOTE_DELETION = 3, + REMOTE_NON_INITIAL_UPDATE = 4, + REMOTE_INITIAL_UPDATE = 5, + MODEL_TYPE_ENTITY_CHANGE_COUNT = 6 +}; + // Class that enables or disables USS based on test parameter. Must be the first // base class of the test fixture. // TODO(jkrcal): When the new implementation fully launches, remove this class, @@ -64,7 +77,11 @@ TwoClientAutofillProfileSyncTest() : SyncTest(TWO_CLIENT) {} ~TwoClientAutofillProfileSyncTest() override {} - bool TestUsesSelfNotifications() override { return false; } + // Tests that check Sync.ModelTypeEntityChange* histograms require + // self-notifications. The reason is that every commit will eventually trigger + // an incoming update on the same client, and without self-notifications we + // have no good way to reliably trigger these updates. + bool TestUsesSelfNotifications() override { return true; } private: DISALLOW_COPY_AND_ASSIGN(TwoClientAutofillProfileSyncTest); @@ -108,6 +125,134 @@ EXPECT_EQ(0U, GetAllAutoFillProfiles(0).size()); } +IN_PROC_BROWSER_TEST_P(TwoClientAutofillProfileSyncTest, SyncHistogramsSanity) { + ASSERT_TRUE(SetupSync()); + + // Client0 adds a profile. + { + base::HistogramTester histograms; + + UpdatedProgressMarkerChecker checker(GetSyncService(0)); + + AddProfile(0, CreateAutofillProfile(PROFILE_MARION)); + EXPECT_TRUE(AutofillProfileChecker(0, 1).Wait()); + EXPECT_EQ(1U, GetAllAutoFillProfiles(0).size()); + + // Wait until the self-notification on Client0 has been processed, so that + // we get consistent histogram counts below. + checker.Wait(); + + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + LOCAL_CREATION, 1); + // We should get 2 remote updates, one per client. + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + REMOTE_NON_INITIAL_UPDATE, 2); + histograms.ExpectTotalCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + 3); + } + + // Client1 adds a profile. + { + base::HistogramTester histograms; + + UpdatedProgressMarkerChecker checker(GetSyncService(1)); + + AddProfile(1, CreateAutofillProfile(PROFILE_HOMER)); + EXPECT_TRUE(AutofillProfileChecker(0, 1).Wait()); + EXPECT_EQ(2U, GetAllAutoFillProfiles(0).size()); + + // Wait until the self-notification on Client1 has been processed, so that + // we get consistent histogram counts below. + checker.Wait(); + + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + LOCAL_CREATION, 1); + // We should get 2 remote updates, one per client. + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + REMOTE_NON_INITIAL_UPDATE, 2); + histograms.ExpectTotalCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + 3); + } + + // TODO(crbug.com/904390): Add a duplicate profile on Client0 (similar to what + // the PersonalDataManagerSanity test does), and make sure that it doesn't + // trigger any entity changes. Currently it's flaky and sometimes does trigger + // a LOCAL_UPDATE change, but neither the AutofillProfileChecker nor the + // UpdatedProgressMarkerChecker actually wait for it, so it messes up *later* + // test expectations. + + // Client1 removes a profile. + { + base::HistogramTester histograms; + + UpdatedProgressMarkerChecker checker(GetSyncService(1)); + + RemoveProfile(1, GetAllAutoFillProfiles(1)[0]->guid()); + EXPECT_TRUE(AutofillProfileChecker(0, 1).Wait()); + EXPECT_EQ(1U, GetAllAutoFillProfiles(0).size()); + + // Wait until the self-notification on Client1 has been processed, so that + // we get consistent histogram counts below. + checker.Wait(); + + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + LOCAL_DELETION, 1); + // We should get one remote deletion update per client. + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + REMOTE_DELETION, 2); + histograms.ExpectTotalCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + 3); + } + + // Client0 updates a profile. + { + base::HistogramTester histograms; + + UpdatedProgressMarkerChecker checker(GetSyncService(0)); + + UpdateProfile(0, GetAllAutoFillProfiles(0)[0]->guid(), + AutofillType(autofill::NAME_FIRST), + base::ASCIIToUTF16("Bart")); + EXPECT_TRUE(AutofillProfileChecker(0, 1).Wait()); + EXPECT_EQ(1U, GetAllAutoFillProfiles(0).size()); + + // Wait until the self-notification on Client0 has been processed, so that + // we get consistent histogram counts below. + checker.Wait(); + + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + LOCAL_UPDATE, 1); + // We should get 2 remote updates, one per client. + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + REMOTE_NON_INITIAL_UPDATE, 2); + histograms.ExpectTotalCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + 3); + } + + // Client1 removes remaining profile. + { + base::HistogramTester histograms; + + UpdatedProgressMarkerChecker checker(GetSyncService(0)); + + RemoveProfile(1, GetAllAutoFillProfiles(1)[0]->guid()); + EXPECT_TRUE(AutofillProfileChecker(0, 1).Wait()); + EXPECT_EQ(0U, GetAllAutoFillProfiles(0).size()); + + // Wait until the self-notification on Client0 has been processed, so that + // we get consistent histogram counts below. + checker.Wait(); + + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + LOCAL_DELETION, 1); + // We should get one remote deletion update per client. + histograms.ExpectBucketCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + REMOTE_DELETION, 2); + histograms.ExpectTotalCount("Sync.ModelTypeEntityChange3.AUTOFILL_PROFILE", + 3); + } +} + IN_PROC_BROWSER_TEST_P(TwoClientAutofillProfileSyncTest, AddDuplicateProfiles) { ASSERT_TRUE(SetupClients());
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 98ce2928..b975bfc8 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -382,7 +382,6 @@ "//chrome/browser/profiling_host", "//chrome/browser/safe_browsing", "//chrome/browser/ssl:proto", - "//chrome/browser/ui/webui/app_management:mojo_bindings", "//chrome/browser/ui/webui/bluetooth_internals", "//chrome/browser/ui/webui/interventions_internals:mojo_bindings", "//chrome/browser/ui/webui/md_downloads:mojo_bindings", @@ -1236,8 +1235,10 @@ "//chrome/browser/profile_resetter:profile_reset_report_proto", "//chrome/browser/resource_coordinator:tab_metrics_event_proto", "//chrome/browser/resource_coordinator/tab_ranker", + "//chrome/browser/ui/webui/app_management:mojo_bindings", "//chrome/common:buildflags", "//chrome/common:search_mojom", + "//chrome/services/app_service/public/cpp:app_update", "//chrome/services/app_service/public/mojom", "//components/feedback/proto", "//components/keep_alive_registry",
diff --git a/chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.cc b/chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.cc index ed1b84f..ddc04a7a 100644 --- a/chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.cc +++ b/chrome/browser/ui/app_list/search/search_result_ranker/app_search_result_ranker.cc
@@ -42,14 +42,23 @@ // Save |proto| to |predictor_filename|. void SaveToDiskOnWorkerThread(const base::FilePath& predictor_filename, const AppLaunchPredictorProto& proto) { - base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); std::string proto_str; - if (!proto.SerializeToString(&proto_str)) + if (!proto.SerializeToString(&proto_str)) { + LOG(ERROR) + << "Unable to serialize AppLaunchPredictorProto, not saving to disk."; return; - - base::ImportantFileWriter::WriteFileAtomically(predictor_filename, proto_str, - "AppSearchResultRanker"); + } + bool write_result; + { + base::ScopedBlockingCall scoped_blocking_call( + base::BlockingType::MAY_BLOCK); + write_result = base::ImportantFileWriter::WriteFileAtomically( + predictor_filename, proto_str, "AppSearchResultRanker"); + } + if (!write_result) { + LOG(ERROR) << "Error writing predictor file " << predictor_filename; + } } // Loads a AppLaunchPredictor from |predictor_filename|.
diff --git a/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc b/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc index eebb87b..9bf805b 100644 --- a/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc +++ b/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc
@@ -407,6 +407,11 @@ void LocalCardMigrationDialogView::DeleteCard(const std::string& guid) { controller_->DeleteCard(guid); ConstructView(); + UpdateLayout(); +} + +// TODO(crbug.com/913571): Figure out a way to avoid two consecutive layouts. +void LocalCardMigrationDialogView::UpdateLayout() { Layout(); // Since the dialog does not have anchor view or arrow, cannot use // SizeToContents() for now. TODO(crbug.com/867194): Try to fix the
diff --git a/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.h b/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.h index 409e818..4b2759b 100644 --- a/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.h +++ b/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.h
@@ -48,6 +48,7 @@ // Called by MigratableCardView when the user clicks the trash can button. // |guid| is the GUID of the credit card to be deleted. void DeleteCard(const std::string& guid); + void UpdateLayout(); private: void ConstructView();
diff --git a/chrome/browser/ui/views/autofill/migratable_card_view.cc b/chrome/browser/ui/views/autofill/migratable_card_view.cc index 6deb429..97e7e4b 100644 --- a/chrome/browser/ui/views/autofill/migratable_card_view.cc +++ b/chrome/browser/ui/views/autofill/migratable_card_view.cc
@@ -6,6 +6,7 @@ #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/ui/autofill/local_card_migration_dialog_state.h" +#include "chrome/browser/ui/autofill/popup_constants.h" #include "chrome/browser/ui/views/autofill/local_card_migration_dialog_view.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" @@ -36,92 +37,38 @@ : migratable_credit_card_(migratable_credit_card), parent_dialog_(parent_dialog) { ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - SetLayoutManager(std::make_unique<views::BoxLayout>( - views::BoxLayout::kHorizontal, gfx::Insets(), - provider->GetDistanceMetric(views::DISTANCE_RELATED_CONTROL_HORIZONTAL))); + views::BoxLayout::kVertical, gfx::Insets(), + provider->GetDistanceMetric(DISTANCE_CONTENT_LIST_VERTICAL_MULTI))); - std::unique_ptr<views::Label> card_description = - std::make_unique<views::Label>( - migratable_credit_card.credit_card().NetworkAndLastFourDigits(), - views::style::CONTEXT_LABEL); + AddChildView(GetMigratableCardDescriptionView(migratable_credit_card, + should_show_checkbox, this) + .release()); - constexpr int kMigrationResultImageSize = 16; - switch (migratable_credit_card.migration_status()) { - case MigratableCreditCard::MigrationStatus::UNKNOWN: { - if (should_show_checkbox) { - checkbox_ = new views::Checkbox(base::string16(), this); - checkbox_->SetChecked(true); - // TODO(crbug/867194): Currently the ink drop animation circle is - // cropped by the border of scroll bar view. Find a way to adjust the - // format. - checkbox_->SetInkDropMode(views::InkDropHostView::InkDropMode::OFF); - checkbox_->SetAssociatedLabel(card_description.get()); - AddChildView(checkbox_); - } - break; - } - case MigratableCreditCard::MigrationStatus::SUCCESS_ON_UPLOAD: { - auto* migration_succeeded_image = new views::ImageView(); - migration_succeeded_image->SetImage(gfx::CreateVectorIcon( - vector_icons::kCheckCircleIcon, kMigrationResultImageSize, - gfx::kGoogleGreen700)); - AddChildView(migration_succeeded_image); - break; - } - case MigratableCreditCard::MigrationStatus::FAILURE_ON_UPLOAD: { - auto* migration_failed_image = new views::ImageView(); - migration_failed_image->SetImage( - gfx::CreateVectorIcon(kBrowserToolsErrorIcon, - kMigrationResultImageSize, gfx::kGoogleRed700)); - AddChildView(migration_failed_image); - break; - } - } - - std::unique_ptr<views::View> card_network_and_last_four_digits = - std::make_unique<views::View>(); - card_network_and_last_four_digits->SetLayoutManager( + checkbox_uncheck_text_container_ = new views::View(); + views::BoxLayout* layout = checkbox_uncheck_text_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( - views::BoxLayout::kHorizontal, gfx::Insets(), - provider->GetDistanceMetric(DISTANCE_RELATED_LABEL_HORIZONTAL_LIST))); + views::BoxLayout::kVertical, + gfx::Insets(provider->GetDistanceMetric( + views::DISTANCE_RELATED_CONTROL_VERTICAL), + provider->GetDistanceMetric( + views::DISTANCE_RELATED_CONTROL_HORIZONTAL)), + provider->GetDistanceMetric( + views::DISTANCE_RELATED_CONTROL_HORIZONTAL))); + layout->set_cross_axis_alignment( + views::BoxLayout::CROSS_AXIS_ALIGNMENT_START); - std::unique_ptr<views::ImageView> card_image = - std::make_unique<views::ImageView>(); - card_image->SetImage( - rb.GetImageNamed(CreditCard::IconResourceId( - migratable_credit_card.credit_card().network())) - .AsImageSkia()); - card_image->SetAccessibleName( - migratable_credit_card.credit_card().NetworkForDisplay()); - card_network_and_last_four_digits->AddChildView(card_image.release()); - card_network_and_last_four_digits->AddChildView(card_description.release()); - AddChildView(card_network_and_last_four_digits.release()); + views::Label* checkbox_uncheck_text_ = new views::Label( + l10n_util::GetStringUTF16( + IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_CHECKBOX_UNCHECK_WARNING), + CONTEXT_BODY_TEXT_SMALL, ChromeTextStyle::STYLE_RED); - std::unique_ptr<views::Label> card_expiration = - std::make_unique<views::Label>( - migratable_credit_card.credit_card() - .AbbreviatedExpirationDateForDisplay(/*with_prefix=*/true), - views::style::CONTEXT_LABEL, ChromeTextStyle::STYLE_SECONDARY); - AddChildView(card_expiration.release()); + checkbox_uncheck_text_container_->AddChildView(checkbox_uncheck_text_); + checkbox_uncheck_text_container_->SetBackground( + views::CreateSolidBackground(gfx::kGoogleGrey050)); + checkbox_uncheck_text_container_->SetVisible(false); - // If card is not successfully uploaded we show the invalid card - // label and the trash can icon. - if (migratable_credit_card.migration_status() == - MigratableCreditCard::MigrationStatus::FAILURE_ON_UPLOAD) { - AddChildView(new views::Label( - l10n_util::GetStringUTF16( - IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_LABEL_INVALID_CARDS), - views::style::CONTEXT_LABEL, ChromeTextStyle::STYLE_RED)); - - delete_card_from_local_button_ = views::CreateVectorImageButton(this); - views::SetImageFromVectorIcon(delete_card_from_local_button_, - kTrashCanIcon); - delete_card_from_local_button_->SetTooltipText(l10n_util::GetStringUTF16( - IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_TRASH_CAN_BUTTON_TOOLTIP)); - AddChildView(delete_card_from_local_button_); - } + AddChildView(checkbox_uncheck_text_container_); } MigratableCardView::~MigratableCardView() = default; @@ -134,6 +81,107 @@ return migratable_credit_card_.credit_card().guid(); } +std::unique_ptr<views::View> +MigratableCardView::GetMigratableCardDescriptionView( + const MigratableCreditCard& migratable_credit_card, + bool should_show_checkbox, + ButtonListener* listener) { + auto migratable_card_description_view = std::make_unique<views::View>(); + ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); + + migratable_card_description_view->SetLayoutManager( + std::make_unique<views::BoxLayout>( + views::BoxLayout::kHorizontal, gfx::Insets(), + provider->GetDistanceMetric( + views::DISTANCE_RELATED_CONTROL_HORIZONTAL))); + + std::unique_ptr<views::Label> card_description = + std::make_unique<views::Label>( + migratable_credit_card.credit_card().NetworkAndLastFourDigits(), + views::style::CONTEXT_LABEL); + + constexpr int kMigrationResultImageSize = 16; + switch (migratable_credit_card.migration_status()) { + case MigratableCreditCard::MigrationStatus::UNKNOWN: { + if (should_show_checkbox) { + checkbox_ = new views::Checkbox(base::string16(), listener); + checkbox_->SetChecked(true); + // TODO(crbug/867194): Currently the ink drop animation circle is + // cropped by the border of scroll bar view. Find a way to adjust the + // format. + checkbox_->SetInkDropMode(views::InkDropHostView::InkDropMode::OFF); + checkbox_->SetAssociatedLabel(card_description.get()); + migratable_card_description_view->AddChildView(checkbox_); + } + break; + } + case MigratableCreditCard::MigrationStatus::SUCCESS_ON_UPLOAD: { + auto* migration_succeeded_image = new views::ImageView(); + migration_succeeded_image->SetImage(gfx::CreateVectorIcon( + vector_icons::kCheckCircleIcon, kMigrationResultImageSize, + gfx::kGoogleGreen700)); + migratable_card_description_view->AddChildView(migration_succeeded_image); + break; + } + case MigratableCreditCard::MigrationStatus::FAILURE_ON_UPLOAD: { + auto* migration_failed_image = new views::ImageView(); + migration_failed_image->SetImage( + gfx::CreateVectorIcon(kBrowserToolsErrorIcon, + kMigrationResultImageSize, gfx::kGoogleRed700)); + migratable_card_description_view->AddChildView(migration_failed_image); + break; + } + } + + std::unique_ptr<views::View> card_network_and_last_four_digits = + std::make_unique<views::View>(); + card_network_and_last_four_digits->SetLayoutManager( + std::make_unique<views::BoxLayout>( + views::BoxLayout::kHorizontal, gfx::Insets(), + provider->GetDistanceMetric(DISTANCE_RELATED_LABEL_HORIZONTAL_LIST))); + + ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); + std::unique_ptr<views::ImageView> card_image = + std::make_unique<views::ImageView>(); + card_image->SetImage( + rb.GetImageNamed(CreditCard::IconResourceId( + migratable_credit_card.credit_card().network())) + .AsImageSkia()); + card_image->SetAccessibleName( + migratable_credit_card.credit_card().NetworkForDisplay()); + card_network_and_last_four_digits->AddChildView(card_image.release()); + card_network_and_last_four_digits->AddChildView(card_description.release()); + migratable_card_description_view->AddChildView( + card_network_and_last_four_digits.release()); + + std::unique_ptr<views::Label> card_expiration = + std::make_unique<views::Label>( + migratable_credit_card.credit_card() + .AbbreviatedExpirationDateForDisplay(/*with_prefix=*/true), + views::style::CONTEXT_LABEL, ChromeTextStyle::STYLE_SECONDARY); + migratable_card_description_view->AddChildView(card_expiration.release()); + + // If card is not successfully uploaded we show the invalid card + // label and the trash can icon. + if (migratable_credit_card.migration_status() == + MigratableCreditCard::MigrationStatus::FAILURE_ON_UPLOAD) { + migratable_card_description_view->AddChildView(new views::Label( + l10n_util::GetStringUTF16( + IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_LABEL_INVALID_CARDS), + views::style::CONTEXT_LABEL, ChromeTextStyle::STYLE_RED)); + + delete_card_from_local_button_ = views::CreateVectorImageButton(listener); + views::SetImageFromVectorIcon(delete_card_from_local_button_, + kTrashCanIcon); + delete_card_from_local_button_->SetTooltipText(l10n_util::GetStringUTF16( + IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_TRASH_CAN_BUTTON_TOOLTIP)); + migratable_card_description_view->AddChildView( + delete_card_from_local_button_); + } + + return migratable_card_description_view; +} + const char* MigratableCardView::GetClassName() const { return kViewClassName; } @@ -144,6 +192,10 @@ // If the button clicked is a checkbox. Enable/disable the save // button if needed. parent_dialog_->DialogModelChanged(); + // The warning text will be visible only when user unchecks the checkbox. + checkbox_uncheck_text_container_->SetVisible(!checkbox_->checked()); + InvalidateLayout(); + parent_dialog_->UpdateLayout(); } else { // Otherwise it is the trash can button clicked. Delete the corresponding // card from local storage.
diff --git a/chrome/browser/ui/views/autofill/migratable_card_view.h b/chrome/browser/ui/views/autofill/migratable_card_view.h index 39800f6..a3fb3f45 100644 --- a/chrome/browser/ui/views/autofill/migratable_card_view.h +++ b/chrome/browser/ui/views/autofill/migratable_card_view.h
@@ -37,6 +37,11 @@ bool IsSelected(); std::string GetGuid(); + std::unique_ptr<views::View> GetMigratableCardDescriptionView( + const MigratableCreditCard& migratable_credit_card, + bool should_show_checkbox, + ButtonListener* listener); + // views::View const char* GetClassName() const override; @@ -50,6 +55,8 @@ // card migration dialog contains only one card. views::Checkbox* checkbox_ = nullptr; + views::View* checkbox_uncheck_text_container_ = nullptr; + views::ImageButton* delete_card_from_local_button_ = nullptr; LocalCardMigrationDialogView* parent_dialog_ = nullptr;
diff --git a/chrome/browser/ui/views/overlay/OWNERS b/chrome/browser/ui/views/overlay/OWNERS index 2d095db3..b234e09 100644 --- a/chrome/browser/ui/views/overlay/OWNERS +++ b/chrome/browser/ui/views/overlay/OWNERS
@@ -1,4 +1,3 @@ -apacible@chromium.org -mlamouri@chromium.org +file://third_party/blink/renderer/modules/picture_in_picture/OWNERS -# COMPONENT: Internals>Media>UI \ No newline at end of file +# COMPONENT: Internals>Media>UI
diff --git a/chrome/browser/ui/webui/DEPS b/chrome/browser/ui/webui/DEPS index 10bf6c8b..fcf6dcdf 100644 --- a/chrome/browser/ui/webui/DEPS +++ b/chrome/browser/ui/webui/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+chrome/services/app_service/public", "+device/bluetooth", "+extensions/strings/grit/extensions_strings.h",
diff --git a/chrome/browser/ui/webui/app_management/BUILD.gn b/chrome/browser/ui/webui/app_management/BUILD.gn index 1f743d8..4395a4ca 100644 --- a/chrome/browser/ui/webui/app_management/BUILD.gn +++ b/chrome/browser/ui/webui/app_management/BUILD.gn
@@ -8,4 +8,8 @@ sources = [ "app_management.mojom", ] + + public_deps = [ + "//chrome/services/app_service/public/mojom", + ] }
diff --git a/chrome/browser/ui/webui/app_management/app_management.mojom b/chrome/browser/ui/webui/app_management/app_management.mojom index 0525d25..6b4870a8b 100644 --- a/chrome/browser/ui/webui/app_management/app_management.mojom +++ b/chrome/browser/ui/webui/app_management/app_management.mojom
@@ -4,6 +4,22 @@ module app_management.mojom; +import "chrome/services/app_service/public/mojom/types.mojom"; + +struct App { + // The id of this app. + string id; + + // The type of this app. + apps.mojom.AppType type; + + // The fields below may be omitted because this struct is also used to signal + // updates. + + // The name of the app to display in the UI. + string? title; +}; + interface PageHandlerFactory { CreatePageHandler(Page page, PageHandler& handler); }; @@ -15,5 +31,7 @@ // Frontend interface. interface Page { - OnAppsAdded(array<string> ids); + OnAppsAdded(array<App> apps); + OnAppChanged(App app); + OnAppRemoved(string app_id); };
diff --git a/chrome/browser/ui/webui/app_management/app_management_page_handler.cc b/chrome/browser/ui/webui/app_management/app_management_page_handler.cc index 203ad3218..2e23865 100644 --- a/chrome/browser/ui/webui/app_management/app_management_page_handler.cc +++ b/chrome/browser/ui/webui/app_management/app_management_page_handler.cc
@@ -7,15 +7,44 @@ #include <utility> #include <vector> +#include "chrome/browser/apps/app_service/app_service_proxy.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/services/app_service/public/cpp/app_registry_cache.h" +#include "chrome/services/app_service/public/mojom/types.mojom.h" + AppManagementPageHandler::AppManagementPageHandler( app_management::mojom::PageHandlerRequest request, app_management::mojom::PagePtr page, content::WebUI* web_ui) - : binding_(this, std::move(request)), page_(std::move(page)) {} + : binding_(this, std::move(request)), + page_(std::move(page)), + profile_(Profile::FromWebUI(web_ui)) {} AppManagementPageHandler::~AppManagementPageHandler() {} void AppManagementPageHandler::GetApps() { - std::vector<std::string> ids = {"test_id"}; - page_->OnAppsAdded(ids); + apps::AppServiceProxy* proxy = apps::AppServiceProxy::Get(profile_); + + // TODO(crbug.com/826982): revisit pending decision on AppServiceProxy in + // incognito + if (!proxy) + return; + + std::vector<app_management::mojom::AppPtr> apps; + proxy->Cache().ForEachApp([&apps](const apps::AppUpdate& update) { + apps.push_back(app_management::mojom::App::New( + update.AppId(), update.AppType(), update.Name())); + }); + page_->OnAppsAdded(std::move(apps)); +} + +void AppManagementPageHandler::OnAppUpdate(const apps::AppUpdate& update) { + if (update.ReadinessChanged() && + update.Readiness() == apps::mojom::Readiness::kUninstalledByUser) { + page_->OnAppRemoved(update.AppId()); + return; + } + + page_->OnAppChanged(app_management::mojom::App::New( + update.AppId(), update.AppType(), update.Name())); }
diff --git a/chrome/browser/ui/webui/app_management/app_management_page_handler.h b/chrome/browser/ui/webui/app_management/app_management_page_handler.h index 76c45b6..0b5f710a 100644 --- a/chrome/browser/ui/webui/app_management/app_management_page_handler.h +++ b/chrome/browser/ui/webui/app_management/app_management_page_handler.h
@@ -7,13 +7,17 @@ #include "base/macros.h" #include "chrome/browser/ui/webui/app_management/app_management.mojom.h" +#include "chrome/services/app_service/public/cpp/app_registry_cache.h" #include "mojo/public/cpp/bindings/binding.h" namespace content { class WebUI; } -class AppManagementPageHandler : public app_management::mojom::PageHandler { +class Profile; + +class AppManagementPageHandler : public app_management::mojom::PageHandler, + public apps::AppRegistryCache::Observer { public: AppManagementPageHandler(app_management::mojom::PageHandlerRequest request, app_management::mojom::PagePtr page, @@ -24,10 +28,15 @@ void GetApps() override; private: + // apps::AppRegistryCache::Observer overrides: + void OnAppUpdate(const apps::AppUpdate& update) override; + mojo::Binding<app_management::mojom::PageHandler> binding_; app_management::mojom::PagePtr page_; + Profile* profile_; + DISALLOW_COPY_AND_ASSIGN(AppManagementPageHandler); };
diff --git a/chrome/browser/ui/webui/app_management/app_management_ui.cc b/chrome/browser/ui/webui/app_management/app_management_ui.cc index 7a278a2a..0bbdab0 100644 --- a/chrome/browser/ui/webui/app_management/app_management_ui.cc +++ b/chrome/browser/ui/webui/app_management/app_management_ui.cc
@@ -28,18 +28,31 @@ content::WebUIDataSource::Create(chrome::kChromeUIAppLauncherPageHost); source->AddLocalizedString("appListTitle", IDS_APP_MANAGEMENT_APP_LIST_TITLE); + source->AddLocalizedString("lessApps", IDS_APP_MANAGEMENT_LESS_APPS); source->AddLocalizedString("moreApps", IDS_APP_MANAGEMENT_MORE_APPS); source->AddLocalizedString("searchPrompt", IDS_APP_MANAGEMENT_SEARCH_PROMPT); source->AddLocalizedString("title", IDS_APP_MANAGEMENT_TITLE); source->AddResourcePath("app_management.mojom-lite.js", IDR_APP_MANAGEMENT_MOJO_LITE_JS); + source->AddResourcePath("types.mojom-lite.js", + IDR_APP_MANAGEMENT_TYPES_MOJO_LITE_JS); + source->AddResourcePath("big_buffer.mojom-lite.js", + IDR_APP_MANAGEMENT_BIG_BUFFER_MOJO_LITE_JS); + source->AddResourcePath("bitmap.mojom-lite.js", + IDR_APP_MANAGEMENT_BITMAP_MOJO_LITE_JS); + source->AddResourcePath("image.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_MOJO_LITE_JS); + source->AddResourcePath("image_info.mojom-lite.js", + IDR_APP_MANAGEMENT_IMAGE_INFO_MOJO_LITE_JS); source->AddResourcePath("app.html", IDR_APP_MANAGEMENT_APP_HTML); source->AddResourcePath("app.js", IDR_APP_MANAGEMENT_APP_JS); source->AddResourcePath("browser_proxy.html", IDR_APP_MANAGEMENT_BROWSER_PROXY_HTML); source->AddResourcePath("browser_proxy.js", IDR_APP_MANAGEMENT_BROWSER_PROXY_JS); + source->AddResourcePath("constants.html", IDR_APP_MANAGEMENT_CONSTANTS_HTML); + source->AddResourcePath("constants.js", IDR_APP_MANAGEMENT_CONSTANTS_JS); source->AddResourcePath("fake_page_handler.js", IDR_APP_MANAGEMENT_FAKE_PAGE_HANDLER_JS); source->AddResourcePath("main_view.html", IDR_APP_MANAGEMENT_MAIN_VIEW_HTML);
diff --git a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc index 6f05f1940..f0960599 100644 --- a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc +++ b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
@@ -63,14 +63,20 @@ content::NavigationHandle* navigation_handle) override { navigation_result_ = navigation_handle->IsErrorPage() ? ERROR_PAGE : SUCCESS; + net_error_ = navigation_handle->GetNetErrorCode(); } NavigationResult navigation_result() const { return navigation_result_; } + net::Error net_error() const { return net_error_; } - void Reset() { navigation_result_ = NOT_FINISHED; } + void Reset() { + navigation_result_ = NOT_FINISHED; + net_error_ = net::OK; + } private: NavigationResult navigation_result_; + net::Error net_error_ = net::OK; DISALLOW_COPY_AND_ASSIGN(NavigationObserver); }; @@ -96,12 +102,16 @@ ui_test_utils::NavigateToURL( browser(), GURL("chrome://theme/IDR_SETTINGS_FAVICON")); EXPECT_EQ(NavigationObserver::SUCCESS, observer.navigation_result()); + EXPECT_EQ(net::OK, observer.net_error()); // Unknown resource observer.Reset(); ui_test_utils::NavigateToURL( browser(), GURL("chrome://theme/IDR_ASDFGHJKL")); EXPECT_EQ(NavigationObserver::ERROR_PAGE, observer.navigation_result()); + // The presence of net error means that navigation did not commit to the + // original url. + EXPECT_NE(net::OK, observer.net_error()); } // Makes sure browser does not crash when the resource scale is very large. @@ -112,10 +122,14 @@ ui_test_utils::NavigateToURL( browser(), GURL("chrome://theme/IDR_SETTINGS_FAVICON@2x")); EXPECT_EQ(NavigationObserver::SUCCESS, observer.navigation_result()); + EXPECT_EQ(net::OK, observer.net_error()); // Unreasonably large scale observer.Reset(); ui_test_utils::NavigateToURL( browser(), GURL("chrome://theme/IDR_SETTINGS_FAVICON@99999x")); EXPECT_EQ(NavigationObserver::ERROR_PAGE, observer.navigation_result()); + // The presence of net error means that navigation did not commit to the + // original url. + EXPECT_NE(net::OK, observer.net_error()); }
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 5d978a4..4bdefb0 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -22,7 +22,6 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search/suggestions/suggestions_ui.h" #include "chrome/browser/ui/webui/about_ui.h" -#include "chrome/browser/ui/webui/app_management/app_management_ui.h" #include "chrome/browser/ui/webui/bluetooth_internals/bluetooth_internals_ui.h" #include "chrome/browser/ui/webui/components_ui.h" #include "chrome/browser/ui/webui/constrained_web_dialog_ui.h" @@ -108,6 +107,7 @@ #if !defined(OS_ANDROID) #include "chrome/browser/media/router/media_router_feature.h" +#include "chrome/browser/ui/webui/app_management/app_management_ui.h" #include "chrome/browser/ui/webui/management_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_internals_ui.h" #include "chrome/browser/ui/webui/media_router/media_router_ui.h"
diff --git a/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc b/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc index d838e7a..b91fbb3 100644 --- a/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc +++ b/chrome/browser/ui/webui/md_downloads/md_downloads_ui.cc
@@ -127,6 +127,9 @@ source->AddResourcePath("constants.js", IDR_MD_DOWNLOADS_CONSTANTS_JS); source->AddResourcePath("downloads.js", IDR_MD_DOWNLOADS_DOWNLOADS_JS); source->AddResourcePath("i18n_setup.html", IDR_MD_DOWNLOADS_I18N_SETUP_HTML); + source->AddResourcePath("icon_loader.html", + IDR_MD_DOWNLOADS_ICON_LOADER_HTML); + source->AddResourcePath("icon_loader.js", IDR_MD_DOWNLOADS_ICON_LOADER_JS); source->AddResourcePath("icons.html", IDR_MD_DOWNLOADS_ICONS_HTML); source->AddResourcePath("item.html", IDR_MD_DOWNLOADS_ITEM_HTML); source->AddResourcePath("item.js", IDR_MD_DOWNLOADS_ITEM_JS);
diff --git a/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc b/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc index 0240b9d..3427207 100644 --- a/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc +++ b/chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc
@@ -11,11 +11,17 @@ #include "base/memory/ref_counted.h" #include "base/task/post_task.h" #include "base/threading/scoped_blocking_call.h" +#include "build/build_config.h" #include "chrome/browser/ui/webui/print_preview/print_preview_utils.h" #include "components/printing/common/printer_capabilities.h" #include "content/public/browser/browser_thread.h" #include "printing/backend/print_backend.h" +#if defined(OS_MACOSX) +#include "components/printing/browser/features.h" +#include "components/printing/common/printer_capabilities_mac.h" +#endif + namespace { printing::PrinterList EnumeratePrintersAsync() { @@ -29,8 +35,15 @@ } std::unique_ptr<base::DictionaryValue> FetchCapabilitiesAsync( - const std::string& device_name, - const printing::PrinterSemanticCapsAndDefaults::Papers& additional_papers) { + const std::string& device_name) { + printing::PrinterSemanticCapsAndDefaults::Papers additional_papers; +#if defined(OS_MACOSX) + if (base::FeatureList::IsEnabled( + printing::features::kEnableCustomMacPaperSizes)) { + additional_papers = printing::GetMacCustomPaperSizes(); + } +#endif + base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); scoped_refptr<printing::PrintBackend> print_backend( printing::PrintBackend::CreateInstance(nullptr)); @@ -97,13 +110,9 @@ GetCapabilityCallback cb) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // TODO(thestig): Fetch custom paper sizes. - printing::PrinterSemanticCapsAndDefaults::Papers additional_papers; - base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, - base::BindOnce(&FetchCapabilitiesAsync, device_name, additional_papers), - std::move(cb)); + base::BindOnce(&FetchCapabilitiesAsync, device_name), std::move(cb)); } void LocalPrinterHandlerDefault::StartPrint(
diff --git a/chrome/common/extensions/api/autotest_private.idl b/chrome/common/extensions/api/autotest_private.idl index d5bfd96b..5b9bde1 100644 --- a/chrome/common/extensions/api/autotest_private.idl +++ b/chrome/common/extensions/api/autotest_private.idl
@@ -106,6 +106,37 @@ callback IsArcProvisionedCallback = void (boolean arcProvisioned); + dictionary ArcAppDict { + DOMString name; + DOMString packageName; + DOMString activity; + DOMString intentUri; + DOMString iconResourceId; + double lastLaunchTime; + double installTime; + boolean sticky; + boolean notificationsEnabled; + boolean ready; + boolean suspended; + boolean showInLauncher; + boolean shortcut; + boolean launchable; + }; + callback GetArcAppCallback = void (ArcAppDict package); + + dictionary ArcPackageDict { + DOMString packageName; + long packageVersion; + DOMString lastBackupAndroidId; + double lastBackupTime; + boolean shouldSync; + boolean system; + boolean vpnProvider; + }; + callback GetArcPackageCallback = void (ArcPackageDict package); + + callback LaunchArcAppCallback = void (boolean appLaunched); + callback TakeScreenshotCallback = void (DOMString base64Png); callback VoidCallback = void (); @@ -180,9 +211,24 @@ // Returns true if ARC is provisioned. static void isArcProvisioned(IsArcProvisionedCallback callback); + // Gets information about the requested ARC app. + static void getArcApp(DOMString appId, GetArcAppCallback callback); + + // Gets information about requested ARC package. + static void getArcPackage(DOMString packageName, + GetArcPackageCallback callback); + + // Launches ARC app with optional intent. Returns true if ARC is active, + // app exists and launch request is passed to Android. + static void launchArcApp(DOMString appId, DOMString intent, + LaunchArcAppCallback callback); + // Launches an application from the launcher with the given appId. static void launchApp(DOMString appId, VoidCallback callback); + // Closes an application the given appId in case it was running. + static void closeApp(DOMString appId, VoidCallback callback); + // Update printer. Printer with empty ID is considered new. static void updatePrinter(Printer printer);
diff --git a/chrome/common/media_router/providers/cast/cast_media_source.cc b/chrome/common/media_router/providers/cast/cast_media_source.cc index 3a978ec3..edc701b 100644 --- a/chrome/common/media_router/providers/cast/cast_media_source.cc +++ b/chrome/common/media_router/providers/cast/cast_media_source.cc
@@ -36,7 +36,9 @@ std::string DecodeURLComponent(const std::string& encoded) { url::RawCanonOutputT<base::char16> unescaped; std::string output; - url::DecodeURLEscapeSequences(encoded.data(), encoded.size(), &unescaped); + url::DecodeURLEscapeSequences(encoded.data(), encoded.size(), + url::DecodeURLMode::kUTF8OrIsomorphic, + &unescaped); if (base::UTF16ToUTF8(unescaped.data(), unescaped.length(), &output)) return output;
diff --git a/chrome/renderer/resources/extensions/automation/automation_node.js b/chrome/renderer/resources/extensions/automation/automation_node.js index 558cf49..9349b72 100644 --- a/chrome/renderer/resources/extensions/automation/automation_node.js +++ b/chrome/renderer/resources/extensions/automation/automation_node.js
@@ -438,6 +438,11 @@ return; if (!GetBoolAttribute(this.treeID, this.id, 'supportsTextLocation')) { + // GetBoundsForRange should only be called on INLINE_TEXT_BOX. + if (this.role != RoleType.INLINE_TEXT_BOX) { + callback(null); + return; + } try { callback( GetBoundsForRange(this.treeID, this.id, startIndex, endIndex));
diff --git a/chrome/test/chromedriver/server/http_handler.cc b/chrome/test/chromedriver/server/http_handler.cc index 99850da..5d8f8d66 100644 --- a/chrome/test/chromedriver/server/http_handler.cc +++ b/chrome/test/chromedriver/server/http_handler.cc
@@ -1128,7 +1128,8 @@ CHECK(name.length()); url::RawCanonOutputT<base::char16> output; url::DecodeURLEscapeSequences( - path_parts[i].data(), path_parts[i].length(), &output); + path_parts[i].data(), path_parts[i].length(), + url::DecodeURLMode::kUTF8OrIsomorphic, &output); std::string decoded = base::UTF16ToASCII( base::string16(output.data(), output.length())); // Due to crbug.com/533361, the url decoding libraries decodes all of the
diff --git a/chrome/test/data/extensions/api_test/automation/sites/bounds_for_range.html b/chrome/test/data/extensions/api_test/automation/sites/bounds_for_range.html index 11cd66a..925b768 100644 --- a/chrome/test/data/extensions/api_test/automation/sites/bounds_for_range.html +++ b/chrome/test/data/extensions/api_test/automation/sites/bounds_for_range.html
@@ -26,7 +26,7 @@ </ul> <div style="width: 50px; overflow: hidden"> - <div style="width: 200px">This text overflows</span> + <span style="width: 200px">This text overflows</span> </div> <div style="width: 0; height: 0; overflow: hidden">
diff --git a/chrome/test/data/extensions/api_test/automation/tests/tabs/bounds_for_range.js b/chrome/test/data/extensions/api_test/automation/tests/tabs/bounds_for_range.js index a029e1a6..19634d7 100644 --- a/chrome/test/data/extensions/api_test/automation/tests/tabs/bounds_for_range.js +++ b/chrome/test/data/extensions/api_test/automation/tests/tabs/bounds_for_range.js
@@ -93,14 +93,16 @@ }, function boundsForRangeClips() { - let clipped = rootNode.find({attributes: {name: "This text overflows"}}); + let clipped = rootNode.find({attributes: { + name: "This text overflows"}}); clipped.boundsForRange(0, clipped.name.length, (clippedBounds) => { assertTrue( clipped.parent.location.width < clipped.unclippedLocation.width); assertEq(clipped.parent.location.width, clippedBounds.width); }); - let hidden = rootNode.find({attributes: {name: "This text is hidden"}}); + let hidden = rootNode.find({attributes: { + name: "This text is hidden"}); hidden.boundsForRange(0, hidden.name.length, (hiddenBounds) => { assertTrue(hidden.parent.location.width < hidden.unclippedLocation.width); assertTrue(
diff --git a/chrome/test/data/extensions/api_test/autotest_private/test.js b/chrome/test/data/extensions/api_test/autotest_private/test.js index bd44c20e..272eaee 100644 --- a/chrome/test/data/extensions/api_test/autotest_private/test.js +++ b/chrome/test/data/extensions/api_test/autotest_private/test.js
@@ -169,13 +169,18 @@ }); }); }, - // This launches Chrome. - function launchApp() { + // This launches and closes Chrome. + function launchCloseApp() { chrome.autotestPrivate.launchApp('mgndgikekgjfcpckkfioiadnlibdjbkf', - function() { - chrome.test.assertNoLastError(); - chrome.test.succeed(); - }); + function() { + chrome.test.assertNoLastError(); + chrome.autotestPrivate.isAppShown('mgndgikekgjfcpckkfioiadnlibdjbkf', + function(appShown) { + chrome.test.assertNoLastError(); + chrome.test.assertTrue(appShown); + chrome.test.succeed(); + }); + }); }, function setCrostiniEnabled() { chrome.autotestPrivate.setCrostiniEnabled(true, chrome.test.callbackFail( @@ -221,9 +226,31 @@ chrome.test.succeed(); }); }, + // No any ARC app by default + function getArcApp() { + chrome.autotestPrivate.getArcApp( + 'bifanmfigailifmdhaomnmchcgflbbdn', + chrome.test.callbackFail('App is not available')); + }, + // No any ARC package by default + function getArcPackage() { + chrome.autotestPrivate.getArcPackage( + 'fake.package', + chrome.test.callbackFail('Package is not available')); + }, + // Launch fails, no any ARC app by default + function launchArcApp() { + chrome.autotestPrivate.launchArcApp( + 'bifanmfigailifmdhaomnmchcgflbbdn', + '#Intent;', + function(appLaunched) { + chrome.test.assertFalse(appLaunched); + chrome.test.succeed(); + }); + }, ]; -var arcProvisionedTests = [ +var arcEnabledTests = [ // This test verifies that isArcProvisioned returns True in case ARC // provisiong is done. function isArcProvisioned() { @@ -234,11 +261,90 @@ chrome.test.succeed(); }); }, + // ARC app is available + function getArcApp() { + // bifanmfigailifmdhaomnmchcgflbbdn id is taken from + // ArcAppListPrefs::GetAppId( + // "fake.package", "fake.package.activity"); + chrome.autotestPrivate.getArcApp('bifanmfigailifmdhaomnmchcgflbbdn', + chrome.test.callbackPass(function(appInfo) { + chrome.test.assertNoLastError(); + // See AutotestPrivateArcEnabled for constants. + chrome.test.assertEq('Fake App', appInfo.name); + chrome.test.assertEq('fake.package', appInfo.packageName); + chrome.test.assertEq('fake.package.activity', appInfo.activity); + chrome.test.assertEq('', appInfo.intentUri); + chrome.test.assertEq('', appInfo.iconResourceId); + chrome.test.assertEq(0, appInfo.lastLaunchTime); + // Install time is set right before this call. Assume we are 5 + // min maximum after setting the install time. + chrome.test.assertTrue(Date.now() >= appInfo.installTime); + chrome.test.assertTrue( + Date.now() <= appInfo.installTime + 5 * 60 * 1000.0); + chrome.test.assertEq(false, appInfo.sticky); + chrome.test.assertEq(false, appInfo.notificationsEnabled); + chrome.test.assertEq(true, appInfo.ready); + chrome.test.assertEq(false, appInfo.suspended); + chrome.test.assertEq(true, appInfo.showInLauncher); + chrome.test.assertEq(false, appInfo.shortcut); + chrome.test.assertEq(true, appInfo.launchable); + + chrome.test.succeed(); + })); + }, + // ARC is available but app does not exist + function getArcNonExistingApp() { + chrome.autotestPrivate.getArcApp( + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + chrome.test.callbackFail('App is not available')); + }, + // ARC package is available + function getArcPackage() { + chrome.autotestPrivate.getArcPackage('fake.package', + chrome.test.callbackPass(function(packageInfo) { + chrome.test.assertNoLastError(); + // See AutotestPrivateArcEnabled for constants. + chrome.test.assertEq('fake.package', packageInfo.packageName); + chrome.test.assertEq(10, packageInfo.packageVersion); + chrome.test.assertEq('100', packageInfo.lastBackupAndroidId); + // Backup time is set right before this call. Assume we are 5 + // min maximum after setting the backup time. + chrome.test.assertTrue(Date.now() >= packageInfo.lastBackupTime); + chrome.test.assertTrue( + Date.now() <= packageInfo.lastBackupTime + 5 * 60 * 1000.0); + chrome.test.assertEq(true, packageInfo.shouldSync); + chrome.test.assertEq(false, packageInfo.system); + chrome.test.assertEq(false, packageInfo.vpnProvider); + chrome.test.succeed(); + })); + }, + // Launch existing ARC app + function launchArcApp() { + chrome.autotestPrivate.launchArcApp( + 'bifanmfigailifmdhaomnmchcgflbbdn', + '#Intent;', + function(appLaunched) { + chrome.test.assertNoLastError(); + chrome.test.assertTrue(appLaunched); + chrome.test.succeed(); + }); + }, + // Launch non-existing ARC app + function launchNonExistingApp() { + chrome.autotestPrivate.launchArcApp( + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + '#Intent;', + function(appLaunched) { + chrome.test.assertNoLastError(); + chrome.test.assertFalse(appLaunched); + chrome.test.succeed(); + }); + }, ]; var test_suites = { 'default': defaultTests, - 'arcProvisioned': arcProvisionedTests + 'arcEnabled': arcEnabledTests }; chrome.test.getConfig(function(config) {
diff --git a/chrome/test/data/extensions/api_test/native_bindings/extension/background.js b/chrome/test/data/extensions/api_test/native_bindings/extension/background.js index d8f7398..32a5e97 100644 --- a/chrome/test/data/extensions/api_test/native_bindings/extension/background.js +++ b/chrome/test/data/extensions/api_test/native_bindings/extension/background.js
@@ -156,6 +156,7 @@ chrome.test.assertTrue(!!chrome.storage.local, 'no local'); chrome.test.assertTrue(!!chrome.storage.local.set, 'no set'); chrome.test.assertTrue(!!chrome.storage.local.get, 'no get'); + chrome.test.assertTrue(!!chrome.storage.local.onChanged, 'no onChanged'); // Check some properties. chrome.test.assertTrue(!!chrome.storage.local.QUOTA_BYTES, 'local quota bytes');
diff --git a/chrome/test/data/extensions/api_test/settings/storage_area/background.js b/chrome/test/data/extensions/api_test/settings/storage_area/background.js new file mode 100644 index 0000000..0e8a479 --- /dev/null +++ b/chrome/test/data/extensions/api_test/settings/storage_area/background.js
@@ -0,0 +1,33 @@ +// 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. + +var storageAreaOnChanged = function() { + // Checks the onChanged callback is called from both StorageArea and + // chrome.storage. + var localStorageArea = chrome.storage.local; + chrome.test.listenOnce(localStorageArea.onChanged, function(changes) { + chrome.test.assertEq({key:{newValue:'value'}}, changes); + }); + + chrome.test.listenOnce(chrome.storage.onChanged, + function(changes, namespace) { + chrome.test.assertEq({key:{newValue:'value'}}, changes); + chrome.test.assertEq('local', namespace); + } + ); + + chrome.storage.managed.onChanged.addListener(function(changes, namespace) { + chrome.test.notifyFail('managed.onChanged should not be called when local ' + + 'storage update'); + }); + + chrome.storage.sync.onChanged.addListener(function(changes, namespace) { + chrome.test.notifyFail('sync.onChanged should not be called when local ' + + 'storage update'); + }); + + localStorageArea.set({key: 'value'}); +}; + +chrome.test.runTests([storageAreaOnChanged]);
diff --git a/chrome/test/data/extensions/api_test/settings/storage_area/manifest.json b/chrome/test/data/extensions/api_test/settings/storage_area/manifest.json new file mode 100644 index 0000000..6895ca1 --- /dev/null +++ b/chrome/test/data/extensions/api_test/settings/storage_area/manifest.json
@@ -0,0 +1,10 @@ +{ + "name": "StorageArea.OnChanged", + "version": "0.1", + "manifest_version": 2, + "description": "Tests that the StorageArea.onChanged event works.", + "permissions": ["storage"], + "background": { + "scripts": ["background.js"] + } +}
diff --git a/chrome/test/data/webui/cr_components/managed_footnote_test.js b/chrome/test/data/webui/cr_components/managed_footnote_test.js index 90c5438f..6d5fb32 100644 --- a/chrome/test/data/webui/cr_components/managed_footnote_test.js +++ b/chrome/test/data/webui/cr_components/managed_footnote_test.js
@@ -14,6 +14,10 @@ PolymerTest.clearBody(); }); + teardown(function() { + PolymerTest.clearBody(); + }); + /** * Resets loadTimeData to the parameters, inserts a <managed-footnote> element * in the DOM, and returns it.
diff --git a/chrome/test/data/webui/icon_test.html b/chrome/test/data/webui/icon_test.html index 9024032..bd5d15ef 100644 --- a/chrome/test/data/webui/icon_test.html +++ b/chrome/test/data/webui/icon_test.html
@@ -33,6 +33,12 @@ assertEquals(expected, cr.icon.getFavicon(url)); } +function testGetFileIconUrl() { + assertEquals(cr.icon.getFileIconUrl('file path'), + 'chrome://fileicon/file%20path?scale=' + + window.devicePixelRatio + 'x'); +} + </script> </body> </html>
diff --git a/chrome/test/data/webui/md_downloads/downloads_browsertest.js b/chrome/test/data/webui/md_downloads/downloads_browsertest.js index c0406d0..79a2ea2 100644 --- a/chrome/test/data/webui/md_downloads/downloads_browsertest.js +++ b/chrome/test/data/webui/md_downloads/downloads_browsertest.js
@@ -47,6 +47,9 @@ /** @override */ extraLibraries: DownloadsTest.prototype.extraLibraries.concat([ + ROOT_PATH + 'ui/webui/resources/js/cr.js', + '../test_browser_proxy.js', + 'test_support.js', 'item_tests.js', ]), };
diff --git a/chrome/test/data/webui/md_downloads/item_tests.js b/chrome/test/data/webui/md_downloads/item_tests.js index 49d7632..6f3e269 100644 --- a/chrome/test/data/webui/md_downloads/item_tests.js +++ b/chrome/test/data/webui/md_downloads/item_tests.js
@@ -6,23 +6,52 @@ /** @type {!downloads.Item} */ let item; + /** @type {!TestIconLoader} */ + let testIconLoader; + setup(function() { PolymerTest.clearBody(); + + // This isn't strictly necessary, but is a probably good idea. + downloads.BrowserProxy.instance_ = new TestDownloadsProxy; + + testIconLoader = new TestIconLoader; + downloads.IconLoader.instance_ = testIconLoader; + item = document.createElement('downloads-item'); document.body.appendChild(item); }); - test('dangerous downloads aren\'t linkable', function() { - item.set('data', { - dangerType: downloads.DangerType.DANGEROUS_FILE, - fileExternallyRemoved: false, - hideDate: true, - state: downloads.States.DANGEROUS, - url: 'http://evil.com' - }); + test('dangerous downloads aren\'t linkable', () => { + item.set('data', createDownload({ + dangerType: downloads.DangerType.DANGEROUS_FILE, + fileExternallyRemoved: false, + hideDate: true, + state: downloads.States.DANGEROUS, + url: 'http://evil.com' + })); Polymer.dom.flush(); assertTrue(item.$['file-link'].hidden); assertFalse(item.$.url.hasAttribute('href')); }); + + test('icon loads successfully', async () => { + testIconLoader.setShouldIconsLoad(true); + item.set('data', createDownload({filePath: 'unique1', hideDate: false})); + const loadedPath = await testIconLoader.whenCalled('loadIcon'); + assertEquals(loadedPath, 'unique1'); + Polymer.dom.flush(); + assertFalse(item.getFileIcon().hidden); + }); + + test('icon fails to load', async () => { + testIconLoader.setShouldIconsLoad(false); + item.set('data', createDownload({filePath: 'unique2', hideDate: false})); + item.set('data', createDownload({hideDate: false})); + const loadedPath = await testIconLoader.whenCalled('loadIcon'); + assertEquals(loadedPath, 'unique2'); + Polymer.dom.flush(); + assertTrue(item.getFileIcon().hidden); + }); });
diff --git a/chrome/test/data/webui/md_downloads/test_support.js b/chrome/test/data/webui/md_downloads/test_support.js index 847d228..713ab7d 100644 --- a/chrome/test/data/webui/md_downloads/test_support.js +++ b/chrome/test/data/webui/md_downloads/test_support.js
@@ -81,6 +81,29 @@ openDownloadsFolderRequiringGesture() {} } +class TestIconLoader extends TestBrowserProxy { + constructor() { + super(['loadIcon']); + + /** @private */ + this.shouldIconsLoad_ = true; + } + + /** @param {boolean} shouldIconsLoad */ + setShouldIconsLoad(shouldIconsLoad) { + this.shouldIconsLoad_ = shouldIconsLoad; + } + + /** + * @param {!HTMLImageElement} imageEl + * @param {string} filePath + */ + loadIcon(imageEl, filePath) { + this.methodCalled('loadIcon', filePath); + return Promise.resolve(this.shouldIconsLoad_); + } +} + /** * @param {Object=} config * @return {!downloads.Data}
diff --git a/chrome/test/data/webui/settings/cr_settings_browsertest.js b/chrome/test/data/webui/settings/cr_settings_browsertest.js index ca1f82a..774546e 100644 --- a/chrome/test/data/webui/settings/cr_settings_browsertest.js +++ b/chrome/test/data/webui/settings/cr_settings_browsertest.js
@@ -593,6 +593,33 @@ /** * Test fixture for + * chrome/browser/resources/settings/people_page/sync_controls.html. + * @constructor + * @extends {CrSettingsBrowserTest} + */ +function CrSettingsPeoplePageSyncControlsTest() {} + +CrSettingsPeoplePageSyncControlsTest.prototype = { + __proto__: CrSettingsBrowserTest.prototype, + + /** @override */ + browsePreload: 'chrome://settings/people_page/sync_controls.html', + + /** @override */ + extraLibraries: CrSettingsBrowserTest.prototype.extraLibraries.concat([ + '../test_browser_proxy.js', + 'test_sync_browser_proxy.js', + 'test_util.js', + 'people_page_sync_controls.js', + ]), +}; + +TEST_F('CrSettingsPeoplePageSyncControlsTest', 'All', function() { + mocha.run(); +}); + +/** + * Test fixture for * chrome/browser/resources/settings/people_page/sync_page.html. * @constructor * @extends {CrSettingsBrowserTest}
diff --git a/chrome/test/data/webui/settings/people_page_sync_controls.js b/chrome/test/data/webui/settings/people_page_sync_controls.js new file mode 100644 index 0000000..5a79974f --- /dev/null +++ b/chrome/test/data/webui/settings/people_page_sync_controls.js
@@ -0,0 +1,109 @@ +// 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. + +cr.define('settings_people_page_sync_controls', function() { + suite('SyncControlsTest', function() { + let syncControls = null; + let browserProxy = null; + + /** + * Returns sync prefs with everything synced. + * @return {!settings.SyncPrefs} + */ + function getSyncAllPrefs() { + return { + appsEnforced: false, + appsRegistered: true, + appsSynced: true, + autofillEnforced: false, + autofillRegistered: true, + autofillSynced: true, + bookmarksEnforced: false, + bookmarksRegistered: true, + bookmarksSynced: true, + extensionsEnforced: false, + extensionsRegistered: true, + extensionsSynced: true, + passwordsEnforced: false, + passwordsRegistered: true, + passwordsSynced: true, + paymentsIntegrationEnabled: true, + preferencesEnforced: false, + preferencesRegistered: true, + preferencesSynced: true, + syncAllDataTypes: true, + tabsEnforced: false, + tabsRegistered: true, + tabsSynced: true, + themesEnforced: false, + themesRegistered: true, + themesSynced: true, + typedUrlsEnforced: false, + typedUrlsRegistered: true, + typedUrlsSynced: true, + }; + } + + setup(function() { + browserProxy = new TestSyncBrowserProxy(); + settings.SyncBrowserProxyImpl.instance_ = browserProxy; + + PolymerTest.clearBody(); + syncControls = document.createElement('settings-sync-controls'); + document.body.appendChild(syncControls); + + // Start with Sync All. + cr.webUIListenerCallback('sync-prefs-changed', getSyncAllPrefs()); + Polymer.dom.flush(); + }); + + teardown(function() { + syncControls.remove(); + }); + + test('SettingIndividualDatatypes', function() { + const syncAllDataTypesControl = syncControls.$.syncAllDataTypesControl; + assertFalse(syncAllDataTypesControl.disabled); + assertTrue(syncAllDataTypesControl.checked); + + // Assert that all the individual datatype controls are disabled. + const datatypeControls = + syncControls.shadowRoot.querySelectorAll('.list-item cr-toggle'); + for (const control of datatypeControls) { + assertTrue(control.disabled); + assertTrue(control.checked); + } + + // Uncheck the Sync All control. + syncAllDataTypesControl.click(); + + function verifyPrefs(prefs) { + const expected = getSyncAllPrefs(); + expected.syncAllDataTypes = false; + assertEquals(JSON.stringify(expected), JSON.stringify(prefs)); + + cr.webUIListenerCallback('sync-prefs-changed', expected); + + // Assert that all the individual datatype controls are enabled. + for (const control of datatypeControls) { + assertFalse(control.disabled); + assertTrue(control.checked); + } + + browserProxy.resetResolver('setSyncDatatypes'); + + // Test an arbitrarily-selected control (extensions synced control). + datatypeControls[2].click(); + return browserProxy.whenCalled('setSyncDatatypes') + .then(function(prefs) { + const expected = getSyncAllPrefs(); + expected.syncAllDataTypes = false; + expected.extensionsSynced = false; + assertEquals(JSON.stringify(expected), JSON.stringify(prefs)); + }); + } + return browserProxy.whenCalled('setSyncDatatypes').then(verifyPrefs); + }); + }); +});
diff --git a/chrome/test/data/webui/settings/people_page_sync_page_test.js b/chrome/test/data/webui/settings/people_page_sync_page_test.js index a4412818..1d56c444 100644 --- a/chrome/test/data/webui/settings/people_page_sync_page_test.js +++ b/chrome/test/data/webui/settings/people_page_sync_page_test.js
@@ -3,8 +3,7 @@ // found in the LICENSE file. cr.define('settings_people_page_sync_page', function() { - - suite('AdvancedSyncSettingsTests', function() { + suite('SyncSettingsTests', function() { let syncPage = null; let browserProxy = null; let encryptWithGoogle = null; @@ -57,20 +56,6 @@ }; } - function openDatatypeConfigurationWithUnifiedConsent(prefs) { - syncPage.unifiedConsentEnabled = true; - cr.webUIListenerCallback('sync-prefs-changed', prefs); - - Polymer.dom.flush(); - - const syncAllDataTypesControl = syncPage.$.syncAllDataTypesControl; - assertFalse(syncAllDataTypesControl.disabled); - assertTrue(syncAllDataTypesControl.checked); - - // Uncheck the Sync All control. - syncAllDataTypesControl.click(); - } - setup(function() { browserProxy = new TestSyncBrowserProxy(); settings.SyncBrowserProxyImpl.instance_ = browserProxy; @@ -246,50 +231,6 @@ assertTrue(spinnerPage.hidden); }); - test('SettingIndividualDatatypes', function() { - const syncAllDataTypesControl = syncPage.$.syncAllDataTypesControl; - assertFalse(syncAllDataTypesControl.disabled); - assertTrue(syncAllDataTypesControl.checked); - - // Assert that all the individual datatype controls are disabled. - const datatypeControls = - syncPage.$$('#configure').querySelectorAll('.list-item cr-toggle'); - for (const control of datatypeControls) { - assertTrue(control.disabled); - assertTrue(control.checked); - } - - // Uncheck the Sync All control. - syncAllDataTypesControl.click(); - - function verifyPrefs(prefs) { - const expected = getSyncAllPrefs(); - expected.syncAllDataTypes = false; - assertEquals(JSON.stringify(expected), JSON.stringify(prefs)); - - cr.webUIListenerCallback('sync-prefs-changed', expected); - - // Assert that all the individual datatype controls are enabled. - for (const control of datatypeControls) { - assertFalse(control.disabled); - assertTrue(control.checked); - } - - browserProxy.resetResolver('setSyncDatatypes'); - - // Test an arbitrarily-selected control (extensions synced control). - datatypeControls[2].click(); - return browserProxy.whenCalled('setSyncDatatypes') - .then(function(prefs) { - const expected = getSyncAllPrefs(); - expected.syncAllDataTypes = false; - expected.extensionsSynced = false; - assertEquals(JSON.stringify(expected), JSON.stringify(prefs)); - }); - } - return browserProxy.whenCalled('setSyncDatatypes').then(verifyPrefs); - }); - test('RadioBoxesEnabledWhenUnencrypted', function() { // Verify that the encryption radio boxes are enabled. assertFalse(encryptWithGoogle.disabled);
diff --git a/chromeos/components/proximity_auth/mock_proximity_auth_client.cc b/chromeos/components/proximity_auth/mock_proximity_auth_client.cc index 063bb3a2..87e624d 100644 --- a/chromeos/components/proximity_auth/mock_proximity_auth_client.cc +++ b/chromeos/components/proximity_auth/mock_proximity_auth_client.cc
@@ -12,9 +12,4 @@ MockProximityAuthClient::~MockProximityAuthClient() {} -std::unique_ptr<cryptauth::CryptAuthClientFactory> -MockProximityAuthClient::CreateCryptAuthClientFactory() { - return base::WrapUnique(CreateCryptAuthClientFactoryPtr()); -} - } // namespace proximity_auth
diff --git a/chromeos/components/proximity_auth/mock_proximity_auth_client.h b/chromeos/components/proximity_auth/mock_proximity_auth_client.h index 61f94be..2ce5256 100644 --- a/chromeos/components/proximity_auth/mock_proximity_auth_client.h +++ b/chromeos/components/proximity_auth/mock_proximity_auth_client.h
@@ -36,15 +36,6 @@ base::Callback<void(const std::string& challenge)> callback)); MOCK_CONST_METHOD0(GetAuthenticatedUsername, std::string(void)); MOCK_METHOD0(GetPrefManager, ProximityAuthPrefManager*(void)); - MOCK_METHOD0(GetDeviceClassifier, cryptauth::DeviceClassifier(void)); - MOCK_METHOD0(GetAccountId, std::string(void)); - MOCK_METHOD0(GetCryptAuthEnrollmentManager, - cryptauth::CryptAuthEnrollmentManager*(void)); - MOCK_METHOD0(GetCryptAuthDeviceManager, - cryptauth::CryptAuthDeviceManager*(void)); - std::unique_ptr<cryptauth::CryptAuthClientFactory> - CreateCryptAuthClientFactory() override; - MOCK_METHOD0(GetLocalDevicePublicKey, std::string(void)); // Proxy mock methods because implementation requires returning scoped_ptr. MOCK_METHOD0(CreateCryptAuthClientFactoryPtr,
diff --git a/chromeos/components/proximity_auth/proximity_auth_client.h b/chromeos/components/proximity_auth/proximity_auth_client.h index 2d9af0e..3b1de34 100644 --- a/chromeos/components/proximity_auth/proximity_auth_client.h +++ b/chromeos/components/proximity_auth/proximity_auth_client.h
@@ -13,12 +13,6 @@ #include "chromeos/components/proximity_auth/screenlock_state.h" #include "chromeos/services/device_sync/proto/cryptauth_api.pb.h" -namespace cryptauth { -class CryptAuthClientFactory; -class CryptAuthDeviceManager; -class CryptAuthEnrollmentManager; -} // namespace cryptauth - namespace proximity_auth { // An interface that needs to be supplied to the Proximity Auth component by its @@ -57,24 +51,6 @@ // Returns the manager responsible for EasyUnlock preferences. virtual ProximityAuthPrefManager* GetPrefManager() = 0; - - // Constructs the CryptAuthClientFactory that can be used for API requests. - virtual std::unique_ptr<cryptauth::CryptAuthClientFactory> - CreateCryptAuthClientFactory() = 0; - - // Constructs the DeviceClassifier message that is sent to CryptAuth for all - // API requests. - virtual cryptauth::DeviceClassifier GetDeviceClassifier() = 0; - - // Returns the account id of the user. - virtual std::string GetAccountId() = 0; - - virtual cryptauth::CryptAuthEnrollmentManager* - GetCryptAuthEnrollmentManager() = 0; - - virtual cryptauth::CryptAuthDeviceManager* GetCryptAuthDeviceManager() = 0; - - virtual std::string GetLocalDevicePublicKey() = 0; }; } // namespace proximity_auth
diff --git a/chromeos/services/device_sync/proto/cryptauth_api.proto b/chromeos/services/device_sync/proto/cryptauth_api.proto index b2589b8..a69cde2f 100644 --- a/chromeos/services/device_sync/proto/cryptauth_api.proto +++ b/chromeos/services/device_sync/proto/cryptauth_api.proto
@@ -31,13 +31,12 @@ optional string device_software_package = 19; // Device type/platform. - // TODO(khorimoto): Change this to a string so it works with Apiary endpoints. - optional DeviceType device_type = 32 [default = UNKNOWN]; + optional string device_type = 32 [default = "unknown"]; } enum DeviceType { UNKNOWN = 0; - ANDROIDOS = 1; + ANDROID = 1; CHROME = 2; IOS = 3; BROWSER = 4; @@ -97,8 +96,7 @@ optional bool mobile_hotspot_supported = 7 [default = false]; // The type of the device (e.g. Android vs iOS). - // TODO(khorimoto): Change this to a string so it works with Apiary endpoints. - optional DeviceType device_type = 8 [default = UNKNOWN]; + optional string device_type = 8 [default = "unknown"]; // A list of seeds for EID BLE advertisements targeting this device. repeated BeaconSeed beacon_seeds = 9; @@ -298,8 +296,7 @@ optional string device_manufacturer = 31; // Used to indicate which type of device this is. - // TODO(khorimoto): Change this to a string so it works with Apiary endpoints. - optional DeviceType device_type = 32 [default = ANDROIDOS]; + optional DeviceType device_type = 32 [default = ANDROID]; // Fields corresponding to screenlock type/features and hardware features // should be numbered in the 400 range.
diff --git a/chromeos/services/device_sync/proto/enum_util.cc b/chromeos/services/device_sync/proto/enum_util.cc index 0b3dcca..c72cca2 100644 --- a/chromeos/services/device_sync/proto/enum_util.cc +++ b/chromeos/services/device_sync/proto/enum_util.cc
@@ -6,6 +6,55 @@ namespace cryptauth { +std::ostream& operator<<(std::ostream& stream, const DeviceType& device_type) { + switch (device_type) { + case DeviceType::ANDROID: + stream << "[Android]"; + break; + case DeviceType::CHROME: + stream << "[Chrome]"; + break; + case DeviceType::IOS: + stream << "[iOS]"; + break; + case DeviceType::BROWSER: + stream << "[Browser]"; + break; + default: + stream << "[Unknown device type]"; + break; + } + return stream; +} + +cryptauth::DeviceType DeviceTypeStringToEnum( + const std::string& device_type_as_string) { + if (device_type_as_string == "android") + return cryptauth::DeviceType::ANDROID; + if (device_type_as_string == "chrome") + return cryptauth::DeviceType::CHROME; + if (device_type_as_string == "ios") + return cryptauth::DeviceType::IOS; + if (device_type_as_string == "browser") + return cryptauth::DeviceType::BROWSER; + return cryptauth::DeviceType::UNKNOWN; +} + +std::string DeviceTypeEnumToString(cryptauth::DeviceType device_type) { + switch (device_type) { + case cryptauth::DeviceType::ANDROID: + return "android"; + case cryptauth::DeviceType::CHROME: + return "chrome"; + case cryptauth::DeviceType::IOS: + return "ios"; + case cryptauth::DeviceType::BROWSER: + return "browser"; + default: + return "unknown"; + } +} + std::ostream& operator<<(std::ostream& stream, const SoftwareFeature& software_feature) { switch (software_feature) {
diff --git a/chromeos/services/device_sync/proto/enum_util.h b/chromeos/services/device_sync/proto/enum_util.h index 6810953..4ae512ee 100644 --- a/chromeos/services/device_sync/proto/enum_util.h +++ b/chromeos/services/device_sync/proto/enum_util.h
@@ -36,6 +36,23 @@ std::string SoftwareFeatureEnumToStringAllCaps( cryptauth::SoftwareFeature software_feature); +std::ostream& operator<<(std::ostream& stream, const DeviceType& device_type); + +// Converts the string representation of a DeviceType to its associated +// Proto enum value. Some Proto messages are sent to Apiary endpoints, which +// translate Proto enums to strings instead of leaving them as enums. Thus, when +// communicating with those endpoints, the proto values should be converted from +// enums to strings before sending them. +cryptauth::DeviceType DeviceTypeStringToEnum( + const std::string& device_type_as_string); + +// Converts a Proto enum DeviceType to its associated string +// representation. Some Proto messages are sent to Apiary endpoints, which +// translate Proto enums to strings instead of leaving them as enums. Thus, when +// communicating with those endpoints, the proto values should be converted from +// strings to enums after receiving them. +std::string DeviceTypeEnumToString(cryptauth::DeviceType device_type); + } // namespace cryptauth #endif // CHROMEOS_SERVICES_DEVICE_SYNC_PROTO_ENUM_UTIL_H_
diff --git a/components/arc/arc_vm_client_adapter.cc b/components/arc/arc_vm_client_adapter.cc index 9c18b1988..5aaec266 100644 --- a/components/arc/arc_vm_client_adapter.cc +++ b/components/arc/arc_vm_client_adapter.cc
@@ -59,7 +59,10 @@ DCHECK(upstart_client); upstart_client->StartJob( kArcVmUpstartJob, - {}, // TODO(yusukes): Pass the content of the |request| to the job. + // arc_session_impl.cc fills the |account_id| field, and it is always + // guaranteed that the ID is not for Incognito mode and is a valid one. + // TODO(yusukes): Pass other fields of the |request| to the job. + {"CHROMEOS_USER=" + request.account_id()}, base::BindOnce(&ArcVmClientAdapter::OnArcInstanceUpgraded, weak_factory_.GetWeakPtr(), std::move(success_callback), std::move(error_callback)));
diff --git a/components/arc/intent_helper/link_handler_model.cc b/components/arc/intent_helper/link_handler_model.cc index f5cc44f..b365a5f2 100644 --- a/components/arc/intent_helper/link_handler_model.cc +++ b/components/arc/intent_helper/link_handler_model.cc
@@ -40,6 +40,7 @@ return false; url::RawCanonOutputW<kMaxValueLen> output; url::DecodeURLEscapeSequences(str.c_str() + value.begin, value.len, + url::DecodeURLMode::kUTF8OrIsomorphic, &output); *out = base::string16(output.data(), output.length()); return true;
diff --git a/components/autofill_strings.grdp b/components/autofill_strings.grdp index 5d2c32d..cf7e29e 100644 --- a/components/autofill_strings.grdp +++ b/components/autofill_strings.grdp
@@ -286,6 +286,9 @@ <message name="IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_TITLE_FIX" desc="The title text for a dialog shown after the user accepts another dialog that offers to migrate local cards into the cloud but there are errors with the cards that they need to address."> Almost done </message> + <message name="IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_CHECKBOX_UNCHECK_WARNING" desc="The warning text, after the user unchecks the checkbox, to indicate this card will still be saved on this device only, not to Google account."> + Saved on this device only + </message> <message name="IDS_AUTOFILL_LOCAL_CARD_MIGRATION_DIALOG_MESSAGE_OFFER" desc="The body text for a dialog that offers to migrate local cards into the cloud. [ICU Syntax]"> {NUM_CARDS, plural, =1 {You'll be able to use it when you're signed in. This card and its billing address will be saved in your Google Account.}
diff --git a/components/cryptauth/cryptauth_client_impl_unittest.cc b/components/cryptauth/cryptauth_client_impl_unittest.cc index 30ff617..f19c819 100644 --- a/components/cryptauth/cryptauth_client_impl_unittest.cc +++ b/components/cryptauth/cryptauth_client_impl_unittest.cc
@@ -11,7 +11,9 @@ #include "base/test/null_task_runner.h" #include "base/test/scoped_task_environment.h" #include "chromeos/services/device_sync/proto/cryptauth_api.pb.h" +#include "chromeos/services/device_sync/proto/enum_util.h" #include "components/cryptauth/cryptauth_api_call_flow.h" +#include "components/cryptauth/proto/cryptauth_api.pb.h" #include "components/cryptauth/switches.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "services/identity/public/cpp/identity_test_environment.h" @@ -113,7 +115,8 @@ device_classifier.set_device_software_version_code( kDeviceSoftwareVersionCode); device_classifier.set_device_software_package(kDeviceSoftwarePackage); - device_classifier.set_device_type(kDeviceType); + device_classifier.set_device_type( + cryptauth::DeviceTypeEnumToString(kDeviceType)); identity_test_environment_.MakePrimaryAccountAvailable(kEmail); @@ -577,7 +580,8 @@ device_classifier.device_software_version_code()); EXPECT_EQ(kDeviceSoftwarePackage, device_classifier.device_software_package()); - EXPECT_EQ(kDeviceType, device_classifier.device_type()); + EXPECT_EQ(kDeviceType, + cryptauth::DeviceTypeStringToEnum(device_classifier.device_type())); } TEST_F(CryptAuthClientTest, GetAccessTokenUsed) {
diff --git a/components/cryptauth/cryptauth_device_manager_impl.cc b/components/cryptauth/cryptauth_device_manager_impl.cc index 80fb72f8..91af0011 100644 --- a/components/cryptauth/cryptauth_device_manager_impl.cc +++ b/components/cryptauth/cryptauth_device_manager_impl.cc
@@ -247,8 +247,12 @@ std::to_string(device.last_update_time_millis())); } - if (device.has_device_type() && DeviceType_IsValid(device.device_type())) { - dictionary->SetInteger(kExternalDeviceKeyDeviceType, device.device_type()); + if (device.has_device_type() && + DeviceType_IsValid( + cryptauth::DeviceTypeStringToEnum(device.device_type()))) { + dictionary->SetInteger( + kExternalDeviceKeyDeviceType, + cryptauth::DeviceTypeStringToEnum(device.device_type())); } dictionary->Set(kExternalDeviceKeyBeaconSeeds, @@ -459,7 +463,8 @@ int device_type; if (dictionary.GetInteger(kExternalDeviceKeyDeviceType, &device_type) && DeviceType_IsValid(device_type)) { - external_device->set_device_type(static_cast<DeviceType>(device_type)); + external_device->set_device_type(cryptauth::DeviceTypeEnumToString( + static_cast<DeviceType>(device_type))); } const base::ListValue* beacon_seeds;
diff --git a/components/cryptauth/cryptauth_device_manager_impl_unittest.cc b/components/cryptauth/cryptauth_device_manager_impl_unittest.cc index 4a5371e..5f547071 100644 --- a/components/cryptauth/cryptauth_device_manager_impl_unittest.cc +++ b/components/cryptauth/cryptauth_device_manager_impl_unittest.cc
@@ -256,7 +256,9 @@ int device_type; if (device_dictionary->GetInteger("device_type", &device_type)) { EXPECT_TRUE(expected_device.has_device_type()); - EXPECT_EQ(expected_device.device_type(), device_type); + EXPECT_EQ( + cryptauth::DeviceTypeStringToEnum(expected_device.device_type()), + device_type); } else { EXPECT_FALSE(expected_device.has_device_type()); } @@ -964,7 +966,8 @@ device_with_all_fields.set_bluetooth_address("aa:bb:cc:dd:ee:ff"); device_with_all_fields.set_unlockable(true); device_with_all_fields.set_last_update_time_millis(123456789L); - device_with_all_fields.set_device_type(DeviceType::ANDROIDOS); + device_with_all_fields.set_device_type( + cryptauth::DeviceTypeEnumToString(ANDROID)); BeaconSeed seed1; seed1.set_data(kBeaconSeed1Data);
diff --git a/components/cryptauth/device_classifier_util.cc b/components/cryptauth/device_classifier_util.cc index 2af2709..0040099 100644 --- a/components/cryptauth/device_classifier_util.cc +++ b/components/cryptauth/device_classifier_util.cc
@@ -9,6 +9,7 @@ #include "base/no_destructor.h" #include "base/system/sys_info.h" #include "base/version.h" +#include "chromeos/services/device_sync/proto/enum_util.h" #include "components/version_info/version_info.h" namespace cryptauth { @@ -25,7 +26,8 @@ base::SysInfo::OperatingSystemVersionNumbers(&major_version, &minor_version, &bugfix_version); classifier.set_device_os_version_code(major_version); - classifier.set_device_type(cryptauth::CHROME); + classifier.set_device_type( + cryptauth::DeviceTypeEnumToString(cryptauth::CHROME)); const std::vector<uint32_t>& version_components = version_info::GetVersion().components();
diff --git a/components/download/internal/common/download_item_impl.cc b/components/download/internal/common/download_item_impl.cc index b5fd270b..a39e308 100644 --- a/components/download/internal/common/download_item_impl.cc +++ b/components/download/internal/common/download_item_impl.cc
@@ -1234,6 +1234,9 @@ TRACE_EVENT_SCOPE_THREAD, "bytes_so_far", GetReceivedBytes()); + if (IsPaused() && destination_info_.received_bytes == bytes_so_far) + return; + UpdateObservers(); }
diff --git a/components/flags_ui/resources/flags.css b/components/flags_ui/resources/flags.css index 8ab2de8..ce18774 100644 --- a/components/flags_ui/resources/flags.css +++ b/components/flags_ui/resources/flags.css
@@ -214,7 +214,6 @@ .experiment-name { color: black; - cursor: pointer; display: inline-block; font-size: 13px; font-weight: 500; @@ -452,6 +451,10 @@ border-bottom: 1px solid #f7f7f7; } + .experiment-name { + cursor: pointer; + } + .experiment .flex-container { flex-flow: column; }
diff --git a/components/printing/browser/features.cc b/components/printing/browser/features.cc index e24200d..670650e 100644 --- a/components/printing/browser/features.cc +++ b/components/printing/browser/features.cc
@@ -10,5 +10,10 @@ const base::Feature kUsePdfCompositorServiceForPrint{ "UsePdfCompositorServiceForPrint", base::FEATURE_ENABLED_BY_DEFAULT}; +#if defined(OS_MACOSX) +const base::Feature kEnableCustomMacPaperSizes{ + "EnableCustomMacPaperSizes", base::FEATURE_DISABLED_BY_DEFAULT}; +#endif + } // namespace features } // namespace printing
diff --git a/components/printing/browser/features.h b/components/printing/browser/features.h index 1d18c2f..0dddcfa 100644 --- a/components/printing/browser/features.h +++ b/components/printing/browser/features.h
@@ -6,6 +6,7 @@ #define COMPONENTS_PRINTING_BROWSER_FEATURES_H_ #include "base/feature_list.h" +#include "build/build_config.h" namespace printing { namespace features { @@ -13,6 +14,10 @@ // Use pdf compositor service to generate PDF files for printing. extern const base::Feature kUsePdfCompositorServiceForPrint; +#if defined(OS_MACOSX) +extern const base::Feature kEnableCustomMacPaperSizes; +#endif + } // namespace features } // namespace printing
diff --git a/components/printing/common/BUILD.gn b/components/printing/common/BUILD.gn index 8c9b5348..f0dbe71 100644 --- a/components/printing/common/BUILD.gn +++ b/components/printing/common/BUILD.gn
@@ -29,6 +29,13 @@ "//ui/gfx/ipc/geometry", "//ui/gfx/ipc/skia", ] + + if (is_mac) { + sources += [ + "printer_capabilities_mac.h", + "printer_capabilities_mac.mm", + ] + } } source_set("unit_tests") { @@ -44,4 +51,8 @@ "//printing:test_support", "//testing/gtest", ] + + if (is_mac) { + sources += [ "printer_capabilities_mac_unittest.mm" ] + } }
diff --git a/components/printing/common/printer_capabilities_mac.h b/components/printing/common/printer_capabilities_mac.h new file mode 100644 index 0000000..e391bfc --- /dev/null +++ b/components/printing/common/printer_capabilities_mac.h
@@ -0,0 +1,28 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PRINTING_COMMON_PRINTER_CAPABILITIES_MAC_H_ +#define COMPONENTS_PRINTING_COMMON_PRINTER_CAPABILITIES_MAC_H_ + +#include "printing/backend/print_backend.h" + +namespace base { +class FilePath; +} + +namespace printing { + +// Must be called on a task runner that allows blocking. +PrinterSemanticCapsAndDefaults::Papers GetMacCustomPaperSizes(); + +namespace internal { + +PrinterSemanticCapsAndDefaults::Papers GetMacCustomPaperSizesFromFile( + const base::FilePath& path); + +} // namespace internal + +} // namespace printing + +#endif // COMPONENTS_PRINTING_COMMON_PRINTER_CAPABILITIES_MAC_H_
diff --git a/components/printing/common/printer_capabilities_mac.mm b/components/printing/common/printer_capabilities_mac.mm new file mode 100644 index 0000000..2dc3429 --- /dev/null +++ b/components/printing/common/printer_capabilities_mac.mm
@@ -0,0 +1,78 @@ +// 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 "components/printing/common/printer_capabilities_mac.h" + +#import <AppKit/AppKit.h> + +#include "base/files/file_path.h" +#include "base/mac/foundation_util.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/mac/scoped_nsobject.h" +#include "base/strings/sys_string_conversions.h" +#include "base/threading/scoped_blocking_call.h" +#include "printing/units.h" + +namespace printing { + +namespace { + +// On macOS, the custom paper size UI limits the value to 99999. +constexpr int kMacPaperDimensionLimit = 99999 * kPointsPerInch; + +} // namespace + +PrinterSemanticCapsAndDefaults::Papers GetMacCustomPaperSizes() { + base::FilePath local_library; + bool success = + base::mac::GetUserDirectory(NSLibraryDirectory, &local_library); + DCHECK(success); + + base::FilePath plist = local_library.Append("Preferences") + .Append("com.apple.print.custompapers.plist"); + return internal::GetMacCustomPaperSizesFromFile(plist); +} + +namespace internal { + +PrinterSemanticCapsAndDefaults::Papers GetMacCustomPaperSizesFromFile( + const base::FilePath& path) { + PrinterSemanticCapsAndDefaults::Papers custom_paper_sizes; + + base::scoped_nsobject<NSDictionary> custom_papers_dict; + { + base::ScopedBlockingCall scoped_block(base::BlockingType::MAY_BLOCK); + custom_papers_dict.reset([[NSDictionary alloc] + initWithContentsOfFile:base::mac::FilePathToNSString(path)]); + } + + for (id key in custom_papers_dict.get()) { + NSDictionary* paper = [custom_papers_dict objectForKey:key]; + if (![paper isKindOfClass:[NSDictionary class]]) + continue; + + int width = [[paper objectForKey:@"width"] intValue]; + int height = [[paper objectForKey:@"height"] intValue]; + if (width <= 0 || height <= 0 || width > kMacPaperDimensionLimit || + height > kMacPaperDimensionLimit) { + continue; + } + + NSString* name = [paper objectForKey:@"name"]; + if (![name isKindOfClass:[NSString class]] || [name length] == 0) + continue; + + gfx::Size size_microns( + ConvertUnit(width, kPointsPerInch, kMicronsPerInch), + ConvertUnit(height, kPointsPerInch, kMicronsPerInch)); + custom_paper_sizes.push_back( + {base::SysNSStringToUTF8(name), "", size_microns}); + } + + return custom_paper_sizes; +} + +} // namespace internal + +} // namespace printing
diff --git a/components/printing/common/printer_capabilities_mac_unittest.mm b/components/printing/common/printer_capabilities_mac_unittest.mm new file mode 100644 index 0000000..af020f30 --- /dev/null +++ b/components/printing/common/printer_capabilities_mac_unittest.mm
@@ -0,0 +1,197 @@ +// 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 "components/printing/common/printer_capabilities_mac.h" + +#include "base/files/scoped_temp_dir.h" +#include "base/mac/foundation_util.h" +#include "base/mac/scoped_nsobject.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace printing { + +namespace { + +base::FilePath WriteOutCustomPapersPlist(const base::FilePath& dir, + const char* name, + NSDictionary* dict) { + base::FilePath path = dir.Append(name); + NSString* plist_path = base::mac::FilePathToNSString(path); + if (![dict writeToFile:plist_path atomically:YES]) + path.clear(); + return path; +} + +} // namespace + +TEST(PrinterCapabilitiesMacTest, GetMacCustomPaperSizesFromFile) { + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"name" : @"foo", + @"width" : @144, + @"height" : @288, + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "good1.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(1u, papers.size()); + EXPECT_EQ("foo", papers[0].display_name); + EXPECT_EQ("", papers[0].vendor_id); + EXPECT_EQ(50800, papers[0].size_um.width()); + EXPECT_EQ(101600, papers[0].size_um.height()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @100, + @"height" : @200, + @"name" : @"bar", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "good2.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(1u, papers.size()); + EXPECT_EQ("bar", papers[0].display_name); + EXPECT_EQ("", papers[0].vendor_id); + EXPECT_EQ(35278, papers[0].size_um.width()); + EXPECT_EQ(70556, papers[0].size_um.height()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{}]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "empty.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"height" : @200, + @"name" : @"bar", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "no_width.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @100, + @"name" : @"bar", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "no_height.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @100, + @"height" : @200, + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "no_name.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @0, + @"height" : @200, + @"name" : @"bar", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "zero_width.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @100, + @"height" : @0, + @"name" : @"bar", + } + }]); + base::FilePath path = WriteOutCustomPapersPlist(temp_dir.GetPath(), + "zero_height.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @7199929, + @"height" : @200, + @"name" : @"bar", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "big_width.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @100, + @"height" : @7199929, + @"name" : @"bar", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "big_height.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } + { + base::scoped_nsobject<NSMutableDictionary> dict( + [[NSMutableDictionary alloc] initWithDictionary:@{ + @"foo" : @{ + @"width" : @100, + @"height" : @200, + @"name" : @"", + } + }]); + base::FilePath path = + WriteOutCustomPapersPlist(temp_dir.GetPath(), "empty_name.plist", dict); + ASSERT_FALSE(path.empty()); + auto papers = internal::GetMacCustomPaperSizesFromFile(path); + ASSERT_EQ(0u, papers.size()); + } +} + +} // namespace printing
diff --git a/components/services/filesystem/BUILD.gn b/components/services/filesystem/BUILD.gn index e6ecaff8..21d8a9f5 100644 --- a/components/services/filesystem/BUILD.gn +++ b/components/services/filesystem/BUILD.gn
@@ -3,7 +3,7 @@ # found in the LICENSE file. import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -35,7 +35,7 @@ if (!is_ios) { # service binaries are not supported on iOS. - service("filesystem") { + service_executable("filesystem") { sources = [ "file_system_app.cc", "file_system_app.h",
diff --git a/components/services/filesystem/main.cc b/components/services/filesystem/main.cc index 5890ec1..b4957fb 100644 --- a/components/services/filesystem/main.cc +++ b/components/services/filesystem/main.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "components/services/filesystem/file_system_app.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/components/services/font/BUILD.gn b/components/services/font/BUILD.gn index 96ceee2a..1c1e289 100644 --- a/components/services/font/BUILD.gn +++ b/components/services/font/BUILD.gn
@@ -5,7 +5,7 @@ import("//build/config/features.gni") import("//ppapi/buildflags/buildflags.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -56,7 +56,7 @@ } } -service("font_service") { +service_executable("font_service") { sources = [ "main.cc", ]
diff --git a/components/services/font/main.cc b/components/services/font/main.cc index ab58533..a9b1386 100644 --- a/components/services/font/main.cc +++ b/components/services/font/main.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "components/services/font/font_service_app.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/components/services/leveldb/BUILD.gn b/components/services/leveldb/BUILD.gn index 1d2e024..29c62d4 100644 --- a/components/services/leveldb/BUILD.gn +++ b/components/services/leveldb/BUILD.gn
@@ -3,7 +3,7 @@ # found in the LICENSE file. import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -32,7 +32,7 @@ ] } -service("leveldb") { +service_executable("leveldb") { sources = [ "leveldb_app.cc", "leveldb_app.h",
diff --git a/components/services/leveldb/main.cc b/components/services/leveldb/main.cc index b463f2d..64ca3b56 100644 --- a/components/services/leveldb/main.cc +++ b/components/services/leveldb/main.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "components/services/leveldb/leveldb_app.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/components/viz/service/gl/gpu_service_impl.cc b/components/viz/service/gl/gpu_service_impl.cc index 9ce7beb2..fce46b0 100644 --- a/components/viz/service/gl/gpu_service_impl.cc +++ b/components/viz/service/gl/gpu_service_impl.cc
@@ -264,7 +264,8 @@ gpu_preferences_, this, watchdog_thread_.get(), main_runner_, io_runner_, scheduler_.get(), sync_point_manager_, gpu_memory_buffer_factory_.get(), gpu_feature_info_, std::move(activity_flags), - std::move(default_offscreen_surface), vulkan_context_provider()); + std::move(default_offscreen_surface), + nullptr /* image_decode_accelerator_worker */, vulkan_context_provider()); media_gpu_channel_manager_.reset( new media::MediaGpuChannelManager(gpu_channel_manager_.get()));
diff --git a/components/viz/test/test_context_provider.cc b/components/viz/test/test_context_provider.cc index 0b35327..a9c796f5 100644 --- a/components/viz/test/test_context_provider.cc +++ b/components/viz/test/test_context_provider.cc
@@ -126,6 +126,17 @@ } gpu::Mailbox TestSharedImageInterface::CreateSharedImage( + ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) { + auto mailbox = gpu::Mailbox::Generate(); + shared_images_.insert(mailbox); + return mailbox; +} + +gpu::Mailbox TestSharedImageInterface::CreateSharedImage( gfx::GpuMemoryBuffer* gpu_memory_buffer, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const gfx::ColorSpace& color_space,
diff --git a/components/viz/test/test_context_provider.h b/components/viz/test/test_context_provider.h index 045a50c6..ab0af20f 100644 --- a/components/viz/test/test_context_provider.h +++ b/components/viz/test/test_context_provider.h
@@ -42,6 +42,12 @@ const gfx::ColorSpace& color_space, uint32_t usage) override; + gpu::Mailbox CreateSharedImage(ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) override; + gpu::Mailbox CreateSharedImage( gfx::GpuMemoryBuffer* gpu_memory_buffer, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager,
diff --git a/content/browser/appcache/appcache_host.cc b/content/browser/appcache/appcache_host.cc index 97ac5cd..9ff6309d 100644 --- a/content/browser/appcache/appcache_host.cc +++ b/content/browser/appcache/appcache_host.cc
@@ -134,7 +134,9 @@ if (!manifest_url.is_empty() && (manifest_url.GetOrigin() == document_url.GetOrigin())) { - DCHECK(!first_party_url_.is_empty()); +#if DCHECK_IS_ON() + DCHECK(first_party_url_initialized_); +#endif AppCachePolicy* policy = service()->appcache_policy(); if (policy && !policy->CanCreateAppCache(manifest_url, first_party_url_)) { @@ -308,6 +310,9 @@ // Store the first party origin so that it can be used later in SelectCache // for checking whether the creation of the appcache is allowed. first_party_url_ = request->GetSiteForCookies(); +#if DCHECK_IS_ON() + first_party_url_initialized_ = true; +#endif return base::WrapUnique(new AppCacheRequestHandler( this, resource_type, should_reset_appcache, std::move(request))); }
diff --git a/content/browser/appcache/appcache_host.h b/content/browser/appcache/appcache_host.h index ee149def..bb14d1c 100644 --- a/content/browser/appcache/appcache_host.h +++ b/content/browser/appcache/appcache_host.h
@@ -31,21 +31,13 @@ namespace content { FORWARD_DECLARE_TEST(AppCacheGroupTest, CleanupUnusedGroup); FORWARD_DECLARE_TEST(AppCacheGroupTest, QueueUpdate); -FORWARD_DECLARE_TEST(AppCacheHostTest, Basic); -FORWARD_DECLARE_TEST(AppCacheHostTest, SelectNoCache); -FORWARD_DECLARE_TEST(AppCacheHostTest, ForeignEntry); FORWARD_DECLARE_TEST(AppCacheHostTest, FailedCacheLoad); FORWARD_DECLARE_TEST(AppCacheHostTest, FailedGroupLoad); FORWARD_DECLARE_TEST(AppCacheHostTest, SetSwappableCache); -FORWARD_DECLARE_TEST(AppCacheHostTest, ForDedicatedWorker); -FORWARD_DECLARE_TEST(AppCacheHostTest, SelectCacheAllowed); -FORWARD_DECLARE_TEST(AppCacheHostTest, SelectCacheBlocked); -FORWARD_DECLARE_TEST(AppCacheHostTest, SelectCacheTwice); FORWARD_DECLARE_TEST(AppCacheTest, CleanupUnusedCache); class AppCache; class AppCacheFrontend; class AppCacheGroupTest; -class AppCacheHostTest; class AppCacheRequest; class AppCacheRequestHandler; class AppCacheRequestHandlerTest; @@ -190,6 +182,12 @@ } const GURL& first_party_url() const { return first_party_url_; } + void SetFirstPartyUrlForTesting(const GURL& url) { + first_party_url_ = url; +#if DCHECK_IS_ON() + first_party_url_initialized_ = true; +#endif + } // Returns a weak pointer reference to the host. base::WeakPtr<AppCacheHost> GetWeakPtr(); @@ -205,7 +203,6 @@ AppCacheSubresourceURLFactory* subresource_factory); private: - friend class content::AppCacheHostTest; friend class content::AppCacheStorageImplTest; friend class content::AppCacheRequestHandlerTest; friend class content::appcache_update_job_unittest::AppCacheUpdateJobTest; @@ -347,19 +344,15 @@ // First party url to be used in policy checks. GURL first_party_url_; +#if DCHECK_IS_ON() + bool first_party_url_initialized_ = false; +#endif FRIEND_TEST_ALL_PREFIXES(content::AppCacheGroupTest, CleanupUnusedGroup); FRIEND_TEST_ALL_PREFIXES(content::AppCacheGroupTest, QueueUpdate); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, Basic); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, SelectNoCache); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, ForeignEntry); FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, FailedCacheLoad); FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, FailedGroupLoad); FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, SetSwappableCache); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, ForDedicatedWorker); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, SelectCacheAllowed); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, SelectCacheBlocked); - FRIEND_TEST_ALL_PREFIXES(content::AppCacheHostTest, SelectCacheTwice); FRIEND_TEST_ALL_PREFIXES(content::AppCacheTest, CleanupUnusedCache); // In the network service world points to the subresource URLLoaderFactory.
diff --git a/content/browser/appcache/appcache_host_unittest.cc b/content/browser/appcache/appcache_host_unittest.cc index 64f9bcf..83fa1c52 100644 --- a/content/browser/appcache/appcache_host_unittest.cc +++ b/content/browser/appcache/appcache_host_unittest.cc
@@ -438,7 +438,7 @@ const GURL kManifestUrl(GURL("http://whatever/cache.manifest")); { AppCacheHost host(1, &mock_frontend_, &service_); - host.first_party_url_ = kDocAndOriginUrl; + host.SetFirstPartyUrlForTesting(kDocAndOriginUrl); host.SelectCache(kDocAndOriginUrl, kAppCacheNoCacheId, kManifestUrl); EXPECT_EQ(1, mock_quota_proxy->GetInUseCount(kOrigin)); @@ -479,7 +479,7 @@ const GURL kManifestUrl(GURL("http://whatever/cache.manifest")); { AppCacheHost host(1, &mock_frontend_, &service_); - host.first_party_url_ = kDocAndOriginUrl; + host.SetFirstPartyUrlForTesting(kDocAndOriginUrl); host.SelectCache(kDocAndOriginUrl, kAppCacheNoCacheId, kManifestUrl); EXPECT_EQ(1, mock_quota_proxy->GetInUseCount(kOrigin));
diff --git a/content/browser/appcache/appcache_storage_impl_unittest.cc b/content/browser/appcache/appcache_storage_impl_unittest.cc index 8fe73464..9599a172 100644 --- a/content/browser/appcache/appcache_storage_impl_unittest.cc +++ b/content/browser/appcache/appcache_storage_impl_unittest.cc
@@ -1749,7 +1749,7 @@ backend_->RegisterHost(1); AppCacheHost* host1 = backend_->GetHost(1); const GURL kEmptyPageUrl(MockHttpServer::GetMockUrl("empty.html")); - host1->first_party_url_ = kEmptyPageUrl; + host1->SetFirstPartyUrlForTesting(kEmptyPageUrl); host1->SelectCache(kEmptyPageUrl, kAppCacheNoCacheId, MockHttpServer::GetMockUrl("manifest"));
diff --git a/content/browser/appcache/appcache_update_job_unittest.cc b/content/browser/appcache/appcache_update_job_unittest.cc index dd69e96..ffb2202 100644 --- a/content/browser/appcache/appcache_update_job_unittest.cc +++ b/content/browser/appcache/appcache_update_job_unittest.cc
@@ -2234,7 +2234,7 @@ MockFrontend* frontend = MakeMockFrontend(); AppCacheHost* host = MakeHost(1, frontend); - host->first_party_url_ = kManifestUrl; + host->SetFirstPartyUrlForTesting(kManifestUrl); host->SelectCache(MockHttpServer::GetMockUrl("files/empty1"), kAppCacheNoCacheId, kManifestUrl);
diff --git a/content/browser/background_fetch/background_fetch_context.cc b/content/browser/background_fetch/background_fetch_context.cc index 3882c17..692ea3d 100644 --- a/content/browser/background_fetch/background_fetch_context.cc +++ b/content/browser/background_fetch/background_fetch_context.cc
@@ -84,7 +84,7 @@ for (auto& data : initialization_data) { for (auto& observer : data_manager_->observers()) { observer.OnRegistrationLoadedAtStartup( - data.registration_id, data.registration, data.options.Clone(), + data.registration_id, *data.registration, data.options.Clone(), data.icon, data.num_completed_requests, data.num_requests, data.active_fetch_requests); } @@ -117,20 +117,19 @@ void BackgroundFetchContext::DidGetRegistration( blink::mojom::BackgroundFetchService::GetRegistrationCallback callback, blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration) { + blink::mojom::BackgroundFetchRegistrationPtr registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (error != blink::mojom::BackgroundFetchError::NONE) { - std::move(callback).Run(error, - base::nullopt /* BackgroundFetchRegistration */); + std::move(callback).Run( + error, nullptr /* blink::mojom::BackgroundFetchRegistration */); return; } - BackgroundFetchRegistration updated_registration(registration); for (auto& observer : data_manager_->observers()) - observer.OnRegistrationQueried(&updated_registration); + observer.OnRegistrationQueried(registration.get()); - std::move(callback).Run(error, updated_registration); + std::move(callback).Run(error, std::move(registration)); } void BackgroundFetchContext::StartFetch( @@ -206,8 +205,7 @@ // No permission, the fetch should be rejected. std::move(fetch_callbacks_[registration_id]) - .Run(blink::mojom::BackgroundFetchError::PERMISSION_DENIED, - base::nullopt); + .Run(blink::mojom::BackgroundFetchError::PERMISSION_DENIED, nullptr); fetch_callbacks_.erase(registration_id); } @@ -220,7 +218,7 @@ void BackgroundFetchContext::DidCreateRegistration( const BackgroundFetchRegistrationId& registration_id, blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration) { + blink::mojom::BackgroundFetchRegistrationPtr registration) { DCHECK_CURRENTLY_ON(BrowserThread::IO); auto iter = fetch_callbacks_.find(registration_id); @@ -231,9 +229,9 @@ return; if (error == blink::mojom::BackgroundFetchError::NONE) - std::move(iter->second).Run(error, registration); + std::move(iter->second).Run(error, std::move(registration)); else - std::move(iter->second).Run(error, base::nullopt /* registration */); + std::move(iter->second).Run(error, nullptr /* registration */); fetch_callbacks_.erase(registration_id); }
diff --git a/content/browser/background_fetch/background_fetch_context.h b/content/browser/background_fetch/background_fetch_context.h index 256b7a6..edfbac70 100644 --- a/content/browser/background_fetch/background_fetch_context.h +++ b/content/browser/background_fetch/background_fetch_context.h
@@ -143,13 +143,13 @@ void DidGetRegistration( blink::mojom::BackgroundFetchService::GetRegistrationCallback callback, blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration); + blink::mojom::BackgroundFetchRegistrationPtr registration); // Called when a new registration has been created by the data manager. void DidCreateRegistration( const BackgroundFetchRegistrationId& registration_id, blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration); + blink::mojom::BackgroundFetchRegistrationPtr registration); // Called when the sequence of matching settled fetches have been received // from storage, and |callback| can be invoked to pass these on to the
diff --git a/content/browser/background_fetch/background_fetch_data_manager.h b/content/browser/background_fetch/background_fetch_data_manager.h index 9b88d49..14229af0 100644 --- a/content/browser/background_fetch/background_fetch_data_manager.h +++ b/content/browser/background_fetch/background_fetch_data_manager.h
@@ -67,7 +67,7 @@ std::vector<BackgroundFetchSettledFetch>)>; using GetRegistrationCallback = base::OnceCallback<void(blink::mojom::BackgroundFetchError, - const BackgroundFetchRegistration&)>; + blink::mojom::BackgroundFetchRegistrationPtr)>; using MarkRegistrationForDeletionCallback = base::OnceCallback<void(blink::mojom::BackgroundFetchError, blink::mojom::BackgroundFetchFailureReason)>;
diff --git a/content/browser/background_fetch/background_fetch_data_manager_observer.h b/content/browser/background_fetch/background_fetch_data_manager_observer.h index 0b36864..319f3df 100644 --- a/content/browser/background_fetch/background_fetch_data_manager_observer.h +++ b/content/browser/background_fetch/background_fetch_data_manager_observer.h
@@ -16,7 +16,6 @@ namespace content { -struct BackgroundFetchRegistration; class BackgroundFetchRegistrationId; class BackgroundFetchRequestInfo; @@ -28,7 +27,7 @@ // Called when the Background Fetch |registration| has been created. virtual void OnRegistrationCreated( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_requests, @@ -37,7 +36,7 @@ // Called on start-up when an incomplete registration has been found. virtual void OnRegistrationLoadedAtStartup( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_completed_requests, @@ -48,7 +47,7 @@ // Called when a registration is being queried. Implementations should update // |registration| with in-progress information. virtual void OnRegistrationQueried( - BackgroundFetchRegistration* registration) = 0; + blink::mojom::BackgroundFetchRegistration* registration) = 0; // Called if corrupted data is found in the Service Worker database. virtual void OnServiceWorkerDatabaseCorrupted(
diff --git a/content/browser/background_fetch/background_fetch_data_manager_unittest.cc b/content/browser/background_fetch/background_fetch_data_manager_unittest.cc index 8a2c2a2..20c540ea 100644 --- a/content/browser/background_fetch/background_fetch_data_manager_unittest.cc +++ b/content/browser/background_fetch/background_fetch_data_manager_unittest.cc
@@ -75,10 +75,11 @@ std::move(quit_closure).Run(); } -void DidCreateRegistration(base::OnceClosure quit_closure, - blink::mojom::BackgroundFetchError* out_error, - blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration) { +void DidCreateRegistration( + base::OnceClosure quit_closure, + blink::mojom::BackgroundFetchError* out_error, + blink::mojom::BackgroundFetchError error, + blink::mojom::BackgroundFetchRegistrationPtr registration) { *out_error = error; std::move(quit_closure).Run(); } @@ -263,20 +264,20 @@ DCHECK(HasCache(registration_id.unique_id())); } - BackgroundFetchRegistration GetRegistration( + blink::mojom::BackgroundFetchRegistrationPtr GetRegistration( int64_t service_worker_registration_id, const url::Origin& origin, const std::string developer_id, blink::mojom::BackgroundFetchError* out_error) { DCHECK(out_error); - BackgroundFetchRegistration registration; + auto registration = blink::mojom::BackgroundFetchRegistration::New(); base::RunLoop run_loop; background_fetch_data_manager_->GetRegistration( service_worker_registration_id, origin, developer_id, base::BindOnce(&BackgroundFetchDataManagerTest::DidGetRegistration, base::Unretained(this), run_loop.QuitClosure(), - out_error, ®istration)); + out_error, registration.get())); run_loop.Run(); return registration; @@ -577,35 +578,38 @@ } // BackgroundFetchDataManagerObserver mocks: - MOCK_METHOD6(OnRegistrationCreated, - void(const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, - blink::mojom::BackgroundFetchOptionsPtr options, - const SkBitmap& icon, - int num_requests, - bool start_paused)); - MOCK_METHOD7(OnRegistrationLoadedAtStartup, - void(const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, - blink::mojom::BackgroundFetchOptionsPtr options, - const SkBitmap& icon, - int num_completed_requests, - int num_requests, - std::vector<scoped_refptr<BackgroundFetchRequestInfo>> - active_fetch_requests)); + MOCK_METHOD6( + OnRegistrationCreated, + void(const BackgroundFetchRegistrationId& registration_id, + const blink::mojom::BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchOptionsPtr options, + const SkBitmap& icon, + int num_requests, + bool start_paused)); + MOCK_METHOD7( + OnRegistrationLoadedAtStartup, + void(const BackgroundFetchRegistrationId& registration_id, + const blink::mojom::BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchOptionsPtr options, + const SkBitmap& icon, + int num_completed_requests, + int num_requests, + std::vector<scoped_refptr<BackgroundFetchRequestInfo>> + active_fetch_requests)); MOCK_METHOD1(OnRegistrationQueried, - void(BackgroundFetchRegistration* registration)); + void(blink::mojom::BackgroundFetchRegistration* registration)); MOCK_METHOD1(OnServiceWorkerDatabaseCorrupted, void(int64_t service_worker_registration_id)); protected: - void DidGetRegistration(base::OnceClosure quit_closure, - blink::mojom::BackgroundFetchError* out_error, - BackgroundFetchRegistration* out_registration, - blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration) { + void DidGetRegistration( + base::OnceClosure quit_closure, + blink::mojom::BackgroundFetchError* out_error, + blink::mojom::BackgroundFetchRegistration* out_registration, + blink::mojom::BackgroundFetchError error, + blink::mojom::BackgroundFetchRegistrationPtr registration) { *out_error = error; - *out_registration = registration; + *out_registration = *registration; std::move(quit_closure).Run(); } @@ -975,9 +979,9 @@ GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(kExampleUniqueId, registration.unique_id); - EXPECT_EQ(kExampleDeveloperId, registration.developer_id); - EXPECT_EQ(0u, registration.upload_total); + EXPECT_EQ(kExampleUniqueId, registration->unique_id); + EXPECT_EQ(kExampleDeveloperId, registration->developer_id); + EXPECT_EQ(0u, registration->upload_total); // Verify that retrieving using the wrong developer id doesn't work. registration = @@ -990,8 +994,8 @@ registration = GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(kExampleUniqueId, registration.unique_id); - EXPECT_EQ(kExampleDeveloperId, registration.developer_id); + EXPECT_EQ(kExampleUniqueId, registration->unique_id); + EXPECT_EQ(kExampleDeveloperId, registration->developer_id); } TEST_F(BackgroundFetchDataManagerTest, GetMetadata) { @@ -1059,9 +1063,9 @@ GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(registration.unique_id, kExampleUniqueId); - EXPECT_EQ(registration.developer_id, kExampleDeveloperId); - EXPECT_EQ(registration.upload_total, upload_data.size()); + EXPECT_EQ(registration->unique_id, kExampleUniqueId); + EXPECT_EQ(registration->developer_id, kExampleDeveloperId); + EXPECT_EQ(registration->upload_total, upload_data.size()); } TEST_F(BackgroundFetchDataManagerTest, LargeIconNotPersisted) { @@ -1138,8 +1142,8 @@ GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(kExampleUniqueId, registration.unique_id); - EXPECT_EQ(kExampleDeveloperId, registration.developer_id); + EXPECT_EQ(kExampleUniqueId, registration->unique_id); + EXPECT_EQ(kExampleDeveloperId, registration->developer_id); // Deactivating the registration should succeed. MarkRegistrationForDeletion(registration_id1, /* check_for_failure= */ true, @@ -1393,7 +1397,7 @@ auto registration = GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(registration.downloaded, 0u); + EXPECT_EQ(registration->downloaded, 0u); scoped_refptr<BackgroundFetchRequestInfo> request_info; PopNextRequest(registration_id, &error, &request_info); @@ -1405,7 +1409,7 @@ registration = GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(registration.downloaded, kResponseFileSize); + EXPECT_EQ(registration->downloaded, kResponseFileSize); PopNextRequest(registration_id, &error, &request_info); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); @@ -1416,7 +1420,7 @@ registration = GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); - EXPECT_EQ(registration.downloaded, 2 * kResponseFileSize); + EXPECT_EQ(registration->downloaded, 2 * kResponseFileSize); PopNextRequest(registration_id, &error, &request_info); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); @@ -1428,7 +1432,7 @@ registration = GetRegistration(sw_id, origin(), kExampleDeveloperId, &error); ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); // |registration.downloaded| is unchanged. - EXPECT_EQ(registration.downloaded, 2 * kResponseFileSize); + EXPECT_EQ(registration->downloaded, 2 * kResponseFileSize); } TEST_F(BackgroundFetchDataManagerTest, ExceedingQuotaIsReported) { @@ -1929,8 +1933,8 @@ const BackgroundFetchInitializationData& init = data[0]; EXPECT_EQ(init.registration_id, registration_id); - EXPECT_EQ(init.registration.unique_id, kExampleUniqueId); - EXPECT_EQ(init.registration.developer_id, kExampleDeveloperId); + EXPECT_EQ(init.registration->unique_id, kExampleUniqueId); + EXPECT_EQ(init.registration->developer_id, kExampleDeveloperId); EXPECT_EQ(init.options->title, kInitialTitle); EXPECT_EQ(init.options->download_total, 42u); EXPECT_EQ(init.ui_title, kInitialTitle);
diff --git a/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc b/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc index 78f2d783..001c282 100644 --- a/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc +++ b/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.cc
@@ -19,9 +19,9 @@ ~BackgroundFetchEmbeddedWorkerTestHelper() = default; void BackgroundFetchEmbeddedWorkerTestHelper::OnBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchAbortEventCallback callback) { - last_registration_ = registration; + last_registration_ = std::move(registration); if (fail_abort_event_) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::REJECTED); @@ -34,9 +34,9 @@ } void BackgroundFetchEmbeddedWorkerTestHelper::OnBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchClickEventCallback callback) { - last_registration_ = registration; + last_registration_ = std::move(registration); if (fail_click_event_) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::REJECTED); @@ -49,9 +49,9 @@ } void BackgroundFetchEmbeddedWorkerTestHelper::OnBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchFailEventCallback callback) { - last_registration_ = registration; + last_registration_ = std::move(registration); if (fail_fetch_fail_event_) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::REJECTED); @@ -64,10 +64,10 @@ } void BackgroundFetchEmbeddedWorkerTestHelper::OnBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchSuccessEventCallback callback) { - last_registration_ = registration; + last_registration_ = std::move(registration); if (fail_fetched_event_) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::REJECTED);
diff --git a/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.h b/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.h index 9836bd9..80def252 100644 --- a/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.h +++ b/content/browser/background_fetch/background_fetch_embedded_worker_test_helper.h
@@ -44,26 +44,27 @@ fetched_event_closure_ = closure; } - const base::Optional<BackgroundFetchRegistration>& last_registration() const { + const blink::mojom::BackgroundFetchRegistrationPtr& last_registration() + const { return last_registration_; } protected: // EmbeddedWorkerTestHelper overrides: void OnBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchAbortEventCallback callback) override; void OnBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchClickEventCallback callback) override; void OnBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchFailEventCallback callback) override; void OnBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchSuccessEventCallback callback) override; @@ -78,7 +79,7 @@ base::Closure fetch_fail_event_closure_; base::Closure fetched_event_closure_; - base::Optional<BackgroundFetchRegistration> last_registration_; + blink::mojom::BackgroundFetchRegistrationPtr last_registration_; DISALLOW_COPY_AND_ASSIGN(BackgroundFetchEmbeddedWorkerTestHelper); };
diff --git a/content/browser/background_fetch/background_fetch_event_dispatcher.cc b/content/browser/background_fetch/background_fetch_event_dispatcher.cc index 87765c9..7f03df1a3 100644 --- a/content/browser/background_fetch/background_fetch_event_dispatcher.cc +++ b/content/browser/background_fetch/background_fetch_event_dispatcher.cc
@@ -77,7 +77,7 @@ void BackgroundFetchEventDispatcher::DispatchBackgroundFetchCompletionEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure) { switch (registration->failure_reason) { case blink::mojom::BackgroundFetchFailureReason::NONE: @@ -112,7 +112,7 @@ void BackgroundFetchEventDispatcher::DispatchBackgroundFetchAbortEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure) { DCHECK_CURRENTLY_ON(BrowserThread::IO); LoadServiceWorkerRegistrationForDispatch( @@ -124,19 +124,19 @@ } void BackgroundFetchEventDispatcher::DoDispatchBackgroundFetchAbortEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id) { DCHECK(service_worker_version); DCHECK(registration); service_worker_version->endpoint()->DispatchBackgroundFetchAbortEvent( - *registration, + std::move(registration), service_worker_version->CreateSimpleEventCallback(request_id)); } void BackgroundFetchEventDispatcher::DispatchBackgroundFetchClickEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure) { DCHECK_CURRENTLY_ON(BrowserThread::IO); LoadServiceWorkerRegistrationForDispatch( @@ -148,19 +148,19 @@ } void BackgroundFetchEventDispatcher::DoDispatchBackgroundFetchClickEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id) { DCHECK(service_worker_version); DCHECK(registration); service_worker_version->endpoint()->DispatchBackgroundFetchClickEvent( - *registration, + std::move(registration), service_worker_version->CreateSimpleEventCallback(request_id)); } void BackgroundFetchEventDispatcher::DispatchBackgroundFetchFailEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure) { DCHECK_CURRENTLY_ON(BrowserThread::IO); LoadServiceWorkerRegistrationForDispatch( @@ -172,19 +172,19 @@ } void BackgroundFetchEventDispatcher::DoDispatchBackgroundFetchFailEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id) { DCHECK(service_worker_version); DCHECK(registration); service_worker_version->endpoint()->DispatchBackgroundFetchFailEvent( - *registration, + std::move(registration), service_worker_version->CreateSimpleEventCallback(request_id)); } void BackgroundFetchEventDispatcher::DispatchBackgroundFetchSuccessEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure) { DCHECK_CURRENTLY_ON(BrowserThread::IO); LoadServiceWorkerRegistrationForDispatch( @@ -198,13 +198,13 @@ } void BackgroundFetchEventDispatcher::DoDispatchBackgroundFetchSuccessEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id) { DCHECK(service_worker_version); DCHECK(registration); service_worker_version->endpoint()->DispatchBackgroundFetchSuccessEvent( - *registration, + std::move(registration), service_worker_version->CreateSimpleEventCallback(request_id)); }
diff --git a/content/browser/background_fetch/background_fetch_event_dispatcher.h b/content/browser/background_fetch/background_fetch_event_dispatcher.h index 8e7ba89..65c2223 100644 --- a/content/browser/background_fetch/background_fetch_event_dispatcher.h +++ b/content/browser/background_fetch/background_fetch_event_dispatcher.h
@@ -44,14 +44,14 @@ // provided registration. void DispatchBackgroundFetchCompletionEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure); // Dispatches the `backgroundfetchclick` event, which indicates that the user // interface displayed for an active background fetch was activated. void DispatchBackgroundFetchClickEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure); private: @@ -62,21 +62,21 @@ // background fetch was aborted by the user or another external event. void DispatchBackgroundFetchAbortEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure); // Dispatches the `backgroundfetchfail` event, which indicates that a // background fetch has finished with one or more failed fetches. void DispatchBackgroundFetchFailEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure); // Dispatches the `backgroundfetchsuccess` event, which indicates that a // background fetch has successfully completed. void DispatchBackgroundFetchSuccessEvent( const BackgroundFetchRegistrationId& registration_id, - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, base::OnceClosure finished_closure); // Phase at which the dispatching process finished. Used for UMA. @@ -119,19 +119,19 @@ // Methods that actually invoke the event on an activated Service Worker. static void DoDispatchBackgroundFetchAbortEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id); static void DoDispatchBackgroundFetchClickEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id); static void DoDispatchBackgroundFetchFailEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id); static void DoDispatchBackgroundFetchSuccessEvent( - std::unique_ptr<BackgroundFetchRegistration> registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, scoped_refptr<ServiceWorkerVersion> service_worker_version, int request_id);
diff --git a/content/browser/background_fetch/background_fetch_event_dispatcher_unittest.cc b/content/browser/background_fetch/background_fetch_event_dispatcher_unittest.cc index efe53279..866cbae 100644 --- a/content/browser/background_fetch/background_fetch_event_dispatcher_unittest.cc +++ b/content/browser/background_fetch/background_fetch_event_dispatcher_unittest.cc
@@ -87,7 +87,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, embedded_worker_test_helper()->last_registration()->developer_id); EXPECT_EQ(kExampleUniqueId, @@ -118,7 +118,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId2, embedded_worker_test_helper()->last_registration()->developer_id); EXPECT_EQ(kExampleUniqueId2, @@ -156,7 +156,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, embedded_worker_test_helper()->last_registration()->developer_id); EXPECT_EQ(blink::mojom::BackgroundFetchResult::UNSET, @@ -185,7 +185,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId2, embedded_worker_test_helper()->last_registration()->developer_id); EXPECT_EQ(blink::mojom::BackgroundFetchResult::FAILURE, @@ -223,7 +223,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, embedded_worker_test_helper()->last_registration()->developer_id); @@ -249,7 +249,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId2, embedded_worker_test_helper()->last_registration()->developer_id); @@ -285,7 +285,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, embedded_worker_test_helper()->last_registration()->developer_id); @@ -315,7 +315,7 @@ run_loop.Run(); } - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId2, embedded_worker_test_helper()->last_registration()->developer_id); EXPECT_EQ(kExampleUniqueId2,
diff --git a/content/browser/background_fetch/background_fetch_job_controller.cc b/content/browser/background_fetch/background_fetch_job_controller.cc index 67db41d..e4e6548 100644 --- a/content/browser/background_fetch/background_fetch_job_controller.cc +++ b/content/browser/background_fetch/background_fetch_job_controller.cc
@@ -192,9 +192,9 @@ std::move(active_request_finished_callback_).Run(request); } -std::unique_ptr<BackgroundFetchRegistration> +blink::mojom::BackgroundFetchRegistrationPtr BackgroundFetchJobController::NewRegistration() const { - return std::make_unique<BackgroundFetchRegistration>( + return blink::mojom::BackgroundFetchRegistration::New( registration_id().developer_id(), registration_id().unique_id(), 0 /* upload_total */, 0 /* uploaded */, options_->download_total, complete_requests_downloaded_bytes_cache_,
diff --git a/content/browser/background_fetch/background_fetch_job_controller.h b/content/browser/background_fetch/background_fetch_job_controller.h index 22e335c..79e74b6 100644 --- a/content/browser/background_fetch/background_fetch_job_controller.h +++ b/content/browser/background_fetch/background_fetch_job_controller.h
@@ -46,8 +46,8 @@ base::OnceCallback<void(const BackgroundFetchRegistrationId&, blink::mojom::BackgroundFetchFailureReason, ErrorCallback)>; - using ProgressCallback = - base::RepeatingCallback<void(const BackgroundFetchRegistration&)>; + using ProgressCallback = base::RepeatingCallback<void( + const blink::mojom::BackgroundFetchRegistration&)>; using RequestFinishedCallback = base::OnceCallback<void(scoped_refptr<BackgroundFetchRequestInfo>)>; @@ -75,9 +75,9 @@ // Gets the number of bytes downloaded for jobs that are currently running. uint64_t GetInProgressDownloadedBytes(); - // Returns a unique_ptr to a BackgroundFetchRegistration object + // Returns a blink::mojom::BackgroundFetchRegistrationPtr object // created with member fields. - std::unique_ptr<BackgroundFetchRegistration> NewRegistration() const; + blink::mojom::BackgroundFetchRegistrationPtr NewRegistration() const; const BackgroundFetchRegistrationId& registration_id() const { return registration_id_;
diff --git a/content/browser/background_fetch/background_fetch_job_controller_unittest.cc b/content/browser/background_fetch/background_fetch_job_controller_unittest.cc index 15aa568..115bb4b 100644 --- a/content/browser/background_fetch/background_fetch_job_controller_unittest.cc +++ b/content/browser/background_fetch/background_fetch_job_controller_unittest.cc
@@ -212,7 +212,8 @@ BackgroundFetchScheduler* scheduler() { return context_->scheduler_.get(); } private: - void DidUpdateProgress(const BackgroundFetchRegistration& registration) { + void DidUpdateProgress( + const blink::mojom::BackgroundFetchRegistration& registration) { last_downloaded_ = registration.downloaded; if (job_progress_closure_)
diff --git a/content/browser/background_fetch/background_fetch_registration_notifier.cc b/content/browser/background_fetch/background_fetch_registration_notifier.cc index e5dfc98..41c7897b 100644 --- a/content/browser/background_fetch/background_fetch_registration_notifier.cc +++ b/content/browser/background_fetch/background_fetch_registration_notifier.cc
@@ -29,7 +29,7 @@ } void BackgroundFetchRegistrationNotifier::Notify( - const BackgroundFetchRegistration& registration) { + const blink::mojom::BackgroundFetchRegistration& registration) { auto range = observers_.equal_range(registration.unique_id); for (auto it = range.first; it != range.second; ++it) { // TODO(crbug.com/774054): Uploads are not yet supported.
diff --git a/content/browser/background_fetch/background_fetch_registration_notifier.h b/content/browser/background_fetch/background_fetch_registration_notifier.h index 06324735..359ff9e 100644 --- a/content/browser/background_fetch/background_fetch_registration_notifier.h +++ b/content/browser/background_fetch/background_fetch_registration_notifier.h
@@ -17,8 +17,9 @@ namespace content { -// Tracks the live BackgroundFetchRegistration objects across the renderer -// processes and provides the functionality to notify them of progress updates. +// Tracks the live BackgroundFetchRegistration objects across the +// renderer processes and provides the functionality to notify them of progress +// updates. class CONTENT_EXPORT BackgroundFetchRegistrationNotifier { public: BackgroundFetchRegistrationNotifier(); @@ -33,7 +34,7 @@ // Notifies any registered observers for the |registration| of the progress. // This will cause JavaScript events to fire. // Completed fetches must also call Notify with the final state. - void Notify(const BackgroundFetchRegistration& registration); + void Notify(const blink::mojom::BackgroundFetchRegistration& registration); // Notifies any registered observers for the registration identifier by // |unique_id| that the records for the fetch are no longer available.
diff --git a/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc b/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc index cd9eee1..60c5596 100644 --- a/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc +++ b/content/browser/background_fetch/background_fetch_registration_notifier_unittest.cc
@@ -106,8 +106,8 @@ // Notifies all observers for the |unique_id| of the made progress, and waits // until the task runner managing the Mojo connection has finished. - void Notify(const BackgroundFetchRegistration& registration) { - notifier_->Notify(registration); + void Notify(blink::mojom::BackgroundFetchRegistrationPtr registration) { + notifier_->Notify(*registration); task_runner_->RunUntilIdle(); } @@ -132,7 +132,7 @@ notifier_->AddObserver(kPrimaryUniqueId, observer->GetPtr()); ASSERT_EQ(observer->progress_updates().size(), 0u); - Notify(BackgroundFetchRegistration( + Notify(blink::mojom::BackgroundFetchRegistration::New( kDeveloperId, kPrimaryUniqueId, /* upload_total*/ 0, /* uploaded*/ 0, kDownloadTotal, kDownloaded, blink::mojom::BackgroundFetchResult::UNSET, @@ -168,7 +168,7 @@ ASSERT_EQ(secondary_observer->progress_updates().size(), 0u); // Notify the |kPrimaryUniqueId|. - Notify(BackgroundFetchRegistration( + Notify(blink::mojom::BackgroundFetchRegistration::New( kDeveloperId, kPrimaryUniqueId, /* upload_total*/ 0, /* uploaded*/ 0, kDownloadTotal, kDownloaded, blink::mojom::BackgroundFetchResult::UNSET, @@ -199,7 +199,7 @@ notifier_->AddObserver(kPrimaryUniqueId, observer->GetPtr()); ASSERT_EQ(observer->progress_updates().size(), 0u); - Notify(BackgroundFetchRegistration( + Notify(blink::mojom::BackgroundFetchRegistration::New( kDeveloperId, kPrimaryUniqueId, /* upload_total*/ 0, /* uploaded*/ 0, kDownloadTotal, kDownloaded, blink::mojom::BackgroundFetchResult::UNSET, @@ -210,7 +210,7 @@ // Closes the binding as would be done from the renderer process. observer->Close(); - Notify(BackgroundFetchRegistration( + Notify(blink::mojom::BackgroundFetchRegistration::New( kDeveloperId, kPrimaryUniqueId, /* upload_total*/ 0, /* uploaded*/ 0, kDownloadTotal, kDownloaded, blink::mojom::BackgroundFetchResult::UNSET, @@ -227,7 +227,7 @@ notifier_->AddObserver(kPrimaryUniqueId, observer->GetPtr()); ASSERT_EQ(observer->progress_updates().size(), 0u); - Notify(BackgroundFetchRegistration( + Notify(blink::mojom::BackgroundFetchRegistration::New( kDeveloperId, kSecondaryUniqueId, /* upload_total*/ 0, /* uploaded*/ 0, kDownloadTotal, kDownloaded, blink::mojom::BackgroundFetchResult::UNSET,
diff --git a/content/browser/background_fetch/background_fetch_scheduler.cc b/content/browser/background_fetch/background_fetch_scheduler.cc index 8deecd0..53dc8b7 100644 --- a/content/browser/background_fetch/background_fetch_scheduler.cc +++ b/content/browser/background_fetch/background_fetch_scheduler.cc
@@ -124,7 +124,8 @@ auto it = completed_fetches_.find(registration_id.unique_id()); DCHECK(it != completed_fetches_.end()); - BackgroundFetchRegistration* registration = it->second.second.get(); + blink::mojom::BackgroundFetchRegistrationPtr& registration = + it->second.second; // Include any other failure reasons the marking for deletion may have found. if (registration->failure_reason == BackgroundFetchFailureReason::NONE) registration->failure_reason = failure_reason; @@ -137,8 +138,7 @@ registration_notifier_->Notify(*registration); event_dispatcher_.DispatchBackgroundFetchCompletionEvent( - registration_id, - std::make_unique<BackgroundFetchRegistration>(*registration), + registration_id, registration.Clone(), base::BindOnce(&BackgroundFetchScheduler::CleanupRegistration, weak_ptr_factory_.GetWeakPtr(), registration_id)); @@ -193,7 +193,7 @@ std::unique_ptr<BackgroundFetchJobController> BackgroundFetchScheduler::CreateInitializedController( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_completed_requests, @@ -220,7 +220,7 @@ void BackgroundFetchScheduler::OnRegistrationCreated( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_requests, @@ -240,7 +240,7 @@ void BackgroundFetchScheduler::OnRegistrationLoadedAtStartup( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_completed_requests, @@ -306,7 +306,7 @@ } void BackgroundFetchScheduler::OnRegistrationQueried( - BackgroundFetchRegistration* registration) { + blink::mojom::BackgroundFetchRegistration* registration) { DCHECK(registration); if (!active_controller_) return;
diff --git a/content/browser/background_fetch/background_fetch_scheduler.h b/content/browser/background_fetch/background_fetch_scheduler.h index a13304c..2ae250f 100644 --- a/content/browser/background_fetch/background_fetch_scheduler.h +++ b/content/browser/background_fetch/background_fetch_scheduler.h
@@ -53,14 +53,14 @@ // BackgroundFetchDataManagerObserver implementation. void OnRegistrationCreated( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_requests, bool start_paused) override; void OnRegistrationLoadedAtStartup( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_completed_requests, @@ -70,7 +70,7 @@ void OnServiceWorkerDatabaseCorrupted( int64_t service_worker_registration_id) override; void OnRegistrationQueried( - BackgroundFetchRegistration* registration) override; + blink::mojom::BackgroundFetchRegistration* registration) override; // ServiceWorkerContextCoreObserver implementation. void OnRegistrationDeleted(int64_t registration_id, @@ -90,7 +90,7 @@ std::unique_ptr<BackgroundFetchJobController> CreateInitializedController( const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, + const blink::mojom::BackgroundFetchRegistration& registration, blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, int num_completed_requests, @@ -141,7 +141,7 @@ // TODO(crbug.com/857122): Clean this up when the UI is no longer showing. std::map<std::string, std::pair<BackgroundFetchRegistrationId, - std::unique_ptr<BackgroundFetchRegistration>>> + blink::mojom::BackgroundFetchRegistrationPtr>> completed_fetches_; base::WeakPtrFactory<BackgroundFetchScheduler> weak_ptr_factory_;
diff --git a/content/browser/background_fetch/background_fetch_service_impl.cc b/content/browser/background_fetch/background_fetch_service_impl.cc index e62c2bc..932e251 100644 --- a/content/browser/background_fetch/background_fetch_service_impl.cc +++ b/content/browser/background_fetch/background_fetch_service_impl.cc
@@ -115,7 +115,7 @@ if (!ValidateDeveloperId(developer_id) || !ValidateRequests(requests)) { std::move(callback).Run( blink::mojom::BackgroundFetchError::INVALID_ARGUMENT, - base::nullopt /* registration */); + nullptr /* registration */); return; } @@ -207,7 +207,7 @@ if (!ValidateDeveloperId(developer_id)) { std::move(callback).Run( blink::mojom::BackgroundFetchError::INVALID_ARGUMENT, - base::nullopt /* registration */); + nullptr /* registration */); return; }
diff --git a/content/browser/background_fetch/background_fetch_service_unittest.cc b/content/browser/background_fetch/background_fetch_service_unittest.cc index 56be553..44b3dc6 100644 --- a/content/browser/background_fetch/background_fetch_service_unittest.cc +++ b/content/browser/background_fetch/background_fetch_service_unittest.cc
@@ -132,7 +132,7 @@ blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, blink::mojom::BackgroundFetchError* out_error, - BackgroundFetchRegistration* out_registration) { + blink::mojom::BackgroundFetchRegistration* out_registration) { DCHECK(out_error); DCHECK(out_registration); @@ -184,7 +184,7 @@ blink::mojom::BackgroundFetchOptionsPtr options, const SkBitmap& icon, blink::mojom::BackgroundFetchError* out_error, - BackgroundFetchRegistration* out_registration) { + blink::mojom::BackgroundFetchRegistration* out_registration) { DCHECK(out_error); DCHECK(out_registration); @@ -252,10 +252,11 @@ } // Synchronous wrapper for BackgroundFetchServiceImpl::GetRegistration(). - void GetRegistration(int64_t service_worker_registration_id, - const std::string& developer_id, - blink::mojom::BackgroundFetchError* out_error, - BackgroundFetchRegistration* out_registration) { + void GetRegistration( + int64_t service_worker_registration_id, + const std::string& developer_id, + blink::mojom::BackgroundFetchError* out_error, + blink::mojom::BackgroundFetchRegistration* out_registration) { DCHECK(out_error); DCHECK(out_registration); @@ -320,24 +321,26 @@ } // BackgroundFetchDataManagerObserver implementation & mocks: - MOCK_METHOD6(OnRegistrationCreated, - void(const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, - blink::mojom::BackgroundFetchOptionsPtr options, - const SkBitmap& icon, - int num_requests, - bool start_paused)); - MOCK_METHOD7(OnRegistrationLoadedAtStartup, - void(const BackgroundFetchRegistrationId& registration_id, - const BackgroundFetchRegistration& registration, - blink::mojom::BackgroundFetchOptionsPtr options, - const SkBitmap& icon, - int num_completed_requests, - int num_requests, - std::vector<scoped_refptr<BackgroundFetchRequestInfo>> - active_fetch_requests)); + MOCK_METHOD6( + OnRegistrationCreated, + void(const BackgroundFetchRegistrationId& registration_id, + const blink::mojom::BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchOptionsPtr options, + const SkBitmap& icon, + int num_requests, + bool start_paused)); + MOCK_METHOD7( + OnRegistrationLoadedAtStartup, + void(const BackgroundFetchRegistrationId& registration_id, + const blink::mojom::BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchOptionsPtr options, + const SkBitmap& icon, + int num_completed_requests, + int num_requests, + std::vector<scoped_refptr<BackgroundFetchRequestInfo>> + active_fetch_requests)); MOCK_METHOD1(OnRegistrationQueried, - void(BackgroundFetchRegistration* registration)); + void(blink::mojom::BackgroundFetchRegistration* registration)); MOCK_METHOD1(OnServiceWorkerDatabaseCorrupted, void(int64_t service_worker_registration_id)); @@ -359,20 +362,21 @@ void DidGetRegistration( base::OnceClosure quit_closure, blink::mojom::BackgroundFetchError* out_error, - BackgroundFetchRegistration* out_registration, + blink::mojom::BackgroundFetchRegistration* out_registration, blink::mojom::BackgroundFetchError error, - const base::Optional<content::BackgroundFetchRegistration>& - registration) { + blink::mojom::BackgroundFetchRegistrationPtr registration) { *out_error = error; - *out_registration = - registration ? registration.value() : BackgroundFetchRegistration(); + *out_registration = registration + ? *registration + : blink::mojom::BackgroundFetchRegistration(); std::move(quit_closure).Run(); } - void DidStartFetch(base::OnceClosure quit_closure, - blink::mojom::BackgroundFetchError error, - const BackgroundFetchRegistration& registration) { + void DidStartFetch( + base::OnceClosure quit_closure, + blink::mojom::BackgroundFetchError error, + blink::mojom::BackgroundFetchRegistrationPtr registration) { ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); std::move(quit_closure).Run(); } @@ -422,7 +426,7 @@ requests.push_back(CreateDefaultRequest()); blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; Fetch(42 /* service_worker_registration_id */, "" /* developer_id */, std::move(requests), options.Clone(), SkBitmap(), &error, @@ -438,7 +442,7 @@ // |requests| has deliberately been left empty. blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; Fetch(42 /* service_worker_registration_id */, kExampleDeveloperId, std::move(requests), std::move(options), SkBitmap(), &error, @@ -450,8 +454,9 @@ TEST_F(BackgroundFetchServiceTest, FetchRegistrationProperties) { // This test starts a new Background Fetch and verifies that the returned - // BackgroundFetchRegistration object matches the given options. Then gets the - // active Background Fetch with the same |developer_id|, and verifies that. + // blink::mojom::BackgroundFetchRegistration object matches the given options. + // Then gets the active Background Fetch with the same |developer_id|, and + // verifies that. int64_t service_worker_registration_id = RegisterServiceWorker(); ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId, @@ -469,7 +474,7 @@ options->download_total = 9001; blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; Fetch(service_worker_registration_id, kExampleDeveloperId, std::move(requests), options.Clone(), SkBitmap(), &error, @@ -482,7 +487,7 @@ EXPECT_EQ(registration.download_total, options->download_total); blink::mojom::BackgroundFetchError second_error; - BackgroundFetchRegistration second_registration; + blink::mojom::BackgroundFetchRegistration second_registration; GetRegistration(service_worker_registration_id, kExampleDeveloperId, &second_error, &second_registration); @@ -509,7 +514,7 @@ auto options = blink::mojom::BackgroundFetchOptions::New(); blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; // Create the first registration. This must succeed. Fetch(service_worker_registration_id, kExampleDeveloperId, @@ -518,7 +523,7 @@ ASSERT_EQ(error, blink::mojom::BackgroundFetchError::NONE); blink::mojom::BackgroundFetchError second_error; - BackgroundFetchRegistration second_registration; + blink::mojom::BackgroundFetchRegistration second_registration; // Create the second registration with the same data. This must fail. Fetch(service_worker_registration_id, kExampleDeveloperId, @@ -576,7 +581,7 @@ .Build())); // Create the registration with the given |requests|. - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; { auto options = blink::mojom::BackgroundFetchOptions::New(); blink::mojom::BackgroundFetchError error; @@ -591,7 +596,7 @@ // Spin the |event_dispatched_loop| to wait for the dispatched event. event_dispatched_loop.Run(); - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, registration.developer_id); // Get all the settled fetches and test properties. @@ -681,7 +686,7 @@ .Build())); // Create the registration with the given |requests|. - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; { auto options = blink::mojom::BackgroundFetchOptions::New(); @@ -698,7 +703,7 @@ // Spin the |event_dispatched_loop| to wait for the dispatched event. event_dispatched_loop.Run(); - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, registration.developer_id); // Get all the settled fetches and test properties. @@ -762,7 +767,7 @@ options->title = "1st title"; blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; // Create the registration. BackgroundFetchRegistrationId registration_id = Fetch( @@ -778,7 +783,7 @@ second_title, &error); EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error); - BackgroundFetchRegistration second_registration; + blink::mojom::BackgroundFetchRegistration second_registration; // GetRegistration should now resolve with the updated title. GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error, @@ -800,7 +805,7 @@ auto options = blink::mojom::BackgroundFetchOptions::New(); blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; // Create the registration. This must succeed. BackgroundFetchRegistrationId registration_id = Fetch( @@ -819,7 +824,7 @@ base::RunLoop().RunUntilIdle(); blink::mojom::BackgroundFetchError second_error; - BackgroundFetchRegistration second_registration; + blink::mojom::BackgroundFetchRegistration second_registration; // Now try to get the created registration, which is expected to fail. GetRegistration(service_worker_registration_id, kExampleDeveloperId, @@ -896,7 +901,7 @@ auto options = blink::mojom::BackgroundFetchOptions::New(); blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; // Create the registration. This must succeed. registration_id = Fetch(service_worker_registration_id, kExampleDeveloperId, @@ -917,7 +922,7 @@ event_dispatched_loop.Run(); - ASSERT_TRUE(embedded_worker_test_helper()->last_registration().has_value()); + ASSERT_TRUE(embedded_worker_test_helper()->last_registration()); EXPECT_EQ(kExampleDeveloperId, embedded_worker_test_helper()->last_registration()->developer_id); } @@ -927,9 +932,9 @@ // registration, according to the registration's |unique_id|, rather than // keying off the |developer_id| provided by JavaScript, since multiple // registrations can share an |developer_id| if JavaScript holds a reference - // to a BackgroundFetchRegistration object after that registration is - // completed/failed/aborted and then creates a new registration with the same - // |developer_id|. + // to a blink::mojom::BackgroundFetchRegistration object after that + // registration is completed/failed/aborted and then creates a new + // registration with the same |developer_id|. int64_t service_worker_registration_id = RegisterServiceWorker(); ASSERT_NE(blink::mojom::kInvalidServiceWorkerRegistrationId, @@ -943,7 +948,7 @@ // Create the first registration, that we will soon abort. auto aborted_options = blink::mojom::BackgroundFetchOptions::New(); aborted_options->title = "Aborted"; - BackgroundFetchRegistration aborted_registration; + blink::mojom::BackgroundFetchRegistration aborted_registration; BackgroundFetchRegistrationId aborted_registration_id = Fetch(service_worker_registration_id, kExampleDeveloperId, CloneRequestVector(requests), std::move(aborted_options), @@ -963,7 +968,7 @@ // succeed. auto second_options = blink::mojom::BackgroundFetchOptions::New(); second_options->title = "Second"; - BackgroundFetchRegistration second_registration; + blink::mojom::BackgroundFetchRegistration second_registration; BackgroundFetchRegistrationId second_registration_id = Fetch( service_worker_registration_id, kExampleDeveloperId, std::move(requests), std::move(second_options), SkBitmap(), &error, &second_registration); @@ -971,7 +976,7 @@ // Now try to get the registration using its |developer_id|. This should // return the second registration since that is the active one. - BackgroundFetchRegistration gotten_registration; + blink::mojom::BackgroundFetchRegistration gotten_registration; GetRegistration(service_worker_registration_id, kExampleDeveloperId, &error, &gotten_registration); EXPECT_EQ(blink::mojom::BackgroundFetchError::NONE, error); @@ -1053,7 +1058,7 @@ // Start the Background Fetch for the |registration_id|. { blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; Fetch(service_worker_registration_id, kExampleDeveloperId, CloneRequestVector(requests), options.Clone(), SkBitmap(), &error, @@ -1076,7 +1081,7 @@ // Start the Background Fetch for the |second_registration_id|. { blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; Fetch(service_worker_registration_id, kAlternativeDeveloperId, std::move(requests), std::move(options), SkBitmap(), &error, @@ -1156,7 +1161,7 @@ options->download_total = 9001; blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; { using blink::mojom::BackgroundFetchError; @@ -1183,7 +1188,7 @@ requests.push_back(CreateDefaultRequest()); auto options = blink::mojom::BackgroundFetchOptions::New(); blink::mojom::BackgroundFetchError error; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistration registration; // Start the fetch. The request is indefinitley pending so this will never // finish.
diff --git a/content/browser/background_fetch/background_fetch_test_base.cc b/content/browser/background_fetch/background_fetch_test_base.cc index eae5a761..8826be7 100644 --- a/content/browser/background_fetch/background_fetch_test_base.cc +++ b/content/browser/background_fetch/background_fetch_test_base.cc
@@ -175,16 +175,15 @@ return request; } -std::unique_ptr<BackgroundFetchRegistration> +blink::mojom::BackgroundFetchRegistrationPtr BackgroundFetchTestBase::CreateBackgroundFetchRegistration( const std::string& developer_id, const std::string& unique_id, blink::mojom::BackgroundFetchResult result, blink::mojom::BackgroundFetchFailureReason failure_reason) { - auto registration = std::make_unique<BackgroundFetchRegistration>( + return blink::mojom::BackgroundFetchRegistration::New( developer_id, unique_id, 0 /* upload_total */, 0 /* uploaded */, 0 /* download_total */, 0 /* downloaded */, result, failure_reason); - return registration; } } // namespace content
diff --git a/content/browser/background_fetch/background_fetch_test_base.h b/content/browser/background_fetch/background_fetch_test_base.h index b1717c3..7d25437 100644 --- a/content/browser/background_fetch/background_fetch_test_base.h +++ b/content/browser/background_fetch/background_fetch_test_base.h
@@ -56,8 +56,8 @@ const GURL& url, std::unique_ptr<TestResponse> response); - // Creates a BackgroundFetchRegistration object. - std::unique_ptr<BackgroundFetchRegistration> + // Creates a blink::mojom::BackgroundFetchRegistrationPtr object. + blink::mojom::BackgroundFetchRegistrationPtr CreateBackgroundFetchRegistration( const std::string& developer_id, const std::string& unique_id,
diff --git a/content/browser/background_fetch/storage/create_metadata_task.cc b/content/browser/background_fetch/storage/create_metadata_task.cc index 6028d2cf..3c84e1de 100644 --- a/content/browser/background_fetch/storage/create_metadata_task.cc +++ b/content/browser/background_fetch/storage/create_metadata_task.cc
@@ -409,13 +409,13 @@ void CreateMetadataTask::FinishWithError( blink::mojom::BackgroundFetchError error) { - BackgroundFetchRegistration registration; + auto registration = blink::mojom::BackgroundFetchRegistration::New(); if (error == blink::mojom::BackgroundFetchError::NONE) { DCHECK(metadata_proto_); bool converted = - ToBackgroundFetchRegistration(*metadata_proto_, ®istration); + ToBackgroundFetchRegistration(*metadata_proto_, registration.get()); if (!converted) { // Database corrupted. SetStorageErrorAndFinish( @@ -424,7 +424,7 @@ } for (auto& observer : data_manager()->observers()) { - observer.OnRegistrationCreated(registration_id_, registration, + observer.OnRegistrationCreated(registration_id_, *registration, options_.Clone(), icon_, requests_.size(), start_paused_); } @@ -432,7 +432,7 @@ ReportStorageError(); - std::move(callback_).Run(error, registration); + std::move(callback_).Run(error, std::move(registration)); Finished(); // Destroys |this|. }
diff --git a/content/browser/background_fetch/storage/create_metadata_task.h b/content/browser/background_fetch/storage/create_metadata_task.h index 6bc2abc..e8a4201 100644 --- a/content/browser/background_fetch/storage/create_metadata_task.h +++ b/content/browser/background_fetch/storage/create_metadata_task.h
@@ -18,8 +18,6 @@ namespace content { -struct BackgroundFetchRegistration; - namespace background_fetch { // Checks if the registration can be created, then writes the Background @@ -28,7 +26,7 @@ public: using CreateMetadataCallback = base::OnceCallback<void(blink::mojom::BackgroundFetchError, - const BackgroundFetchRegistration&)>; + blink::mojom::BackgroundFetchRegistrationPtr)>; CreateMetadataTask(DatabaseTaskHost* host, const BackgroundFetchRegistrationId& registration_id,
diff --git a/content/browser/background_fetch/storage/database_helpers.cc b/content/browser/background_fetch/storage/database_helpers.cc index caac11b..c29f8e9 100644 --- a/content/browser/background_fetch/storage/database_helpers.cc +++ b/content/browser/background_fetch/storage/database_helpers.cc
@@ -91,7 +91,7 @@ bool ToBackgroundFetchRegistration( const proto::BackgroundFetchMetadata& metadata_proto, - BackgroundFetchRegistration* registration) { + blink::mojom::BackgroundFetchRegistration* registration) { DCHECK(registration); const auto& registration_proto = metadata_proto.registration();
diff --git a/content/browser/background_fetch/storage/database_helpers.h b/content/browser/background_fetch/storage/database_helpers.h index 82ea96e..668d5f22 100644 --- a/content/browser/background_fetch/storage/database_helpers.h +++ b/content/browser/background_fetch/storage/database_helpers.h
@@ -62,7 +62,7 @@ // Converts the |metadata_proto| to a BackgroundFetchRegistration object. bool ToBackgroundFetchRegistration( const proto::BackgroundFetchMetadata& metadata_proto, - BackgroundFetchRegistration* registration); + blink::mojom::BackgroundFetchRegistration* registration); bool MojoFailureReasonFromRegistrationProto( proto::BackgroundFetchRegistration_BackgroundFetchFailureReason
diff --git a/content/browser/background_fetch/storage/get_initialization_data_task.cc b/content/browser/background_fetch/storage/get_initialization_data_task.cc index fc53c57..dd36725 100644 --- a/content/browser/background_fetch/storage/get_initialization_data_task.cc +++ b/content/browser/background_fetch/storage/get_initialization_data_task.cc
@@ -337,7 +337,7 @@ // Fill BackgroundFetchRegistration. auto& registration = sub_task_init().initialization_data->registration; - ToBackgroundFetchRegistration(metadata, ®istration); + ToBackgroundFetchRegistration(metadata, registration.get()); // Total number of requests. sub_task_init().initialization_data->num_requests = metadata.num_fetches();
diff --git a/content/browser/background_fetch/storage/get_initialization_data_task.h b/content/browser/background_fetch/storage/get_initialization_data_task.h index 2709014..53530d66 100644 --- a/content/browser/background_fetch/storage/get_initialization_data_task.h +++ b/content/browser/background_fetch/storage/get_initialization_data_task.h
@@ -37,7 +37,8 @@ blink::mojom::BackgroundFetchOptionsPtr options = blink::mojom::BackgroundFetchOptions::New(); SkBitmap icon; - BackgroundFetchRegistration registration; + blink::mojom::BackgroundFetchRegistrationPtr registration = + blink::mojom::BackgroundFetchRegistration::New(); size_t num_requests; size_t num_completed_requests; std::vector<scoped_refptr<BackgroundFetchRequestInfo>> active_fetch_requests;
diff --git a/content/browser/background_fetch/storage/get_registration_task.cc b/content/browser/background_fetch/storage/get_registration_task.cc index d5e9c45..aa7c562f 100644 --- a/content/browser/background_fetch/storage/get_registration_task.cc +++ b/content/browser/background_fetch/storage/get_registration_task.cc
@@ -44,13 +44,13 @@ void GetRegistrationTask::FinishWithError( blink::mojom::BackgroundFetchError error) { - BackgroundFetchRegistration registration; + auto registration = blink::mojom::BackgroundFetchRegistration::New(); if (error == blink::mojom::BackgroundFetchError::NONE) { DCHECK(metadata_proto_); bool converted = - ToBackgroundFetchRegistration(*metadata_proto_, ®istration); + ToBackgroundFetchRegistration(*metadata_proto_, registration.get()); if (!converted) { // Database corrupted. SetStorageErrorAndFinish( @@ -61,7 +61,7 @@ ReportStorageError(); - std::move(callback_).Run(error, registration); + std::move(callback_).Run(error, std::move(registration)); Finished(); // Destroys |this|. }
diff --git a/content/browser/background_fetch/storage/get_registration_task.h b/content/browser/background_fetch/storage/get_registration_task.h index 908b8568..df057c8d 100644 --- a/content/browser/background_fetch/storage/get_registration_task.h +++ b/content/browser/background_fetch/storage/get_registration_task.h
@@ -26,7 +26,7 @@ public: using GetRegistrationCallback = base::OnceCallback<void(blink::mojom::BackgroundFetchError, - const BackgroundFetchRegistration&)>; + blink::mojom::BackgroundFetchRegistrationPtr)>; GetRegistrationTask(DatabaseTaskHost* host, int64_t service_worker_registration_id,
diff --git a/content/browser/media/midi_host.cc b/content/browser/media/midi_host.cc index 058ea90..138349915 100644 --- a/content/browser/media/midi_host.cc +++ b/content/browser/media/midi_host.cc
@@ -37,8 +37,8 @@ using midi::IsDataByte; using midi::IsSystemRealTimeMessage; using midi::IsValidWebMIDIData; -using midi::kSysExByte; using midi::kEndOfSysExByte; +using midi::kSysExByte; using midi::mojom::PortState; using midi::mojom::Result; @@ -188,9 +188,8 @@ { base::AutoLock auto_lock(output_port_count_lock_); if (output_port_count_ <= port) { - bad_message::ReceivedBadMessage( - RenderProcessHost::FromID(renderer_process_id_), - bad_message::MH_INVALID_MIDI_PORT); + bad_message::ReceivedBadMessage(renderer_process_id_, + bad_message::MH_INVALID_MIDI_PORT); return; } } @@ -202,9 +201,8 @@ // in JavaScript. The actual permission check for security purposes // happens here in the browser process. if (!has_sys_ex_permission_ && base::ContainsValue(data, kSysExByte)) { - bad_message::ReceivedBadMessage( - RenderProcessHost::FromID(renderer_process_id_), - bad_message::MH_SYS_EX_PERMISSION); + bad_message::ReceivedBadMessage(renderer_process_id_, + bad_message::MH_SYS_EX_PERMISSION); return; }
diff --git a/content/browser/picture_in_picture/OWNERS b/content/browser/picture_in_picture/OWNERS index 645933b..b234e09 100644 --- a/content/browser/picture_in_picture/OWNERS +++ b/content/browser/picture_in_picture/OWNERS
@@ -1,4 +1,3 @@ -apacible@chromium.org -mlamouri@chromium.org +file://third_party/blink/renderer/modules/picture_in_picture/OWNERS # COMPONENT: Internals>Media>UI
diff --git a/content/browser/service_worker/embedded_worker_test_helper.cc b/content/browser/service_worker/embedded_worker_test_helper.cc index f14b7d8..e5bc2cc 100644 --- a/content/browser/service_worker/embedded_worker_test_helper.cc +++ b/content/browser/service_worker/embedded_worker_test_helper.cc
@@ -212,35 +212,38 @@ } void DispatchBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchAbortEventCallback callback) override { if (!helper_) return; - helper_->OnBackgroundFetchAbortEventStub(registration, std::move(callback)); + helper_->OnBackgroundFetchAbortEventStub(std::move(registration), + std::move(callback)); } void DispatchBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchClickEventCallback callback) override { if (!helper_) return; - helper_->OnBackgroundFetchClickEventStub(registration, std::move(callback)); + helper_->OnBackgroundFetchClickEventStub(std::move(registration), + std::move(callback)); } void DispatchBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchFailEventCallback callback) override { if (!helper_) return; - helper_->OnBackgroundFetchFailEventStub(registration, std::move(callback)); + helper_->OnBackgroundFetchFailEventStub(std::move(registration), + std::move(callback)); } void DispatchBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchSuccessEventCallback callback) override { if (!helper_) return; - helper_->OnBackgroundFetchSuccessEventStub(registration, + helper_->OnBackgroundFetchSuccessEventStub(std::move(registration), std::move(callback)); } @@ -584,25 +587,25 @@ } void EmbeddedWorkerTestHelper::OnBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchAbortEventCallback callback) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED); } void EmbeddedWorkerTestHelper::OnBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchClickEventCallback callback) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED); } void EmbeddedWorkerTestHelper::OnBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchFailEventCallback callback) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED); } void EmbeddedWorkerTestHelper::OnBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchSuccessEventCallback callback) { std::move(callback).Run(blink::mojom::ServiceWorkerEventStatus::COMPLETED); @@ -852,40 +855,44 @@ } void EmbeddedWorkerTestHelper::OnBackgroundFetchAbortEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchAbortEventCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&EmbeddedWorkerTestHelper::OnBackgroundFetchAbortEvent, - AsWeakPtr(), registration, std::move(callback))); + AsWeakPtr(), std::move(registration), + std::move(callback))); } void EmbeddedWorkerTestHelper::OnBackgroundFetchClickEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchClickEventCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&EmbeddedWorkerTestHelper::OnBackgroundFetchClickEvent, - AsWeakPtr(), registration, std::move(callback))); + AsWeakPtr(), std::move(registration), + std::move(callback))); } void EmbeddedWorkerTestHelper::OnBackgroundFetchFailEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchFailEventCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&EmbeddedWorkerTestHelper::OnBackgroundFetchFailEvent, - AsWeakPtr(), registration, std::move(callback))); + AsWeakPtr(), std::move(registration), + std::move(callback))); } void EmbeddedWorkerTestHelper::OnBackgroundFetchSuccessEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchSuccessEventCallback callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&EmbeddedWorkerTestHelper::OnBackgroundFetchSuccessEvent, - AsWeakPtr(), registration, std::move(callback))); + AsWeakPtr(), std::move(registration), + std::move(callback))); } void EmbeddedWorkerTestHelper::OnCookieChangeEventStub(
diff --git a/content/browser/service_worker/embedded_worker_test_helper.h b/content/browser/service_worker/embedded_worker_test_helper.h index 902a084..cd98877 100644 --- a/content/browser/service_worker/embedded_worker_test_helper.h +++ b/content/browser/service_worker/embedded_worker_test_helper.h
@@ -39,7 +39,6 @@ namespace content { -struct BackgroundFetchRegistration; class EmbeddedWorkerRegistry; class EmbeddedWorkerTestHelper; class MockRenderProcessHost; @@ -175,16 +174,16 @@ virtual void OnActivateEvent( mojom::ServiceWorker::DispatchActivateEventCallback callback); virtual void OnBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchAbortEventCallback callback); virtual void OnBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchClickEventCallback callback); virtual void OnBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchFailEventCallback callback); virtual void OnBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchSuccessEventCallback callback); virtual void OnCookieChangeEvent( @@ -269,16 +268,16 @@ void OnActivateEventStub( mojom::ServiceWorker::DispatchActivateEventCallback callback); void OnBackgroundFetchAbortEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchAbortEventCallback callback); void OnBackgroundFetchClickEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchClickEventCallback callback); void OnBackgroundFetchFailEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchFailEventCallback callback); void OnBackgroundFetchSuccessEventStub( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, mojom::ServiceWorker::DispatchBackgroundFetchSuccessEventCallback callback); void OnCookieChangeEventStub(
diff --git a/content/browser/webui/url_data_manager_backend.cc b/content/browser/webui/url_data_manager_backend.cc index 9df2980..032f547 100644 --- a/content/browser/webui/url_data_manager_backend.cc +++ b/content/browser/webui/url_data_manager_backend.cc
@@ -271,6 +271,12 @@ TRACE_EVENT_ASYNC_END0("browser", "DataManager:Request", this); DCHECK(!data_); + if (!bytes) { + NotifyStartError( + net::URLRequestStatus(net::URLRequestStatus::FAILED, net::ERR_FAILED)); + return; + } + if (bytes) set_expected_content_size(bytes->size());
diff --git a/content/browser/webui/url_data_manager_backend_unittest.cc b/content/browser/webui/url_data_manager_backend_unittest.cc index 87333d19..f898d9d 100644 --- a/content/browser/webui/url_data_manager_backend_unittest.cc +++ b/content/browser/webui/url_data_manager_backend_unittest.cc
@@ -59,9 +59,8 @@ const char* origin) { std::unique_ptr<net::URLRequest> request = url_request_context_.CreateRequest( - GURL( - "chrome://resources/polymer/v1_0/polymer/polymer-extracted.js"), - net::HIGHEST, delegate, TRAFFIC_ANNOTATION_FOR_TESTS); + GURL("chrome://resources/css/text_defaults.css"), net::HIGHEST, + delegate, TRAFFIC_ANNOTATION_FOR_TESTS); request->SetExtraRequestHeaderByName("Origin", origin, true); return request; }
diff --git a/content/common/background_fetch/background_fetch_struct_traits.cc b/content/common/background_fetch/background_fetch_struct_traits.cc index e3b3884e..995e33af 100644 --- a/content/common/background_fetch/background_fetch_struct_traits.cc +++ b/content/common/background_fetch/background_fetch_struct_traits.cc
@@ -12,25 +12,6 @@ namespace mojo { // static -bool StructTraits<blink::mojom::BackgroundFetchRegistrationDataView, - content::BackgroundFetchRegistration>:: - Read(blink::mojom::BackgroundFetchRegistrationDataView data, - content::BackgroundFetchRegistration* registration) { - if (!data.ReadDeveloperId(®istration->developer_id) || - !data.ReadUniqueId(®istration->unique_id)) { - return false; - } - - registration->upload_total = data.upload_total(); - registration->uploaded = data.uploaded(); - registration->download_total = data.download_total(); - registration->downloaded = data.downloaded(); - registration->result = data.result(); - registration->failure_reason = data.failure_reason(); - return true; -} - -// static bool StructTraits<blink::mojom::BackgroundFetchSettledFetchDataView, content::BackgroundFetchSettledFetch>:: Read(blink::mojom::BackgroundFetchSettledFetchDataView data,
diff --git a/content/common/background_fetch/background_fetch_struct_traits.h b/content/common/background_fetch/background_fetch_struct_traits.h index a338045e..d2da967d 100644 --- a/content/common/background_fetch/background_fetch_struct_traits.h +++ b/content/common/background_fetch/background_fetch_struct_traits.h
@@ -18,47 +18,6 @@ template <> struct CONTENT_EXPORT - StructTraits<blink::mojom::BackgroundFetchRegistrationDataView, - content::BackgroundFetchRegistration> { - static const std::string& developer_id( - const content::BackgroundFetchRegistration& registration) { - return registration.developer_id; - } - static const std::string& unique_id( - const content::BackgroundFetchRegistration& registration) { - return registration.unique_id; - } - static uint64_t upload_total( - const content::BackgroundFetchRegistration& registration) { - return registration.upload_total; - } - static uint64_t uploaded( - const content::BackgroundFetchRegistration& registration) { - return registration.uploaded; - } - static uint64_t download_total( - const content::BackgroundFetchRegistration& registration) { - return registration.download_total; - } - static uint64_t downloaded( - const content::BackgroundFetchRegistration& registration) { - return registration.downloaded; - } - static blink::mojom::BackgroundFetchResult result( - const content::BackgroundFetchRegistration& registration) { - return registration.result; - } - static blink::mojom::BackgroundFetchFailureReason failure_reason( - const content::BackgroundFetchRegistration& registration) { - return registration.failure_reason; - } - - static bool Read(blink::mojom::BackgroundFetchRegistrationDataView data, - content::BackgroundFetchRegistration* registration); -}; - -template <> -struct CONTENT_EXPORT StructTraits<blink::mojom::BackgroundFetchSettledFetchDataView, content::BackgroundFetchSettledFetch> { static blink::mojom::FetchAPIRequestPtr request(
diff --git a/content/common/background_fetch/background_fetch_struct_traits_unittest.cc b/content/common/background_fetch/background_fetch_struct_traits_unittest.cc index daae458..86224e6 100644 --- a/content/common/background_fetch/background_fetch_struct_traits_unittest.cc +++ b/content/common/background_fetch/background_fetch_struct_traits_unittest.cc
@@ -34,28 +34,6 @@ } // namespace -TEST(BackgroundFetchStructTraitsTest, BackgroundFetchRegistrationRoundTrip) { - BackgroundFetchRegistration registration; - registration.developer_id = "my_id"; - registration.unique_id = "7e57ab1e-c0de-a150-ca75-1e75f005ba11"; - registration.download_total = 9001; - registration.result = blink::mojom::BackgroundFetchResult::FAILURE; - registration.failure_reason = - blink::mojom::BackgroundFetchFailureReason::CANCELLED_FROM_UI; - - BackgroundFetchRegistration roundtrip_registration; - ASSERT_TRUE(blink::mojom::BackgroundFetchRegistration::Deserialize( - blink::mojom::BackgroundFetchRegistration::Serialize(®istration), - &roundtrip_registration)); - - EXPECT_EQ(roundtrip_registration.developer_id, registration.developer_id); - EXPECT_EQ(roundtrip_registration.unique_id, registration.unique_id); - - EXPECT_EQ(roundtrip_registration.download_total, registration.download_total); - EXPECT_EQ(roundtrip_registration.result, registration.result); - EXPECT_EQ(roundtrip_registration.failure_reason, registration.failure_reason); -} - TEST(BackgroundFetchStructTraitsTest, ImageResourceRoundtrip) { blink::Manifest::ImageResource icon = CreateIcon("my_icon.png", {{256, 256}}, "image/png");
diff --git a/content/common/background_fetch/background_fetch_types.cc b/content/common/background_fetch/background_fetch_types.cc index dabcfbf..3e2f3f5 100644 --- a/content/common/background_fetch/background_fetch_types.cc +++ b/content/common/background_fetch/background_fetch_types.cc
@@ -21,33 +21,6 @@ namespace content { -BackgroundFetchRegistration::BackgroundFetchRegistration() - : result(blink::mojom::BackgroundFetchResult::UNSET), - failure_reason(blink::mojom::BackgroundFetchFailureReason::NONE) {} - -BackgroundFetchRegistration::BackgroundFetchRegistration( - const std::string& developer_id, - const std::string& unique_id, - uint64_t upload_total, - uint64_t uploaded, - uint64_t download_total, - uint64_t downloaded, - blink::mojom::BackgroundFetchResult result, - blink::mojom::BackgroundFetchFailureReason failure_reason) - : developer_id(developer_id), - unique_id(unique_id), - upload_total(upload_total), - uploaded(uploaded), - download_total(download_total), - downloaded(downloaded), - result(result), - failure_reason(failure_reason) {} - -BackgroundFetchRegistration::BackgroundFetchRegistration( - const BackgroundFetchRegistration& other) = default; - -BackgroundFetchRegistration::~BackgroundFetchRegistration() = default; - // static blink::mojom::FetchAPIResponsePtr BackgroundFetchSettledFetch::CloneResponse( const blink::mojom::FetchAPIResponsePtr& response) {
diff --git a/content/common/background_fetch/background_fetch_types.h b/content/common/background_fetch/background_fetch_types.h index f4a50407..0e4751c7 100644 --- a/content/common/background_fetch/background_fetch_types.h +++ b/content/common/background_fetch/background_fetch_types.h
@@ -14,48 +14,8 @@ #include "third_party/blink/public/common/manifest/manifest.h" #include "third_party/blink/public/mojom/fetch/fetch_api_response.mojom.h" -namespace blink { -namespace mojom { -enum class BackgroundFetchFailureReason; -enum class BackgroundFetchResult; -} // namespace mojom -} // namespace blink - namespace content { -// Represents the information associated with a Background Fetch registration. -// Analogous to the following structure in the spec: -// https://wicg.github.io/background-fetch/#background-fetch-registration -struct CONTENT_EXPORT BackgroundFetchRegistration { - BackgroundFetchRegistration(); - BackgroundFetchRegistration( - const std::string& developer_id, - const std::string& unique_id, - uint64_t upload_total, - uint64_t uploaded, - uint64_t download_total, - uint64_t downloaded, - blink::mojom::BackgroundFetchResult result, - blink::mojom::BackgroundFetchFailureReason failure_reason); - BackgroundFetchRegistration(const BackgroundFetchRegistration& other); - ~BackgroundFetchRegistration(); - - // Corresponds to IDL 'id' attribute. Not unique - an active registration can - // have the same |developer_id| as one or more inactive registrations. - std::string developer_id; - // Globally unique ID for the registration, generated in content/. Used to - // distinguish registrations in case a developer re-uses |developer_id|s. Not - // exposed to JavaScript. - std::string unique_id; - - uint64_t upload_total = 0; - uint64_t uploaded = 0; - uint64_t download_total = 0; - uint64_t downloaded = 0; - blink::mojom::BackgroundFetchResult result; - blink::mojom::BackgroundFetchFailureReason failure_reason; -}; - // Represents a request/response pair for a settled Background Fetch fetch. // Analogous to the following structure in the spec: // http://wicg.github.io/background-fetch/#backgroundfetchsettledfetch
diff --git a/content/common/background_fetch/background_fetch_types.typemap b/content/common/background_fetch/background_fetch_types.typemap index 018b20fa..03dd348 100644 --- a/content/common/background_fetch/background_fetch_types.typemap +++ b/content/common/background_fetch/background_fetch_types.typemap
@@ -11,7 +11,4 @@ "//mojo/public/cpp/bindings", "//third_party/blink/public:blink_headers", ] -type_mappings = [ - "blink.mojom.BackgroundFetchRegistration=content::BackgroundFetchRegistration", - "blink.mojom.BackgroundFetchSettledFetch=::content::BackgroundFetchSettledFetch", -] +type_mappings = [ "blink.mojom.BackgroundFetchSettledFetch=::content::BackgroundFetchSettledFetch" ]
diff --git a/content/common/content_security_policy/csp_source.cc b/content/common/content_security_policy/csp_source.cc index 9ada01e..2c8d142 100644 --- a/content/common/content_security_policy/csp_source.cc +++ b/content/common/content_security_policy/csp_source.cc
@@ -16,7 +16,9 @@ bool DecodePath(const base::StringPiece& path, std::string* output) { url::RawCanonOutputT<base::char16> unescaped; - url::DecodeURLEscapeSequences(path.data(), path.size(), &unescaped); + url::DecodeURLEscapeSequences(path.data(), path.size(), + url::DecodeURLMode::kUTF8OrIsomorphic, + &unescaped); return base::UTF16ToUTF8(unescaped.data(), unescaped.length(), output); }
diff --git a/content/renderer/BUILD.gn b/content/renderer/BUILD.gn index c8d520e..850362d 100644 --- a/content/renderer/BUILD.gn +++ b/content/renderer/BUILD.gn
@@ -113,18 +113,10 @@ "frame_blame_context.h", "frame_owner_properties.cc", "frame_owner_properties.h", - "gpu/compositor_dependencies.h", - "gpu/frame_swap_message_queue.cc", - "gpu/frame_swap_message_queue.h", - "gpu/gpu_benchmarking_extension.cc", - "gpu/gpu_benchmarking_extension.h", - "gpu/layer_tree_view.cc", - "gpu/layer_tree_view.h", - "gpu/layer_tree_view_delegate.h", - "gpu/queue_message_swap_promise.cc", - "gpu/queue_message_swap_promise.h", - "gpu/stream_texture_host_android.cc", - "gpu/stream_texture_host_android.h", + "frame_swap_message_queue.cc", + "frame_swap_message_queue.h", + "gpu_benchmarking_extension.cc", + "gpu_benchmarking_extension.h", "history_entry.cc", "history_entry.h", "history_serialization.cc", @@ -489,6 +481,8 @@ "push_messaging/push_messaging_client.h", "push_messaging/push_provider.cc", "push_messaging/push_provider.h", + "queue_message_swap_promise.cc", + "queue_message_swap_promise.h", "render_frame_impl.cc", "render_frame_impl.h", "render_frame_metadata_observer_impl.cc", @@ -568,6 +562,8 @@ "stats_collection_controller.h", "storage_util.cc", "storage_util.h", + "stream_texture_host_android.cc", + "stream_texture_host_android.h", "text_input_client_observer.cc", "text_input_client_observer.h", "theme_helper_mac.h", @@ -635,6 +631,7 @@ "//content/public/common:buildflags", "//content/public/common:feature_h264_with_openh264_ffmpeg", "//content/public/common:service_names", + "//content/renderer/compositor", "//crypto", "//crypto:platform", "//device/base/synchronization",
diff --git a/content/renderer/DEPS b/content/renderer/DEPS index 8dca146..c6c43f5 100644 --- a/content/renderer/DEPS +++ b/content/renderer/DEPS
@@ -45,4 +45,7 @@ "renderer_main\.cc": [ "+ui/ozone/public/client_native_pixmap_factory_ozone.h", ], + ".*_(unit|pixel|perf)test.*\.cc": [ + "+components/viz/test", + ], }
diff --git a/content/renderer/android/synchronous_layer_tree_frame_sink.cc b/content/renderer/android/synchronous_layer_tree_frame_sink.cc index ea5e963..9f4413b 100644 --- a/content/renderer/android/synchronous_layer_tree_frame_sink.cc +++ b/content/renderer/android/synchronous_layer_tree_frame_sink.cc
@@ -28,7 +28,7 @@ #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" #include "content/common/view_messages.h" #include "content/renderer/android/synchronous_compositor_registry.h" -#include "content/renderer/gpu/frame_swap_message_queue.h" +#include "content/renderer/frame_swap_message_queue.h" #include "content/renderer/render_thread_impl.h" #include "gpu/command_buffer/client/context_support.h" #include "gpu/command_buffer/client/gles2_interface.h"
diff --git a/content/renderer/compositor/BUILD.gn b/content/renderer/compositor/BUILD.gn new file mode 100644 index 0000000..1b9f79b --- /dev/null +++ b/content/renderer/compositor/BUILD.gn
@@ -0,0 +1,22 @@ +# Copyright 2018 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/jumbo.gni") + +static_library("compositor") { + deps = [ + "//base", + "//cc", + "//cc/animation", + "//third_party/blink/public:blink_headers", + "//ui/gfx", + ] + + sources = [ + "compositor_dependencies.h", + "layer_tree_view.cc", + "layer_tree_view.h", + "layer_tree_view_delegate.h", + ] +}
diff --git a/content/renderer/compositor/DEPS b/content/renderer/compositor/DEPS new file mode 100644 index 0000000..7f7d1b37 --- /dev/null +++ b/content/renderer/compositor/DEPS
@@ -0,0 +1,12 @@ +include_rules = [ + "-content", + "+content/renderer/compositor", + "+components/viz/common", +] + +specific_include_rules = { + '.*_unittest\.cc': [ + "+components/viz/test", + "+content/test", + ] +}
diff --git a/content/renderer/gpu/OWNERS b/content/renderer/compositor/OWNERS similarity index 100% rename from content/renderer/gpu/OWNERS rename to content/renderer/compositor/OWNERS
diff --git a/content/renderer/gpu/compositor_dependencies.h b/content/renderer/compositor/compositor_dependencies.h similarity index 87% rename from content/renderer/gpu/compositor_dependencies.h rename to content/renderer/compositor/compositor_dependencies.h index 74da8435..2b014ecd 100644 --- a/content/renderer/gpu/compositor_dependencies.h +++ b/content/renderer/compositor/compositor_dependencies.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_COMPOSITOR_DEPENDENCIES_H_ -#define CONTENT_RENDERER_GPU_COMPOSITOR_DEPENDENCIES_H_ +#ifndef CONTENT_RENDERER_COMPOSITOR_COMPOSITOR_DEPENDENCIES_H_ +#define CONTENT_RENDERER_COMPOSITOR_COMPOSITOR_DEPENDENCIES_H_ #include <memory> #include <vector> @@ -18,13 +18,13 @@ namespace cc { class TaskGraphRunner; class UkmRecorderFactory; -} +} // namespace cc namespace blink { namespace scheduler { class WebThreadScheduler; } -} +} // namespace blink namespace content { @@ -59,4 +59,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_COMPOSITOR_DEPENDENCIES_H_ +#endif // CONTENT_RENDERER_COMPOSITOR_COMPOSITOR_DEPENDENCIES_H_
diff --git a/content/renderer/gpu/layer_tree_view.cc b/content/renderer/compositor/layer_tree_view.cc similarity index 99% rename from content/renderer/gpu/layer_tree_view.cc rename to content/renderer/compositor/layer_tree_view.cc index dff7678..0994118 100644 --- a/content/renderer/gpu/layer_tree_view.cc +++ b/content/renderer/compositor/layer_tree_view.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include <stddef.h> #include <string> @@ -39,7 +39,7 @@ #include "components/viz/common/frame_sinks/copy_output_result.h" #include "components/viz/common/quads/compositor_frame_metadata.h" #include "components/viz/common/resources/single_release_callback.h" -#include "content/renderer/gpu/layer_tree_view_delegate.h" +#include "content/renderer/compositor/layer_tree_view_delegate.h" #include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h" #include "third_party/blink/public/platform/web_runtime_features.h" #include "third_party/blink/public/platform/web_size.h"
diff --git a/content/renderer/gpu/layer_tree_view.h b/content/renderer/compositor/layer_tree_view.h similarity index 96% rename from content/renderer/gpu/layer_tree_view.h rename to content/renderer/compositor/layer_tree_view.h index 4d4a038..aee5bfd3 100644 --- a/content/renderer/gpu/layer_tree_view.h +++ b/content/renderer/compositor/layer_tree_view.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_LAYER_TREE_VIEW_H_ -#define CONTENT_RENDERER_GPU_LAYER_TREE_VIEW_H_ +#ifndef CONTENT_RENDERER_COMPOSITOR_LAYER_TREE_VIEW_H_ +#define CONTENT_RENDERER_COMPOSITOR_LAYER_TREE_VIEW_H_ #include <stdint.h> @@ -18,7 +18,6 @@ #include "cc/trees/layer_tree_host_single_thread_client.h" #include "cc/trees/swap_promise.h" #include "cc/trees/swap_promise_monitor.h" -#include "content/common/content_export.h" #include "third_party/blink/public/platform/web_layer_tree_view.h" #include "ui/gfx/geometry/rect.h" @@ -46,7 +45,7 @@ namespace gfx { class ColorSpace; class Size; -} +} // namespace gfx namespace ui { class LatencyInfo; @@ -55,10 +54,9 @@ namespace content { class LayerTreeViewDelegate; -class CONTENT_EXPORT LayerTreeView - : public blink::WebLayerTreeView, - public cc::LayerTreeHostClient, - public cc::LayerTreeHostSingleThreadClient { +class LayerTreeView : public blink::WebLayerTreeView, + public cc::LayerTreeHostClient, + public cc::LayerTreeHostSingleThreadClient { public: // The |main_thread| is the task runner that the compositor will use for the // main thread (where it is constructed). The |compositor_thread| is the task @@ -265,4 +263,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_LAYER_TREE_VIEW_H_ +#endif // CONTENT_RENDERER_COMPOSITOR_LAYER_TREE_VIEW_H_
diff --git a/content/renderer/gpu/layer_tree_view_delegate.h b/content/renderer/compositor/layer_tree_view_delegate.h similarity index 93% rename from content/renderer/gpu/layer_tree_view_delegate.h rename to content/renderer/compositor/layer_tree_view_delegate.h index 4d8a2188..e6b2aea 100644 --- a/content/renderer/gpu/layer_tree_view_delegate.h +++ b/content/renderer/compositor/layer_tree_view_delegate.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_LAYER_TREE_VIEW_DELEGATE_H_ -#define CONTENT_RENDERER_GPU_LAYER_TREE_VIEW_DELEGATE_H_ +#ifndef CONTENT_RENDERER_COMPOSITOR_LAYER_TREE_VIEW_DELEGATE_H_ +#define CONTENT_RENDERER_COMPOSITOR_LAYER_TREE_VIEW_DELEGATE_H_ #include <memory> #include <vector> @@ -88,4 +88,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_LAYER_TREE_VIEW_DELEGATE_H_ +#endif // CONTENT_RENDERER_COMPOSITOR_LAYER_TREE_VIEW_DELEGATE_H_
diff --git a/content/renderer/gpu/layer_tree_view_unittest.cc b/content/renderer/compositor/layer_tree_view_unittest.cc similarity index 99% rename from content/renderer/gpu/layer_tree_view_unittest.cc rename to content/renderer/compositor/layer_tree_view_unittest.cc index 428b2e0..c65eb93c 100644 --- a/content/renderer/gpu/layer_tree_view_unittest.cc +++ b/content/renderer/compositor/layer_tree_view_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 "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include <utility>
diff --git a/content/renderer/gpu/frame_swap_message_queue.cc b/content/renderer/frame_swap_message_queue.cc similarity index 94% rename from content/renderer/gpu/frame_swap_message_queue.cc rename to content/renderer/frame_swap_message_queue.cc index f180368..be3ee2d1 100644 --- a/content/renderer/gpu/frame_swap_message_queue.cc +++ b/content/renderer/frame_swap_message_queue.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/gpu/frame_swap_message_queue.h" +#include "content/renderer/frame_swap_message_queue.h" #include <algorithm> #include <limits> @@ -82,13 +82,11 @@ } // namespace FrameSwapMessageQueue::FrameSwapMessageQueue(int32_t routing_id) - : visual_state_queue_(new VisualStateQueue()), - routing_id_(routing_id) { + : visual_state_queue_(new VisualStateQueue()), routing_id_(routing_id) { DETACH_FROM_THREAD(impl_thread_checker_); } -FrameSwapMessageQueue::~FrameSwapMessageQueue() { -} +FrameSwapMessageQueue::~FrameSwapMessageQueue() {} bool FrameSwapMessageQueue::Empty() const { base::AutoLock lock(lock_); @@ -110,8 +108,7 @@ &next_drain_messages_); } -void FrameSwapMessageQueue::DidSwap(int source_frame_number) { -} +void FrameSwapMessageQueue::DidSwap(int source_frame_number) {} void FrameSwapMessageQueue::DidNotSwap( int source_frame_number,
diff --git a/content/renderer/gpu/frame_swap_message_queue.h b/content/renderer/frame_swap_message_queue.h similarity index 95% rename from content/renderer/gpu/frame_swap_message_queue.h rename to content/renderer/frame_swap_message_queue.h index a1e1de85..9d0e3b3a 100644 --- a/content/renderer/gpu/frame_swap_message_queue.h +++ b/content/renderer/frame_swap_message_queue.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_FRAME_SWAP_MESSAGE_QUEUE_H_ -#define CONTENT_RENDERER_GPU_FRAME_SWAP_MESSAGE_QUEUE_H_ +#ifndef CONTENT_RENDERER_FRAME_SWAP_MESSAGE_QUEUE_H_ +#define CONTENT_RENDERER_FRAME_SWAP_MESSAGE_QUEUE_H_ #include <map> #include <memory> @@ -116,4 +116,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_FRAME_SWAP_MESSAGE_QUEUE_H_ +#endif // CONTENT_RENDERER_FRAME_SWAP_MESSAGE_QUEUE_H_
diff --git a/content/renderer/gpu/frame_swap_message_queue_unittest.cc b/content/renderer/frame_swap_message_queue_unittest.cc similarity index 97% rename from content/renderer/gpu/frame_swap_message_queue_unittest.cc rename to content/renderer/frame_swap_message_queue_unittest.cc index 7c3c95f7..0282e46 100644 --- a/content/renderer/gpu/frame_swap_message_queue_unittest.cc +++ b/content/renderer/frame_swap_message_queue_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 "content/renderer/gpu/frame_swap_message_queue.h" +#include "content/renderer/frame_swap_message_queue.h" #include <utility> @@ -101,8 +101,8 @@ QueueVisualStateMessage(1, CloneMessage(first_message_), &visual_state_first); ASSERT_TRUE(visual_state_first); // Queuing the second time should result in true. - QueueVisualStateMessage( - 1, CloneMessage(second_message_), &visual_state_first); + QueueVisualStateMessage(1, CloneMessage(second_message_), + &visual_state_first); ASSERT_FALSE(visual_state_first); // Queuing for a different frame should result in true. QueueVisualStateMessage(2, CloneMessage(first_message_), &visual_state_first); @@ -204,8 +204,7 @@ QueueNextSwapMessage(CloneMessage(first_message_)); QueueVisualStateMessage(2, CloneMessage(second_message_)); QueueVisualStateMessage(3, CloneMessage(third_message_)); - const int rid[] = {first_message_.routing_id(), - second_message_.routing_id(), + const int rid[] = {first_message_.routing_id(), second_message_.routing_id(), third_message_.routing_id()}; bool msg_delivered = reason != cc::SwapPromise::COMMIT_FAILS &&
diff --git a/content/renderer/gpu/DEPS b/content/renderer/gpu/DEPS deleted file mode 100644 index 5673a9a..0000000 --- a/content/renderer/gpu/DEPS +++ /dev/null
@@ -1,5 +0,0 @@ -specific_include_rules = { - ".*_(unit|pixel|perf)test.*\.cc": [ - "+components/viz/test", - ], -}
diff --git a/content/renderer/gpu/gpu_benchmarking_extension.cc b/content/renderer/gpu_benchmarking_extension.cc similarity index 96% rename from content/renderer/gpu/gpu_benchmarking_extension.cc rename to content/renderer/gpu_benchmarking_extension.cc index 23235a33..0d64cb8 100644 --- a/content/renderer/gpu/gpu_benchmarking_extension.cc +++ b/content/renderer/gpu_benchmarking_extension.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/gpu/gpu_benchmarking_extension.h" +#include "content/renderer/gpu_benchmarking_extension.h" #include <stddef.h> @@ -18,6 +18,7 @@ #include "base/files/file_util.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" +#include "build/build_config.h" #include "cc/layers/layer.h" #include "cc/paint/skia_paint_canvas.h" #include "cc/trees/layer_tree_host.h" @@ -33,7 +34,7 @@ #include "content/public/renderer/chrome_object_extensions_utils.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/v8_value_converter.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/render_thread_impl.h" #include "content/renderer/render_view_impl.h" #include "content/renderer/skia_benchmarking_extension.h" @@ -72,8 +73,8 @@ #include <wrl/client.h> #endif -using blink::WebLocalFrame; using blink::WebImageCache; +using blink::WebLocalFrame; using blink::WebPrivatePtr; using blink::WebSize; using blink::WebView; @@ -84,8 +85,7 @@ class SkPictureSerializer { public: explicit SkPictureSerializer(const base::FilePath& dirpath) - : dirpath_(dirpath), - layer_id_(0) { + : dirpath_(dirpath), layer_id_(0) { // Let skia register known effect subclasses. This basically enables // reflection on those subclasses required for picture serialization. SkiaBenchmarking::Initialize(); @@ -160,9 +160,7 @@ context_.Reset(isolate_, context); } - v8::Isolate* isolate() { - return isolate_; - } + v8::Isolate* isolate() { return isolate_; } v8::Local<v8::Function> GetCallback() { return v8::Local<v8::Function>::New(isolate_, callback_); @@ -258,7 +256,7 @@ if (frame) { v8::Local<v8::Value> value = V8ValueConverter::Create()->ToV8Value(result.get(), context); - v8::Local<v8::Value> argv[] = { value }; + v8::Local<v8::Value> argv[] = {value}; frame->CallFunctionEvenIfScriptDisabled(callback_and_context->GetCallback(), v8::Object::New(isolate), 1, argv); @@ -515,16 +513,15 @@ if (controller.IsEmpty()) return; - v8::Local<v8::Object> chrome = GetOrCreateChromeObject(isolate, - context->Global()); + v8::Local<v8::Object> chrome = + GetOrCreateChromeObject(isolate, context->Global()); chrome->Set(gin::StringToV8(isolate, "gpuBenchmarking"), controller.ToV8()); } GpuBenchmarking::GpuBenchmarking(RenderFrameImpl* frame) : render_frame_(frame) {} -GpuBenchmarking::~GpuBenchmarking() { -} +GpuBenchmarking::~GpuBenchmarking() {} void GpuBenchmarking::EnsureRemoteInterface() { if (!input_injector_) { @@ -630,8 +627,7 @@ return; base::FilePath dirpath = base::FilePath::FromUTF8Unsafe(dirname); - if (!base::CreateDirectory(dirpath) || - !base::PathIsWritable(dirpath)) { + if (!base::CreateDirectory(dirpath) || !base::PathIsWritable(dirpath)) { std::string msg("Path is not writable: "); msg.append(dirpath.MaybeAsASCII()); isolate->ThrowException(v8::Exception::Error( @@ -713,10 +709,8 @@ int gesture_source_type = SyntheticGestureParams::DEFAULT_INPUT; float speed_in_pixels_s = 800; - if (!GetArg(args, &start_x) || - !GetArg(args, &start_y) || - !GetArg(args, &end_x) || - !GetArg(args, &end_y) || + if (!GetArg(args, &start_x) || !GetArg(args, &start_y) || + !GetArg(args, &end_x) || !GetArg(args, &end_y) || !GetOptionalArg(args, &callback) || !GetOptionalArg(args, &gesture_source_type) || !GetOptionalArg(args, &speed_in_pixels_s)) { @@ -791,8 +785,7 @@ !GetOptionalArg(args, &distance_length) || !GetOptionalArg(args, &overscroll_length) || !GetOptionalArg(args, &repeat_count) || - !GetOptionalArg(args, &callback) || - !GetOptionalArg(args, &start_x) || + !GetOptionalArg(args, &callback) || !GetOptionalArg(args, &start_x) || !GetOptionalArg(args, &start_y) || !GetOptionalArg(args, &speed_in_pixels_s)) { return false; @@ -986,10 +979,8 @@ int duration_ms = 50; int gesture_source_type = SyntheticGestureParams::DEFAULT_INPUT; - if (!GetArg(args, &position_x) || - !GetArg(args, &position_y) || - !GetOptionalArg(args, &callback) || - !GetOptionalArg(args, &duration_ms) || + if (!GetArg(args, &position_x) || !GetArg(args, &position_y) || + !GetOptionalArg(args, &callback) || !GetOptionalArg(args, &duration_ms) || !GetOptionalArg(args, &gesture_source_type)) { return false; } @@ -1147,8 +1138,7 @@ RenderThreadImpl::current()->GetGpuChannel(); if (!gpu_channel) return; - const gpu::GpuFeatureInfo& gpu_feature_info = - gpu_channel->gpu_feature_info(); + const gpu::GpuFeatureInfo& gpu_feature_info = gpu_channel->gpu_feature_info(); const std::vector<int32_t>& workarounds = gpu_feature_info.enabled_gpu_driver_bug_workarounds; for (int32_t workaround : workarounds) { @@ -1159,16 +1149,14 @@ // This code must be kept in sync with compositor_util's // GetDriverBugWorkaroundsImpl. - for (auto ext : base::SplitString(gpu_feature_info.disabled_extensions, - " ", - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY)) { + for (auto ext : + base::SplitString(gpu_feature_info.disabled_extensions, " ", + base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { gpu_driver_bug_workarounds.push_back("disabled_extension_" + ext); } - for (auto ext : base::SplitString(gpu_feature_info.disabled_webgl_extensions, - " ", - base::TRIM_WHITESPACE, - base::SPLIT_WANT_NONEMPTY)) { + for (auto ext : + base::SplitString(gpu_feature_info.disabled_webgl_extensions, " ", + base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { gpu_driver_bug_workarounds.push_back("disabled_webgl_extension_" + ext); }
diff --git a/content/renderer/gpu/gpu_benchmarking_extension.h b/content/renderer/gpu_benchmarking_extension.h similarity index 91% rename from content/renderer/gpu/gpu_benchmarking_extension.h rename to content/renderer/gpu_benchmarking_extension.h index b3a66a5..1384789 100644 --- a/content/renderer/gpu/gpu_benchmarking_extension.h +++ b/content/renderer/gpu_benchmarking_extension.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_GPU_BENCHMARKING_EXTENSION_H_ -#define CONTENT_RENDERER_GPU_GPU_BENCHMARKING_EXTENSION_H_ +#ifndef CONTENT_RENDERER_GPU_BENCHMARKING_EXTENSION_H_ +#define CONTENT_RENDERER_GPU_BENCHMARKING_EXTENSION_H_ #include "base/macros.h" #include "content/common/input/input_injector.mojom.h" @@ -16,7 +16,7 @@ namespace v8 { class Isolate; class Object; -} +} // namespace v8 namespace content { @@ -43,8 +43,7 @@ void PrintToSkPicture(v8::Isolate* isolate, const std::string& dirname); void PrintPagesToSkPictures(v8::Isolate* isolate, const std::string& filename); - void PrintPagesToXPS(v8::Isolate* isolate, - const std::string& filename); + void PrintPagesToXPS(v8::Isolate* isolate, const std::string& filename); bool GestureSourceTypeSupported(int gesture_source_type); // All arguments in these methods are in visual viewport coordinates. @@ -102,4 +101,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_GPU_BENCHMARKING_EXTENSION_H_ +#endif // CONTENT_RENDERER_GPU_BENCHMARKING_EXTENSION_H_
diff --git a/content/renderer/input/frame_input_handler_impl.cc b/content/renderer/input/frame_input_handler_impl.cc index 7f5b62cf..606a1fa 100644 --- a/content/renderer/input/frame_input_handler_impl.cc +++ b/content/renderer/input/frame_input_handler_impl.cc
@@ -10,7 +10,7 @@ #include "base/debug/stack_trace.h" #include "base/logging.h" #include "content/common/input/ime_text_span_conversions.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/input/widget_input_handler_manager.h" #include "content/renderer/render_thread_impl.h"
diff --git a/content/renderer/input/render_widget_input_handler.cc b/content/renderer/input/render_widget_input_handler.cc index d42599c24..50aef4fd 100644 --- a/content/renderer/input/render_widget_input_handler.cc +++ b/content/renderer/input/render_widget_input_handler.cc
@@ -19,7 +19,7 @@ #include "content/public/common/input_event_ack_state.h" #include "content/public/renderer/render_frame.h" #include "content/renderer/browser_plugin/browser_plugin.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/input/render_widget_input_handler_delegate.h" #include "content/renderer/render_frame_proxy.h"
diff --git a/content/renderer/input/widget_input_handler_impl.cc b/content/renderer/input/widget_input_handler_impl.cc index 2a25410b4..e1ac787a 100644 --- a/content/renderer/input/widget_input_handler_impl.cc +++ b/content/renderer/input/widget_input_handler_impl.cc
@@ -10,7 +10,7 @@ #include "base/logging.h" #include "content/common/input/ime_text_span_conversions.h" #include "content/common/input_messages.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/input/widget_input_handler_manager.h" #include "content/renderer/render_thread_impl.h"
diff --git a/content/renderer/input/widget_input_handler_manager.cc b/content/renderer/input/widget_input_handler_manager.cc index 67a2a5e..9b251a0 100644 --- a/content/renderer/input/widget_input_handler_manager.cc +++ b/content/renderer/input/widget_input_handler_manager.cc
@@ -9,7 +9,7 @@ #include "base/bind.h" #include "base/logging.h" #include "content/common/input_messages.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/input/widget_input_handler_impl.h" #include "content/renderer/render_thread_impl.h"
diff --git a/content/renderer/loader/shared_memory_data_consumer_handle.cc b/content/renderer/loader/shared_memory_data_consumer_handle.cc index ae994d2..970d0569 100644 --- a/content/renderer/loader/shared_memory_data_consumer_handle.cc +++ b/content/renderer/loader/shared_memory_data_consumer_handle.cc
@@ -53,12 +53,12 @@ class SharedMemoryDataConsumerHandle::Context final : public base::RefCountedThreadSafe<Context> { public: - explicit Context(const base::Closure& on_reader_detached) + explicit Context(base::OnceClosure on_reader_detached) : result_(kOk), first_offset_(0), client_(nullptr), writer_task_runner_(base::ThreadTaskRunnerHandle::Get()), - on_reader_detached_(on_reader_detached), + on_reader_detached_(std::move(on_reader_detached)), is_on_reader_detached_valid_(!on_reader_detached_.is_null()), is_handle_active_(true), is_two_phase_read_in_progress_(false) {} @@ -72,10 +72,12 @@ if (!is_handle_locked() && !is_handle_active()) { // No one is interested in the contents. if (is_on_reader_detached_valid_) { + is_on_reader_detached_valid_ = false; // We post a task even in the writer thread in order to avoid a // reentrance problem as calling |on_reader_detached_| may manipulate // the context synchronously. - writer_task_runner_->PostTask(FROM_HERE, on_reader_detached_); + writer_task_runner_->PostTask(FROM_HERE, + std::move(on_reader_detached_)); } Clear(); } @@ -251,7 +253,7 @@ Client* client_; scoped_refptr<base::SingleThreadTaskRunner> notification_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> writer_task_runner_; - base::Closure on_reader_detached_; + base::OnceClosure on_reader_detached_; // We need this boolean variable to remember if |on_reader_detached_| is // callable because we need to reset |on_reader_detached_| only on the writer // thread and hence |on_reader_detached_.is_null()| is untrustworthy on @@ -440,13 +442,13 @@ SharedMemoryDataConsumerHandle::SharedMemoryDataConsumerHandle( BackpressureMode mode, std::unique_ptr<Writer>* writer) - : SharedMemoryDataConsumerHandle(mode, base::Closure(), writer) {} + : SharedMemoryDataConsumerHandle(mode, base::OnceClosure(), writer) {} SharedMemoryDataConsumerHandle::SharedMemoryDataConsumerHandle( BackpressureMode mode, - const base::Closure& on_reader_detached, + base::OnceClosure on_reader_detached, std::unique_ptr<Writer>* writer) - : context_(new Context(on_reader_detached)) { + : context_(new Context(std::move(on_reader_detached))) { writer->reset(new Writer(context_, mode)); }
diff --git a/content/renderer/loader/shared_memory_data_consumer_handle.h b/content/renderer/loader/shared_memory_data_consumer_handle.h index 39a23dec5..5a4c901 100644 --- a/content/renderer/loader/shared_memory_data_consumer_handle.h +++ b/content/renderer/loader/shared_memory_data_consumer_handle.h
@@ -79,7 +79,7 @@ // context when the writer is detached, i.e. |Close| or |Fail| is called, // and the callback will never be called. SharedMemoryDataConsumerHandle(BackpressureMode mode, - const base::Closure& on_reader_detached, + base::OnceClosure on_reader_detached, std::unique_ptr<Writer>* writer); ~SharedMemoryDataConsumerHandle() override;
diff --git a/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc b/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc index 1792ae8b7..b4ab8f2 100644 --- a/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc +++ b/content/renderer/loader/shared_memory_data_consumer_handle_unittest.cc
@@ -657,7 +657,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( kApplyBackpressure, - base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); + base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_)); handle_.reset(); on_clear = nullptr; checkpoint.Call(1); @@ -683,7 +683,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( kApplyBackpressure, - base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); + base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_)); auto reader = handle_->ObtainReader( nullptr, blink::scheduler::GetSingleThreadTaskRunnerForTesting()); handle_.reset(); @@ -713,7 +713,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( kApplyBackpressure, - base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); + base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_)); on_clear = nullptr; checkpoint.Call(1); writer_->Close(); @@ -740,7 +740,7 @@ checkpoint.Call(0); handle_.reset(new SharedMemoryDataConsumerHandle( kApplyBackpressure, - base::Bind(&DestructionTrackingFunction::Call, on_clear), &writer_)); + base::BindOnce(&DestructionTrackingFunction::Call, on_clear), &writer_)); on_clear = nullptr; checkpoint.Call(1); writer_->Fail();
diff --git a/content/renderer/loader/web_url_loader_impl.cc b/content/renderer/loader/web_url_loader_impl.cc index e1070e88..763c774 100644 --- a/content/renderer/loader/web_url_loader_impl.cc +++ b/content/renderer/loader/web_url_loader_impl.cc
@@ -862,7 +862,7 @@ } auto read_handle = std::make_unique<SharedMemoryDataConsumerHandle>( - mode, base::Bind(&Context::CancelBodyStreaming, this), + mode, base::BindOnce(&Context::CancelBodyStreaming, this), &body_stream_writer_); // Here |body_stream_writer_| has an indirect reference to |this| and that
diff --git a/content/renderer/media/android/stream_texture_factory.h b/content/renderer/media/android/stream_texture_factory.h index 4a4359a..1f2c63a 100644 --- a/content/renderer/media/android/stream_texture_factory.h +++ b/content/renderer/media/android/stream_texture_factory.h
@@ -15,7 +15,7 @@ #include "base/unguessable_token.h" #include "cc/layers/video_frame_provider.h" #include "content/common/content_export.h" -#include "content/renderer/gpu/stream_texture_host_android.h" +#include "content/renderer/stream_texture_host_android.h" #include "gpu/command_buffer/common/mailbox.h" #include "ui/gfx/geometry/size.h"
diff --git a/content/renderer/gpu/queue_message_swap_promise.cc b/content/renderer/queue_message_swap_promise.cc similarity index 95% rename from content/renderer/gpu/queue_message_swap_promise.cc rename to content/renderer/queue_message_swap_promise.cc index 280bde5..0edbb7707 100644 --- a/content/renderer/gpu/queue_message_swap_promise.cc +++ b/content/renderer/queue_message_swap_promise.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/gpu/queue_message_swap_promise.h" +#include "content/renderer/queue_message_swap_promise.h" #include <memory> @@ -10,7 +10,7 @@ #include "content/common/widget_messages.h" #include "content/public/common/content_switches.h" #include "content/public/renderer/render_thread.h" -#include "content/renderer/gpu/frame_swap_message_queue.h" +#include "content/renderer/frame_swap_message_queue.h" #include "ipc/ipc_sync_message_filter.h" namespace content {
diff --git a/content/renderer/gpu/queue_message_swap_promise.h b/content/renderer/queue_message_swap_promise.h similarity index 86% rename from content/renderer/gpu/queue_message_swap_promise.h rename to content/renderer/queue_message_swap_promise.h index e56df39..f77cc64 100644 --- a/content/renderer/gpu/queue_message_swap_promise.h +++ b/content/renderer/queue_message_swap_promise.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_QUEUE_MESSAGE_SWAP_PROMISE_H_ -#define CONTENT_RENDERER_GPU_QUEUE_MESSAGE_SWAP_PROMISE_H_ +#ifndef CONTENT_RENDERER_QUEUE_MESSAGE_SWAP_PROMISE_H_ +#define CONTENT_RENDERER_QUEUE_MESSAGE_SWAP_PROMISE_H_ #include <stdint.h> @@ -46,4 +46,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_QUEUE_MESSAGE_SWAP_PROMISE_H_ +#endif // CONTENT_RENDERER_QUEUE_MESSAGE_SWAP_PROMISE_H_
diff --git a/content/renderer/gpu/queue_message_swap_promise_unittest.cc b/content/renderer/queue_message_swap_promise_unittest.cc similarity index 96% rename from content/renderer/gpu/queue_message_swap_promise_unittest.cc rename to content/renderer/queue_message_swap_promise_unittest.cc index 45b1308..878d37e 100644 --- a/content/renderer/gpu/queue_message_swap_promise_unittest.cc +++ b/content/renderer/queue_message_swap_promise_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 "content/renderer/gpu/queue_message_swap_promise.h" +#include "content/renderer/queue_message_swap_promise.h" #include <stddef.h> @@ -15,8 +15,8 @@ #include "cc/trees/swap_promise.h" #include "content/common/render_frame_metadata.mojom.h" #include "content/common/widget_messages.h" -#include "content/renderer/gpu/frame_swap_message_queue.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" +#include "content/renderer/frame_swap_message_queue.h" #include "content/renderer/render_widget.h" #include "content/test/mock_render_process.h" #include "ipc/ipc_message.h" @@ -71,9 +71,8 @@ ~QueueMessageSwapPromiseTest() override {} - std::unique_ptr<cc::SwapPromise> QueueMessageImpl( - IPC::Message* msg, - int source_frame_number) { + std::unique_ptr<cc::SwapPromise> QueueMessageImpl(IPC::Message* msg, + int source_frame_number) { return RenderWidget::QueueMessageImpl(msg, frame_swap_message_queue_.get(), sync_message_filter_, source_frame_number);
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index e0c8e42..29074248 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -93,6 +93,7 @@ #include "content/renderer/appcache/appcache_dispatcher.h" #include "content/renderer/browser_plugin/browser_plugin.h" #include "content/renderer/browser_plugin/browser_plugin_manager.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/content_security_policy_util.h" #include "content/renderer/context_menu_params_builder.h" #include "content/renderer/crash_helpers.h" @@ -100,8 +101,7 @@ #include "content/renderer/effective_connection_type_helper.h" #include "content/renderer/external_popup_menu.h" #include "content/renderer/frame_owner_properties.h" -#include "content/renderer/gpu/gpu_benchmarking_extension.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/gpu_benchmarking_extension.h" #include "content/renderer/history_entry.h" #include "content/renderer/history_serialization.h" #include "content/renderer/image_downloader/image_downloader_impl.h" @@ -1783,8 +1783,6 @@ new PepperBrowserConnection(this); #endif - GetWebFrame()->InitializeSharedWorkerRepositoryClient(GetInterfaceProvider()); - RegisterMojoInterfaces(); // We delay calling this until we have the WebFrame so that any observer or
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 787ee19b..95e59e7 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -87,7 +87,7 @@ #include "content/renderer/dom_storage/webstoragearea_impl.h" #include "content/renderer/dom_storage/webstoragenamespace_impl.h" #include "content/renderer/effective_connection_type_helper.h" -#include "content/renderer/gpu/frame_swap_message_queue.h" +#include "content/renderer/frame_swap_message_queue.h" #include "content/renderer/input/widget_input_handler_manager.h" #include "content/renderer/loader/resource_dispatcher.h" #include "content/renderer/low_memory_mode_controller.h"
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 8cdd01be..578a715 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -39,7 +39,7 @@ #include "content/common/renderer_host.mojom.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/url_loader_throttle_provider.h" -#include "content/renderer/gpu/compositor_dependencies.h" +#include "content/renderer/compositor/compositor_dependencies.h" #include "content/renderer/media/audio/audio_input_ipc_factory.h" #include "content/renderer/media/audio/audio_output_ipc_factory.h" #include "content/renderer/web_test_dependencies.h"
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 8decba47..b4b2dff5 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -43,7 +43,7 @@ #include "content/public/test/render_view_test.h" #include "content/public/test/test_utils.h" #include "content/renderer/accessibility/render_accessibility_impl.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/history_entry.h" #include "content/renderer/history_serialization.h" #include "content/renderer/loader/request_extra_data.h"
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 80c571f..29a4db1 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -71,8 +71,8 @@ #include "content/renderer/appcache/web_application_cache_host_impl.h" #include "content/renderer/browser_plugin/browser_plugin.h" #include "content/renderer/browser_plugin/browser_plugin_manager.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/drop_data_builder.h" -#include "content/renderer/gpu/layer_tree_view.h" #include "content/renderer/history_serialization.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/internal_document_state_data.h"
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 33b3c6a9..53b1c634 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -54,17 +54,17 @@ #include "content/public/common/use_zoom_for_dsf_policy.h" #include "content/public/renderer/content_renderer_client.h" #include "content/renderer/browser_plugin/browser_plugin.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/cursor_utils.h" #include "content/renderer/devtools/render_widget_screen_metrics_emulator.h" #include "content/renderer/drop_data_builder.h" #include "content/renderer/external_popup_menu.h" -#include "content/renderer/gpu/frame_swap_message_queue.h" -#include "content/renderer/gpu/layer_tree_view.h" -#include "content/renderer/gpu/queue_message_swap_promise.h" +#include "content/renderer/frame_swap_message_queue.h" #include "content/renderer/ime_event_guard.h" #include "content/renderer/input/main_thread_event_queue.h" #include "content/renderer/input/widget_input_handler_manager.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" +#include "content/renderer/queue_message_swap_promise.h" #include "content/renderer/render_frame_impl.h" #include "content/renderer/render_frame_metadata_observer_impl.h" #include "content/renderer/render_frame_proxy.h"
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index e967c5f..88c7ddf 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -38,8 +38,8 @@ #include "content/public/common/drop_data.h" #include "content/public/common/screen_info.h" #include "content/public/common/widget_type.h" +#include "content/renderer/compositor/layer_tree_view_delegate.h" #include "content/renderer/devtools/render_widget_screen_metrics_emulator_delegate.h" -#include "content/renderer/gpu/layer_tree_view_delegate.h" #include "content/renderer/input/main_thread_event_queue.h" #include "content/renderer/input/render_widget_input_handler.h" #include "content/renderer/input/render_widget_input_handler_delegate.h"
diff --git a/content/renderer/render_widget_fullscreen_pepper.cc b/content/renderer/render_widget_fullscreen_pepper.cc index d816cb6..9c309d21 100644 --- a/content/renderer/render_widget_fullscreen_pepper.cc +++ b/content/renderer/render_widget_fullscreen_pepper.cc
@@ -15,7 +15,7 @@ #include "content/common/widget_messages.h" #include "content/public/common/content_switches.h" #include "content/public/common/use_zoom_for_dsf_policy.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_thread_impl.h" #include "gpu/ipc/client/gpu_channel_host.h"
diff --git a/content/renderer/render_widget_unittest.cc b/content/renderer/render_widget_unittest.cc index 5261a8d..c5e6bb8 100644 --- a/content/renderer/render_widget_unittest.cc +++ b/content/renderer/render_widget_unittest.cc
@@ -23,8 +23,8 @@ #include "content/common/visual_properties.h" #include "content/public/common/content_features.h" #include "content/public/test/mock_render_thread.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/devtools/render_widget_screen_metrics_emulator.h" -#include "content/renderer/gpu/layer_tree_view.h" #include "content/renderer/input/widget_input_handler_manager.h" #include "content/renderer/render_widget_owner_delegate.h" #include "content/test/fake_compositor_dependencies.h"
diff --git a/content/renderer/service_worker/service_worker_context_client.cc b/content/renderer/service_worker/service_worker_context_client.cc index f0f67ef2..ec75e97 100644 --- a/content/renderer/service_worker/service_worker_context_client.cc +++ b/content/renderer/service_worker/service_worker_context_client.cc
@@ -200,16 +200,16 @@ return web_client_info; } -// Converts a content::BackgroundFetchRegistration object to +// Converts a blink::mojom::BackgroundFetchRegistrationPtr object to // a blink::WebBackgroundFetchRegistration object. blink::WebBackgroundFetchRegistration ToWebBackgroundFetchRegistration( - const BackgroundFetchRegistration& registration) { + blink::mojom::BackgroundFetchRegistrationPtr registration) { return blink::WebBackgroundFetchRegistration( - blink::WebString::FromUTF8(registration.developer_id), - blink::WebString::FromUTF8(registration.unique_id), - registration.upload_total, registration.uploaded, - registration.download_total, registration.downloaded, registration.result, - registration.failure_reason); + blink::WebString::FromUTF8(registration->developer_id), + blink::WebString::FromUTF8(registration->unique_id), + registration->upload_total, registration->uploaded, + registration->download_total, registration->downloaded, + registration->result, registration->failure_reason); } // This is complementary to ConvertWebKitPriorityToNetPriority, defined in @@ -1426,7 +1426,7 @@ } void ServiceWorkerContextClient::DispatchBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchAbortEventCallback callback) { int request_id = context_->timeout_timer->StartEvent( CreateAbortCallback(&context_->background_fetch_abort_event_callbacks)); @@ -1440,11 +1440,11 @@ TRACE_EVENT_FLAG_FLOW_OUT); proxy_->DispatchBackgroundFetchAbortEvent( - request_id, ToWebBackgroundFetchRegistration(registration)); + request_id, ToWebBackgroundFetchRegistration(std::move(registration))); } void ServiceWorkerContextClient::DispatchBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchClickEventCallback callback) { int request_id = context_->timeout_timer->StartEvent( CreateAbortCallback(&context_->background_fetch_click_event_callbacks)); @@ -1458,11 +1458,11 @@ TRACE_EVENT_FLAG_FLOW_OUT); proxy_->DispatchBackgroundFetchClickEvent( - request_id, ToWebBackgroundFetchRegistration(registration)); + request_id, ToWebBackgroundFetchRegistration(std::move(registration))); } void ServiceWorkerContextClient::DispatchBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchFailEventCallback callback) { int request_id = context_->timeout_timer->StartEvent( CreateAbortCallback(&context_->background_fetch_fail_event_callbacks)); @@ -1476,11 +1476,11 @@ TRACE_EVENT_FLAG_FLOW_OUT); proxy_->DispatchBackgroundFetchFailEvent( - request_id, ToWebBackgroundFetchRegistration(registration)); + request_id, ToWebBackgroundFetchRegistration(std::move(registration))); } void ServiceWorkerContextClient::DispatchBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchSuccessEventCallback callback) { int request_id = context_->timeout_timer->StartEvent( CreateAbortCallback(&context_->background_fetched_event_callbacks)); @@ -1494,7 +1494,7 @@ TRACE_EVENT_FLAG_FLOW_OUT); proxy_->DispatchBackgroundFetchSuccessEvent( - request_id, ToWebBackgroundFetchRegistration(registration)); + request_id, ToWebBackgroundFetchRegistration(std::move(registration))); } void ServiceWorkerContextClient::InitializeGlobalScope(
diff --git a/content/renderer/service_worker/service_worker_context_client.h b/content/renderer/service_worker/service_worker_context_client.h index a99b1e86..f3ded1bb 100644 --- a/content/renderer/service_worker/service_worker_context_client.h +++ b/content/renderer/service_worker/service_worker_context_client.h
@@ -239,16 +239,16 @@ DispatchInstallEventCallback callback) override; void DispatchActivateEvent(DispatchActivateEventCallback callback) override; void DispatchBackgroundFetchAbortEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchAbortEventCallback callback) override; void DispatchBackgroundFetchClickEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchClickEventCallback callback) override; void DispatchBackgroundFetchFailEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchFailEventCallback callback) override; void DispatchBackgroundFetchSuccessEvent( - const BackgroundFetchRegistration& registration, + blink::mojom::BackgroundFetchRegistrationPtr registration, DispatchBackgroundFetchSuccessEventCallback callback) override; void DispatchExtendableMessageEvent( mojom::ExtendableMessageEventPtr event,
diff --git a/content/renderer/gpu/stream_texture_host_android.cc b/content/renderer/stream_texture_host_android.cc similarity index 96% rename from content/renderer/gpu/stream_texture_host_android.cc rename to content/renderer/stream_texture_host_android.cc index f9f2036..ca8003cf 100644 --- a/content/renderer/gpu/stream_texture_host_android.cc +++ b/content/renderer/stream_texture_host_android.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "content/renderer/gpu/stream_texture_host_android.h" +#include "content/renderer/stream_texture_host_android.h" #include "base/unguessable_token.h" #include "content/renderer/render_thread_impl.h"
diff --git a/content/renderer/gpu/stream_texture_host_android.h b/content/renderer/stream_texture_host_android.h similarity index 89% rename from content/renderer/gpu/stream_texture_host_android.h rename to content/renderer/stream_texture_host_android.h index 51082d8f..0959300 100644 --- a/content/renderer/gpu/stream_texture_host_android.h +++ b/content/renderer/stream_texture_host_android.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CONTENT_RENDERER_GPU_STREAM_TEXTURE_HOST_ANDROID_H_ -#define CONTENT_RENDERER_GPU_STREAM_TEXTURE_HOST_ANDROID_H_ +#ifndef CONTENT_RENDERER_STREAM_TEXTURE_HOST_ANDROID_H_ +#define CONTENT_RENDERER_STREAM_TEXTURE_HOST_ANDROID_H_ #include <stdint.h> @@ -66,4 +66,4 @@ } // namespace content -#endif // CONTENT_RENDERER_GPU_STREAM_TEXTURE_HOST_ANDROID_H_ +#endif // CONTENT_RENDERER_STREAM_TEXTURE_HOST_ANDROID_H_
diff --git a/content/shell/test_runner/BUILD.gn b/content/shell/test_runner/BUILD.gn index 0c56511..7d26f89 100644 --- a/content/shell/test_runner/BUILD.gn +++ b/content/shell/test_runner/BUILD.gn
@@ -106,6 +106,7 @@ "//content/public/common:service_names", "//content/public/renderer", "//content/renderer:for_content_tests", + "//content/renderer/compositor", "//content/shell:web_test_switches", "//content/shell:web_test_utils", "//content/test:test_runner_support",
diff --git a/content/shell/test_runner/test_runner_for_specific_view.cc b/content/shell/test_runner/test_runner_for_specific_view.cc index e7f6691c..bd11960 100644 --- a/content/shell/test_runner/test_runner_for_specific_view.cc +++ b/content/shell/test_runner/test_runner_for_specific_view.cc
@@ -15,7 +15,7 @@ #include "base/strings/string_number_conversions.h" #include "build/build_config.h" #include "cc/paint/paint_canvas.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/shell/test_runner/layout_and_paint_async_then.h" #include "content/shell/test_runner/layout_dump.h" #include "content/shell/test_runner/mock_content_settings_client.h"
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 382420d..81d728e7 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -339,6 +339,7 @@ "//content/public/renderer", "//content/public/utility", "//content/renderer:for_content_tests", + "//content/renderer/compositor", "//content/shell:pak", "//content/utility:for_content_tests", "//device/base/synchronization", @@ -633,6 +634,7 @@ "//content/public/common", "//content/public/renderer", "//content/renderer:for_content_tests", + "//content/renderer/compositor", "//content/shell:web_test_switches", "//content/shell/test_runner:test_runner", "//device/bluetooth", @@ -968,6 +970,7 @@ "//content/public/gpu", "//content/public/renderer", "//content/renderer:for_content_tests", + "//content/renderer/compositor", "//content/shell:content_shell_lib", "//content/shell:mojo_bindings", "//content/shell:pak", @@ -1698,14 +1701,13 @@ "../renderer/bmp_image_decoder_unittest.cc", "../renderer/categorized_worker_pool_unittest.cc", "../renderer/child_frame_compositing_helper_unittest.cc", + "../renderer/compositor/layer_tree_view_unittest.cc", "../renderer/dom_storage/dom_storage_cached_area_unittest.cc", "../renderer/dom_storage/local_storage_cached_area_unittest.cc", "../renderer/dom_storage/local_storage_cached_areas_unittest.cc", "../renderer/dom_storage/mock_leveldb_wrapper.cc", "../renderer/dom_storage/mock_leveldb_wrapper.h", - "../renderer/gpu/frame_swap_message_queue_unittest.cc", - "../renderer/gpu/layer_tree_view_unittest.cc", - "../renderer/gpu/queue_message_swap_promise_unittest.cc", + "../renderer/frame_swap_message_queue_unittest.cc", "../renderer/ico_image_decoder_unittest.cc", "../renderer/input/input_event_prediction_unittest.cc", "../renderer/input/main_thread_event_queue_unittest.cc", @@ -1788,6 +1790,7 @@ "../renderer/p2p/filtering_network_manager_unittest.cc", "../renderer/p2p/ipc_network_manager_unittest.cc", "../renderer/peripheral_content_heuristic_unittest.cc", + "../renderer/queue_message_swap_promise_unittest.cc", "../renderer/render_frame_metadata_observer_impl_unittest.cc", "../renderer/render_thread_impl_unittest.cc", "../renderer/render_widget_unittest.cc", @@ -1875,6 +1878,7 @@ "//content/public/common:service_names", "//content/public/renderer", "//content/renderer:for_content_tests", + "//content/renderer/compositor", "//crypto", "//device/bluetooth", "//device/bluetooth:mocks",
diff --git a/content/test/fake_compositor_dependencies.h b/content/test/fake_compositor_dependencies.h index 9c803e4..8d00428 100644 --- a/content/test/fake_compositor_dependencies.h +++ b/content/test/fake_compositor_dependencies.h
@@ -8,7 +8,7 @@ #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "cc/test/test_task_graph_runner.h" -#include "content/renderer/gpu/compositor_dependencies.h" +#include "content/renderer/compositor/compositor_dependencies.h" #include "third_party/blink/public/platform/scheduler/test/web_fake_thread_scheduler.h" namespace content {
diff --git a/content/test/stub_layer_tree_view_delegate.h b/content/test/stub_layer_tree_view_delegate.h index 76653d3..c43b54f 100644 --- a/content/test/stub_layer_tree_view_delegate.h +++ b/content/test/stub_layer_tree_view_delegate.h
@@ -5,7 +5,7 @@ #ifndef CONTENT_TEST_STUB_LAYER_TREE_VIEW_DELEGATE_H_ #define CONTENT_TEST_STUB_LAYER_TREE_VIEW_DELEGATE_H_ -#include "content/renderer/gpu/layer_tree_view_delegate.h" +#include "content/renderer/compositor/layer_tree_view_delegate.h" namespace cc { struct ApplyViewportChangesArgs;
diff --git a/content/test/web_test_support.cc b/content/test/web_test_support.cc index d3f1096..173ff02 100644 --- a/content/test/web_test_support.cc +++ b/content/test/web_test_support.cc
@@ -30,7 +30,7 @@ #include "content/public/common/gpu_stream_constants.h" #include "content/public/common/page_state.h" #include "content/public/common/screen_info.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/renderer/input/render_widget_input_handler_delegate.h" #include "content/renderer/loader/request_extra_data.h" #include "content/renderer/loader/web_worker_fetch_context_impl.h"
diff --git a/device/serial/serial_device_enumerator.h b/device/serial/serial_device_enumerator.h index e707e79..689b257 100644 --- a/device/serial/serial_device_enumerator.h +++ b/device/serial/serial_device_enumerator.h
@@ -19,7 +19,7 @@ SerialDeviceEnumerator(); virtual ~SerialDeviceEnumerator(); - virtual std::vector<mojom::SerialDeviceInfoPtr> GetDevices() = 0; + virtual std::vector<mojom::SerialPortInfoPtr> GetDevices() = 0; }; } // namespace device
diff --git a/device/serial/serial_device_enumerator_linux.cc b/device/serial/serial_device_enumerator_linux.cc index b6e7de5..980f232 100644 --- a/device/serial/serial_device_enumerator_linux.cc +++ b/device/serial/serial_device_enumerator_linux.cc
@@ -39,11 +39,11 @@ SerialDeviceEnumeratorLinux::~SerialDeviceEnumeratorLinux() = default; -std::vector<mojom::SerialDeviceInfoPtr> +std::vector<mojom::SerialPortInfoPtr> SerialDeviceEnumeratorLinux::GetDevices() { base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); - std::vector<mojom::SerialDeviceInfoPtr> devices; + std::vector<mojom::SerialPortInfoPtr> devices; ScopedUdevEnumeratePtr enumerate(udev_enumerate_new(udev_.get())); if (!enumerate) { LOG(ERROR) << "Serial device enumeration failed."; @@ -71,7 +71,7 @@ udev_device_get_property_value(device.get(), kHostPathKey); const char* bus = udev_device_get_property_value(device.get(), kHostBusKey); if (path != NULL && bus != NULL) { - auto info = mojom::SerialDeviceInfo::New(); + auto info = mojom::SerialPortInfo::New(); info->path = path; const char* vendor_id =
diff --git a/device/serial/serial_device_enumerator_linux.h b/device/serial/serial_device_enumerator_linux.h index 92f47ae..1c00098 100644 --- a/device/serial/serial_device_enumerator_linux.h +++ b/device/serial/serial_device_enumerator_linux.h
@@ -18,7 +18,7 @@ ~SerialDeviceEnumeratorLinux() override; // Implementation for SerialDeviceEnumerator. - std::vector<mojom::SerialDeviceInfoPtr> GetDevices() override; + std::vector<mojom::SerialPortInfoPtr> GetDevices() override; private: ScopedUdevPtr udev_;
diff --git a/device/serial/serial_device_enumerator_mac.cc b/device/serial/serial_device_enumerator_mac.cc index 0d8531d2..7c01b4a 100644 --- a/device/serial/serial_device_enumerator_mac.cc +++ b/device/serial/serial_device_enumerator_mac.cc
@@ -102,9 +102,9 @@ // Returns an array of devices as retrieved through the new method of // enumerating serial devices (IOKit). This new method gives more information // about the devices than the old method. -std::vector<mojom::SerialDeviceInfoPtr> GetDevicesNew() { - std::vector<mojom::SerialDeviceInfoPtr> devices; - +std::vector<mojom::SerialPortInfoPtr> GetDevicesNew() { + std::vector<mojom::SerialPortInfoPtr> devices; + base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); // Make a service query to find all serial devices. CFMutableDictionaryRef matchingDict = @@ -121,7 +121,7 @@ base::mac::ScopedIOObject<io_iterator_t> scoped_it(it); base::mac::ScopedIOObject<io_service_t> scoped_device; while (scoped_device.reset(IOIteratorNext(scoped_it.get())), scoped_device) { - auto callout_info = mojom::SerialDeviceInfo::New(); + auto callout_info = mojom::SerialPortInfo::New(); uint16_t vendorId; if (GetUInt16Property(scoped_device.get(), CFSTR(kUSBVendorID), @@ -150,7 +150,7 @@ std::string dialinDevice; if (GetStringProperty(scoped_device.get(), CFSTR(kIODialinDeviceKey), &dialinDevice)) { - mojom::SerialDeviceInfoPtr dialin_info = callout_info.Clone(); + mojom::SerialPortInfoPtr dialin_info = callout_info.Clone(); dialin_info->path = dialinDevice; devices.push_back(std::move(dialin_info)); } @@ -169,7 +169,7 @@ // Returns an array of devices as retrieved through the old method of // enumerating serial devices (pattern matching in /dev/). This old method gives // less information about the devices than the new method. -std::vector<mojom::SerialDeviceInfoPtr> GetDevicesOld() { +std::vector<mojom::SerialPortInfoPtr> GetDevicesOld() { const base::FilePath kDevRoot("/dev"); const int kFilesAndSymLinks = base::FileEnumerator::FILES | base::FileEnumerator::SHOW_SYM_LINKS; @@ -184,7 +184,7 @@ valid_patterns.insert("/dev/cu.*"); base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); - std::vector<mojom::SerialDeviceInfoPtr> devices; + std::vector<mojom::SerialPortInfoPtr> devices; base::FileEnumerator enumerator(kDevRoot, false, kFilesAndSymLinks); do { const base::FilePath next_device_path(enumerator.Next()); @@ -195,7 +195,7 @@ std::set<std::string>::const_iterator i = valid_patterns.begin(); for (; i != valid_patterns.end(); ++i) { if (base::MatchPattern(next_device, *i)) { - auto info = mojom::SerialDeviceInfo::New(); + auto info = mojom::SerialPortInfo::New(); info->path = next_device; devices.push_back(std::move(info)); break; @@ -217,10 +217,9 @@ SerialDeviceEnumeratorMac::~SerialDeviceEnumeratorMac() {} -std::vector<mojom::SerialDeviceInfoPtr> -SerialDeviceEnumeratorMac::GetDevices() { - std::vector<mojom::SerialDeviceInfoPtr> devices = GetDevicesNew(); - std::vector<mojom::SerialDeviceInfoPtr> old_devices = GetDevicesOld(); +std::vector<mojom::SerialPortInfoPtr> SerialDeviceEnumeratorMac::GetDevices() { + std::vector<mojom::SerialPortInfoPtr> devices = GetDevicesNew(); + std::vector<mojom::SerialPortInfoPtr> old_devices = GetDevicesOld(); base::UmaHistogramSparse("Hardware.Serial.NewMinusOldDeviceListSize", Clamp(devices.size() - old_devices.size(), -10, 10));
diff --git a/device/serial/serial_device_enumerator_mac.h b/device/serial/serial_device_enumerator_mac.h index 04c504f7..939a7f9b3 100644 --- a/device/serial/serial_device_enumerator_mac.h +++ b/device/serial/serial_device_enumerator_mac.h
@@ -17,7 +17,7 @@ ~SerialDeviceEnumeratorMac() override; // Implementation for SerialDeviceEnumerator. - std::vector<mojom::SerialDeviceInfoPtr> GetDevices() override; + std::vector<mojom::SerialPortInfoPtr> GetDevices() override; private: DISALLOW_COPY_AND_ASSIGN(SerialDeviceEnumeratorMac);
diff --git a/device/serial/serial_device_enumerator_unittest.cc b/device/serial/serial_device_enumerator_unittest.cc index 4f0f55a..c277c417 100644 --- a/device/serial/serial_device_enumerator_unittest.cc +++ b/device/serial/serial_device_enumerator_unittest.cc
@@ -17,7 +17,7 @@ // attempting to enumerate devices does not cause a crash. auto enumerator = SerialDeviceEnumerator::Create(); ASSERT_TRUE(enumerator); - std::vector<mojom::SerialDeviceInfoPtr> devices = enumerator->GetDevices(); + std::vector<mojom::SerialPortInfoPtr> devices = enumerator->GetDevices(); } } // namespace device
diff --git a/device/serial/serial_device_enumerator_win.cc b/device/serial/serial_device_enumerator_win.cc index 634529b8..9a4d69b 100644 --- a/device/serial/serial_device_enumerator_win.cc +++ b/device/serial/serial_device_enumerator_win.cc
@@ -90,8 +90,8 @@ // Returns an array of devices as retrieved through the new method of // enumerating serial devices (SetupDi). This new method gives more information // about the devices than the old method. -std::vector<mojom::SerialDeviceInfoPtr> GetDevicesNew() { - std::vector<mojom::SerialDeviceInfoPtr> devices; +std::vector<mojom::SerialPortInfoPtr> GetDevicesNew() { + std::vector<mojom::SerialPortInfoPtr> devices; base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); // Make a device interface query to find all serial devices. @@ -112,7 +112,7 @@ // serial device. If the COM can't be found, ignore the device. continue; - auto info = mojom::SerialDeviceInfo::New(); + auto info = mojom::SerialPortInfo::New(); info->path = com_port; std::string display_name; @@ -143,13 +143,13 @@ // Returns an array of devices as retrieved through the old method of // enumerating serial devices (searching the registry). This old method gives // less information about the devices than the new method. -std::vector<mojom::SerialDeviceInfoPtr> GetDevicesOld() { +std::vector<mojom::SerialPortInfoPtr> GetDevicesOld() { base::ScopedBlockingCall scoped_blocking_call(base::BlockingType::MAY_BLOCK); base::win::RegistryValueIterator iter_key( HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\SERIALCOMM\\"); - std::vector<mojom::SerialDeviceInfoPtr> devices; + std::vector<mojom::SerialPortInfoPtr> devices; for (; iter_key.Valid(); ++iter_key) { - auto info = mojom::SerialDeviceInfo::New(); + auto info = mojom::SerialPortInfo::New(); info->path = base::UTF16ToASCII(iter_key.Value()); devices.push_back(std::move(info)); } @@ -168,10 +168,9 @@ SerialDeviceEnumeratorWin::~SerialDeviceEnumeratorWin() {} -std::vector<mojom::SerialDeviceInfoPtr> -SerialDeviceEnumeratorWin::GetDevices() { - std::vector<mojom::SerialDeviceInfoPtr> devices = GetDevicesNew(); - std::vector<mojom::SerialDeviceInfoPtr> old_devices = GetDevicesOld(); +std::vector<mojom::SerialPortInfoPtr> SerialDeviceEnumeratorWin::GetDevices() { + std::vector<mojom::SerialPortInfoPtr> devices = GetDevicesNew(); + std::vector<mojom::SerialPortInfoPtr> old_devices = GetDevicesOld(); base::UmaHistogramSparse("Hardware.Serial.NewMinusOldDeviceListSize", Clamp(devices.size() - old_devices.size(), -10, 10));
diff --git a/device/serial/serial_device_enumerator_win.h b/device/serial/serial_device_enumerator_win.h index 1eea2df0..64ce93b7 100644 --- a/device/serial/serial_device_enumerator_win.h +++ b/device/serial/serial_device_enumerator_win.h
@@ -17,7 +17,7 @@ ~SerialDeviceEnumeratorWin() override; // Implementation for SerialDeviceEnumerator. - std::vector<mojom::SerialDeviceInfoPtr> GetDevices() override; + std::vector<mojom::SerialPortInfoPtr> GetDevices() override; private: DISALLOW_COPY_AND_ASSIGN(SerialDeviceEnumeratorWin);
diff --git a/device/serial/serial_io_handler.h b/device/serial/serial_io_handler.h index 9bc5796..ac833fe 100644 --- a/device/serial/serial_io_handler.h +++ b/device/serial/serial_io_handler.h
@@ -84,7 +84,7 @@ // Reads current control signals (DCD, CTS, etc.) into an existing // DeviceControlSignals structure. Returns |true| iff the signals were // successfully read. - virtual mojom::SerialDeviceControlSignalsPtr GetControlSignals() const = 0; + virtual mojom::SerialPortControlSignalsPtr GetControlSignals() const = 0; // Sets one or more control signals (DTR and/or RTS). Returns |true| iff // the signals were successfully set. Unininitialized flags in the
diff --git a/device/serial/serial_io_handler_posix.cc b/device/serial/serial_io_handler_posix.cc index d6ed5e1f..2cbe3bf 100644 --- a/device/serial/serial_io_handler_posix.cc +++ b/device/serial/serial_io_handler_posix.cc
@@ -403,15 +403,15 @@ return true; } -mojom::SerialDeviceControlSignalsPtr SerialIoHandlerPosix::GetControlSignals() +mojom::SerialPortControlSignalsPtr SerialIoHandlerPosix::GetControlSignals() const { int status; if (ioctl(file().GetPlatformFile(), TIOCMGET, &status) == -1) { VPLOG(1) << "Failed to get port control signals"; - return mojom::SerialDeviceControlSignalsPtr(); + return mojom::SerialPortControlSignalsPtr(); } - auto signals = mojom::SerialDeviceControlSignals::New(); + auto signals = mojom::SerialPortControlSignals::New(); signals->dcd = (status & TIOCM_CAR) != 0; signals->cts = (status & TIOCM_CTS) != 0; signals->dsr = (status & TIOCM_DSR) != 0;
diff --git a/device/serial/serial_io_handler_posix.h b/device/serial/serial_io_handler_posix.h index 7b8abd0..cd8bf41 100644 --- a/device/serial/serial_io_handler_posix.h +++ b/device/serial/serial_io_handler_posix.h
@@ -30,7 +30,7 @@ bool ConfigurePortImpl() override; bool PostOpen() override; bool Flush() const override; - mojom::SerialDeviceControlSignalsPtr GetControlSignals() const override; + mojom::SerialPortControlSignalsPtr GetControlSignals() const override; bool SetControlSignals( const mojom::SerialHostControlSignals& control_signals) override; mojom::SerialConnectionInfoPtr GetPortInfo() const override;
diff --git a/device/serial/serial_io_handler_win.cc b/device/serial/serial_io_handler_win.cc index 26efe2c..c68b256 100644 --- a/device/serial/serial_io_handler_win.cc +++ b/device/serial/serial_io_handler_win.cc
@@ -459,15 +459,15 @@ return true; } -mojom::SerialDeviceControlSignalsPtr SerialIoHandlerWin::GetControlSignals() +mojom::SerialPortControlSignalsPtr SerialIoHandlerWin::GetControlSignals() const { DWORD status; if (!GetCommModemStatus(file().GetPlatformFile(), &status)) { VPLOG(1) << "Failed to get port control signals"; - return mojom::SerialDeviceControlSignalsPtr(); + return mojom::SerialPortControlSignalsPtr(); } - auto signals = mojom::SerialDeviceControlSignals::New(); + auto signals = mojom::SerialPortControlSignals::New(); signals->dcd = (status & MS_RLSD_ON) != 0; signals->cts = (status & MS_CTS_ON) != 0; signals->dsr = (status & MS_DSR_ON) != 0;
diff --git a/device/serial/serial_io_handler_win.h b/device/serial/serial_io_handler_win.h index dad99fa..a0ec69e3 100644 --- a/device/serial/serial_io_handler_win.h +++ b/device/serial/serial_io_handler_win.h
@@ -25,7 +25,7 @@ void CancelWriteImpl() override; bool ConfigurePortImpl() override; bool Flush() const override; - mojom::SerialDeviceControlSignalsPtr GetControlSignals() const override; + mojom::SerialPortControlSignalsPtr GetControlSignals() const override; bool SetControlSignals( const mojom::SerialHostControlSignals& control_signals) override; mojom::SerialConnectionInfoPtr GetPortInfo() const override;
diff --git a/extensions/browser/api/serial/serial_api.cc b/extensions/browser/api/serial/serial_api.cc index b5354b1b..5ea6e20a 100644 --- a/extensions/browser/api/serial/serial_api.cc +++ b/extensions/browser/api/serial/serial_api.cc
@@ -90,14 +90,14 @@ mojo::MakeRequest(&enumerator_)); enumerator_.set_connection_error_handler( base::BindOnce(&SerialGetDevicesFunction::OnGotDevices, this, - std::vector<device::mojom::SerialDeviceInfoPtr>())); + std::vector<device::mojom::SerialPortInfoPtr>())); enumerator_->GetDevices( base::BindOnce(&SerialGetDevicesFunction::OnGotDevices, this)); return RespondLater(); } void SerialGetDevicesFunction::OnGotDevices( - std::vector<device::mojom::SerialDeviceInfoPtr> devices) { + std::vector<device::mojom::SerialPortInfoPtr> devices) { std::unique_ptr<base::ListValue> results = serial::GetDevices::Results::Create( mojo::ConvertTo<std::vector<serial::DeviceInfo>>(devices)); @@ -556,8 +556,8 @@ // static extensions::api::serial::DeviceInfo TypeConverter<extensions::api::serial::DeviceInfo, - device::mojom::SerialDeviceInfoPtr>:: - Convert(const device::mojom::SerialDeviceInfoPtr& device) { + device::mojom::SerialPortInfoPtr>:: + Convert(const device::mojom::SerialPortInfoPtr& device) { extensions::api::serial::DeviceInfo info; info.path = device->path; if (device->has_vendor_id)
diff --git a/extensions/browser/api/serial/serial_api.h b/extensions/browser/api/serial/serial_api.h index 0e5fe9f5..71bd431 100644 --- a/extensions/browser/api/serial/serial_api.h +++ b/extensions/browser/api/serial/serial_api.h
@@ -50,9 +50,9 @@ ResponseAction Run() override; private: - void OnGotDevices(std::vector<device::mojom::SerialDeviceInfoPtr> devices); + void OnGotDevices(std::vector<device::mojom::SerialPortInfoPtr> devices); - device::mojom::SerialDeviceEnumeratorPtr enumerator_; + device::mojom::SerialPortManagerPtr enumerator_; DISALLOW_COPY_AND_ASSIGN(SerialGetDevicesFunction); }; @@ -86,7 +86,7 @@ // ApiResourceManager<SerialConnection> upon success. std::unique_ptr<SerialConnection> connection_; - device::mojom::SerialIoHandlerPtrInfo io_handler_info_; + device::mojom::SerialPortPtrInfo io_handler_info_; }; class SerialUpdateFunction : public SerialAsyncApiFunction { @@ -309,9 +309,9 @@ template <> struct TypeConverter<extensions::api::serial::DeviceInfo, - device::mojom::SerialDeviceInfoPtr> { + device::mojom::SerialPortInfoPtr> { static extensions::api::serial::DeviceInfo Convert( - const device::mojom::SerialDeviceInfoPtr& input); + const device::mojom::SerialPortInfoPtr& input); }; } // namespace mojo
diff --git a/extensions/browser/api/serial/serial_apitest.cc b/extensions/browser/api/serial/serial_apitest.cc index a4dbb4cb..ced8dcf0 100644 --- a/extensions/browser/api/serial/serial_apitest.cc +++ b/extensions/browser/api/serial/serial_apitest.cc
@@ -50,31 +50,30 @@ namespace extensions { namespace { -class FakeSerialDeviceEnumerator - : public device::mojom::SerialDeviceEnumerator { +class FakeSerialPortManager : public device::mojom::SerialPortManager { public: - FakeSerialDeviceEnumerator() = default; - ~FakeSerialDeviceEnumerator() override = default; + FakeSerialPortManager() = default; + ~FakeSerialPortManager() override = default; private: - // device::mojom::SerialDeviceEnumerator methods: + // device::mojom::SerialPortManager methods: void GetDevices(GetDevicesCallback callback) override { - std::vector<device::mojom::SerialDeviceInfoPtr> devices; - auto device0 = device::mojom::SerialDeviceInfo::New(); + std::vector<device::mojom::SerialPortInfoPtr> devices; + auto device0 = device::mojom::SerialPortInfo::New(); device0->path = "/dev/fakeserialmojo"; - auto device1 = device::mojom::SerialDeviceInfo::New(); + auto device1 = device::mojom::SerialPortInfo::New(); device1->path = "\\\\COM800\\"; devices.push_back(std::move(device0)); devices.push_back(std::move(device1)); std::move(callback).Run(std::move(devices)); } - DISALLOW_COPY_AND_ASSIGN(FakeSerialDeviceEnumerator); + DISALLOW_COPY_AND_ASSIGN(FakeSerialPortManager); }; -class FakeSerialIoHandler : public device::mojom::SerialIoHandler { +class FakeSerialPort : public device::mojom::SerialPort { public: - FakeSerialIoHandler() { + FakeSerialPort() { options_.bitrate = 9600; options_.data_bits = device::mojom::SerialDataBits::EIGHT; options_.parity_bit = device::mojom::SerialParityBit::NO_PARITY; @@ -82,10 +81,10 @@ options_.cts_flow_control = false; options_.has_cts_flow_control = true; } - ~FakeSerialIoHandler() override = default; + ~FakeSerialPort() override = default; private: - // device::mojom::SerialIoHandler methods: + // device::mojom::SerialPort methods: void Open(const std::string& port, device::mojom::SerialConnectionOptionsPtr options, OpenCallback callback) override { @@ -116,7 +115,7 @@ } void Flush(FlushCallback callback) override { std::move(callback).Run(true); } void GetControlSignals(GetControlSignalsCallback callback) override { - auto signals = device::mojom::SerialDeviceControlSignals::New(); + auto signals = device::mojom::SerialPortControlSignals::New(); signals->dcd = true; signals->cts = true; signals->ri = true; @@ -184,10 +183,10 @@ // Currently applied connection options. device::mojom::SerialConnectionOptions options_; std::vector<uint8_t> buffer_; - FakeSerialIoHandler::ReadCallback pending_read_callback_; + FakeSerialPort::ReadCallback pending_read_callback_; uint32_t pending_read_bytes_ = 0; - DISALLOW_COPY_AND_ASSIGN(FakeSerialIoHandler); + DISALLOW_COPY_AND_ASSIGN(FakeSerialPort); }; class SerialApiTest : public ExtensionApiTest { @@ -196,23 +195,23 @@ #if SIMULATE_SERIAL_PORTS // Because Device Service also runs in this process(browser process), we can // set our binder to intercept requests for - // SerialDeviceEnumerator/SerialIoHandler interfaces to it. + // SerialPortManager/SerialPort interfaces to it. service_manager::ServiceBinding::OverrideInterfaceBinderForTesting( device::mojom::kServiceName, - base::BindRepeating(&SerialApiTest::BindSerialDeviceEnumerator, + base::BindRepeating(&SerialApiTest::BindSerialPortManager, base::Unretained(this))); service_manager::ServiceBinding::OverrideInterfaceBinderForTesting( device::mojom::kServiceName, - base::BindRepeating(&SerialApiTest::BindSerialIoHandler)); + base::BindRepeating(&SerialApiTest::BindSerialPort)); #endif } ~SerialApiTest() override { #if SIMULATE_SERIAL_PORTS service_manager::ServiceBinding::ClearInterfaceBinderOverrideForTesting< - device::mojom::SerialDeviceEnumerator>(device::mojom::kServiceName); + device::mojom::SerialPortManager>(device::mojom::kServiceName); service_manager::ServiceBinding::ClearInterfaceBinderOverrideForTesting< - device::mojom::SerialIoHandler>(device::mojom::kServiceName); + device::mojom::SerialPort>(device::mojom::kServiceName); #endif } @@ -229,18 +228,16 @@ void FailEnumeratorRequest() { fail_enumerator_request_ = true; } protected: - void BindSerialDeviceEnumerator( - device::mojom::SerialDeviceEnumeratorRequest request) { + void BindSerialPortManager(device::mojom::SerialPortManagerRequest request) { if (fail_enumerator_request_) return; - mojo::MakeStrongBinding(std::make_unique<FakeSerialDeviceEnumerator>(), + mojo::MakeStrongBinding(std::make_unique<FakeSerialPortManager>(), std::move(request)); } - static void BindSerialIoHandler( - device::mojom::SerialIoHandlerRequest request) { - mojo::MakeStrongBinding(std::make_unique<FakeSerialIoHandler>(), + static void BindSerialPort(device::mojom::SerialPortRequest request) { + mojo::MakeStrongBinding(std::make_unique<FakeSerialPort>(), std::move(request)); }
diff --git a/extensions/browser/api/serial/serial_connection.cc b/extensions/browser/api/serial/serial_connection.cc index d9439a4..a015e955 100644 --- a/extensions/browser/api/serial/serial_connection.cc +++ b/extensions/browser/api/serial/serial_connection.cc
@@ -165,7 +165,7 @@ SerialConnection::SerialConnection( const std::string& port, const std::string& owner_extension_id, - device::mojom::SerialIoHandlerPtrInfo io_handler_info) + device::mojom::SerialPortPtrInfo io_handler_info) : ApiResource(owner_extension_id), port_(port), persistent_(false), @@ -352,7 +352,7 @@ DCHECK(io_handler_); auto resp_callback = base::BindOnce( [](GetControlSignalsCompleteCallback callback, - device::mojom::SerialDeviceControlSignalsPtr signals) { + device::mojom::SerialPortControlSignalsPtr signals) { if (!signals) { std::move(callback).Run(nullptr); return;
diff --git a/extensions/browser/api/serial/serial_connection.h b/extensions/browser/api/serial/serial_connection.h index 6bfb8f8e..54ce1501 100644 --- a/extensions/browser/api/serial/serial_connection.h +++ b/extensions/browser/api/serial/serial_connection.h
@@ -24,13 +24,13 @@ namespace extensions { -// Encapsulates an mojo interface ptr of device::mojom::SerialIoHandler, which +// Encapsulates an mojo interface ptr of device::mojom::SerialPort, which // corresponds with an open serial port in remote side(Device Service). NOTE: // Instances of this object should only be constructed on the IO thread, and all // methods should only be called on the IO thread unless otherwise noted. class SerialConnection : public ApiResource { public: - using OpenCompleteCallback = device::mojom::SerialIoHandler::OpenCallback; + using OpenCompleteCallback = device::mojom::SerialPort::OpenCallback; using GetInfoCompleteCallback = base::OnceCallback<void(bool, std::unique_ptr<api::serial::ConnectionInfo>)>; @@ -50,25 +50,24 @@ api::serial::SendError error)>; using ConfigureCompleteCallback = - device::mojom::SerialIoHandler::ConfigurePortCallback; + device::mojom::SerialPort::ConfigurePortCallback; - using FlushCompleteCallback = device::mojom::SerialIoHandler::FlushCallback; + using FlushCompleteCallback = device::mojom::SerialPort::FlushCallback; using GetControlSignalsCompleteCallback = base::OnceCallback<void( std::unique_ptr<api::serial::DeviceControlSignals>)>; using SetControlSignalsCompleteCallback = - device::mojom::SerialIoHandler::SetControlSignalsCallback; + device::mojom::SerialPort::SetControlSignalsCallback; - using SetBreakCompleteCallback = - device::mojom::SerialIoHandler::SetBreakCallback; + using SetBreakCompleteCallback = device::mojom::SerialPort::SetBreakCallback; using ClearBreakCompleteCallback = - device::mojom::SerialIoHandler::ClearBreakCallback; + device::mojom::SerialPort::ClearBreakCallback; SerialConnection(const std::string& port, const std::string& owner_extension_id, - device::mojom::SerialIoHandlerPtrInfo io_handler_info); + device::mojom::SerialPortPtrInfo io_handler_info); ~SerialConnection() override; // ApiResource override. @@ -122,7 +121,7 @@ // Connection configuration query. Returns retrieved ConnectionInfo value via // |callback|, and indicates whether it's complete info. Some ConnectionInfo // fields are filled with local info from |this|, while some other fields must - // be retrieved from remote SerialIoHandler interface, which may fail. + // be retrieved from remote SerialPort interface, which may fail. void GetInfo(GetInfoCompleteCallback callback) const; // Reads current control signals (DCD, CTS, etc.) and returns via |callback|. @@ -206,7 +205,7 @@ base::CancelableClosure send_timeout_task_; // Mojo interface ptr corresponding with remote asynchronous I/O handler. - device::mojom::SerialIoHandlerPtr io_handler_; + device::mojom::SerialPortPtr io_handler_; // Closure which is set by client and will be called when |io_handler_| // connection encountered an error. base::OnceClosure connection_error_handler_;
diff --git a/extensions/browser/api/storage/storage_api_unittest.cc b/extensions/browser/api/storage/storage_api_unittest.cc index dff8426..2e056eb8b 100644 --- a/extensions/browser/api/storage/storage_api_unittest.cc +++ b/extensions/browser/api/storage/storage_api_unittest.cc
@@ -19,10 +19,12 @@ #include "extensions/browser/api_unittest.h" #include "extensions/browser/event_router.h" #include "extensions/browser/event_router_factory.h" +#include "extensions/browser/test_event_router_observer.h" #include "extensions/browser/test_extensions_browser_client.h" #include "extensions/browser/value_store/leveldb_value_store.h" #include "extensions/browser/value_store/value_store.h" #include "extensions/browser/value_store/value_store_factory_impl.h" +#include "extensions/common/api/storage.h" #include "extensions/common/manifest.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" @@ -52,6 +54,19 @@ ~StorageApiUnittest() override {} protected: + void SetUp() override { + ApiUnitTest::SetUp(); + + EventRouterFactory::GetInstance()->SetTestingFactory( + browser_context(), base::BindRepeating(&BuildEventRouter)); + + // Ensure a StorageFrontend can be created on demand. The StorageFrontend + // will be owned by the KeyedService system. + StorageFrontend::GetFactoryInstance()->SetTestingFactory( + browser_context(), + base::BindRepeating(&CreateStorageFrontendForTesting)); + } + // Runs the storage.set() API function with local storage. void RunSetFunction(const std::string& key, const std::string& value) { RunFunction( @@ -84,14 +99,6 @@ }; TEST_F(StorageApiUnittest, RestoreCorruptedStorage) { - EventRouterFactory::GetInstance()->SetTestingFactory( - browser_context(), base::BindRepeating(&BuildEventRouter)); - - // Ensure a StorageFrontend can be created on demand. The StorageFrontend - // will be owned by the KeyedService system. - StorageFrontend::GetFactoryInstance()->SetTestingFactory( - browser_context(), base::BindRepeating(&CreateStorageFrontendForTesting)); - const char kKey[] = "key"; const char kValue[] = "value"; std::string result; @@ -127,4 +134,16 @@ EXPECT_EQ(kValue, result); } +TEST_F(StorageApiUnittest, StorageAreaOnChanged) { + TestEventRouterObserver event_observer(EventRouter::Get(browser_context())); + + RunSetFunction("key", "value"); + EXPECT_EQ(2u, event_observer.events().size()); + + EXPECT_TRUE(base::ContainsKey(event_observer.events(), + api::storage::OnChanged::kEventName)); + EXPECT_TRUE( + base::ContainsKey(event_observer.events(), "storage.local.onChanged")); +} + } // namespace extensions
diff --git a/extensions/browser/api/storage/storage_frontend.cc b/extensions/browser/api/storage/storage_frontend.cc index e550cd2e..ffbd12a 100644 --- a/extensions/browser/api/storage/storage_frontend.cc +++ b/extensions/browser/api/storage/storage_frontend.cc
@@ -13,6 +13,7 @@ #include "base/lazy_instance.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" @@ -35,6 +36,22 @@ base::LazyInstance<BrowserContextKeyedAPIFactory<StorageFrontend>>:: DestructorAtExit g_factory = LAZY_INSTANCE_INITIALIZER; +events::HistogramValue NamespaceToEventHistogram( + settings_namespace::Namespace settings_namespace) { + switch (settings_namespace) { + case settings_namespace::LOCAL: + return events::STORAGE_LOCAL_ON_CHANGE; + case settings_namespace::SYNC: + return events::STORAGE_SYNC_ON_CHANGE; + case settings_namespace::MANAGED: + return events::STORAGE_MANAGED_ON_CHANGE; + case settings_namespace::INVALID: + break; + } + NOTREACHED(); + return events::UNKNOWN; +} + // Settings change Observer which forwards changes on to the extension // processes for |context| and its incognito partner if it exists. class DefaultObserver : public SettingsObserver { @@ -46,9 +63,6 @@ void OnSettingsChanged(const std::string& extension_id, settings_namespace::Namespace settings_namespace, const std::string& change_json) override { - // TODO(gdk): This is a temporary hack while the refactoring for - // string-based event payloads is removed. http://crbug.com/136045 - std::unique_ptr<base::ListValue> args(new base::ListValue()); std::unique_ptr<base::Value> changes = base::JSONReader::Read(change_json); DCHECK(changes); // TODO(devlin): crbug.com/645500 implies this can sometimes fail. If this @@ -56,13 +70,34 @@ // passing invalid json here?). if (!changes) changes = std::make_unique<base::DictionaryValue>(); - args->Append(std::move(changes)); - args->AppendString(settings_namespace::ToString(settings_namespace)); - std::unique_ptr<Event> event(new Event(events::STORAGE_ON_CHANGED, - api::storage::OnChanged::kEventName, - std::move(args))); - EventRouter::Get(browser_context_) - ->DispatchEventToExtension(extension_id, std::move(event)); + + const std::string namespace_string = + settings_namespace::ToString(settings_namespace); + EventRouter* event_router = EventRouter::Get(browser_context_); + + // Event for each storage(sync, local, managed). + { + // TODO(gdk): This is a temporary hack while the refactoring for + // string-based event payloads is removed. http://crbug.com/136045 + std::unique_ptr<base::ListValue> args(new base::ListValue()); + args->Append(std::make_unique<base::Value>(changes->Clone())); + args->AppendString(namespace_string); + std::unique_ptr<Event> event( + new Event(events::STORAGE_ON_CHANGED, + api::storage::OnChanged::kEventName, std::move(args))); + event_router->DispatchEventToExtension(extension_id, std::move(event)); + } + + // Event for StorageArea. + { + auto args = std::make_unique<base::ListValue>(); + args->GetList().push_back(changes->Clone()); + auto event = std::make_unique<Event>( + NamespaceToEventHistogram(settings_namespace), + base::StringPrintf("storage.%s.onChanged", namespace_string.c_str()), + std::move(args)); + event_router->DispatchEventToExtension(extension_id, std::move(event)); + } } private:
diff --git a/extensions/browser/api/webcam_private/visca_webcam.cc b/extensions/browser/api/webcam_private/visca_webcam.cc index e4174e0d..d8d8278 100644 --- a/extensions/browser/api/webcam_private/visca_webcam.cc +++ b/extensions/browser/api/webcam_private/visca_webcam.cc
@@ -171,24 +171,23 @@ const std::string& extension_id, const OpenCompleteCallback& open_callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - device::mojom::SerialIoHandlerPtrInfo io_handler_info; + device::mojom::SerialPortPtrInfo port_ptr_info; DCHECK(content::ServiceManagerConnection::GetForProcess()); content::ServiceManagerConnection::GetForProcess() ->GetConnector() ->BindInterface(device::mojom::kServiceName, - mojo::MakeRequest(&io_handler_info)); + mojo::MakeRequest(&port_ptr_info)); base::PostTaskWithTraits( FROM_HERE, {BrowserThread::IO}, base::Bind(&ViscaWebcam::OpenOnIOThread, weak_ptr_factory_.GetWeakPtr(), - path, extension_id, base::Passed(&io_handler_info), + path, extension_id, base::Passed(&port_ptr_info), open_callback)); } -void ViscaWebcam::OpenOnIOThread( - const std::string& path, - const std::string& extension_id, - device::mojom::SerialIoHandlerPtrInfo io_handler_info, - const OpenCompleteCallback& open_callback) { +void ViscaWebcam::OpenOnIOThread(const std::string& path, + const std::string& extension_id, + device::mojom::SerialPortPtrInfo port_ptr_info, + const OpenCompleteCallback& open_callback) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); api::serial::ConnectionOptions options; @@ -206,7 +205,7 @@ options.stop_bits = api::serial::STOP_BITS_ONE; serial_connection_.reset( - new SerialConnection(path, extension_id, std::move(io_handler_info))); + new SerialConnection(path, extension_id, std::move(port_ptr_info))); serial_connection_->Open( options, base::BindOnce(&ViscaWebcam::OnConnected, weak_ptr_factory_.GetWeakPtr(), open_callback));
diff --git a/extensions/browser/api/webcam_private/visca_webcam.h b/extensions/browser/api/webcam_private/visca_webcam.h index 2c4b287..dcd52af 100644 --- a/extensions/browser/api/webcam_private/visca_webcam.h +++ b/extensions/browser/api/webcam_private/visca_webcam.h
@@ -48,7 +48,7 @@ void OpenOnIOThread(const std::string& path, const std::string& extension_id, - device::mojom::SerialIoHandlerPtrInfo io_handler_info, + device::mojom::SerialPortPtrInfo port_ptr_info, const OpenCompleteCallback& open_callback); // Callback function that will be called after the serial connection has been
diff --git a/extensions/browser/api/webcam_private/visca_webcam_unittest.cc b/extensions/browser/api/webcam_private/visca_webcam_unittest.cc index 6ce7d8a..0f142fd 100644 --- a/extensions/browser/api/webcam_private/visca_webcam_unittest.cc +++ b/extensions/browser/api/webcam_private/visca_webcam_unittest.cc
@@ -18,9 +18,8 @@ class TestSerialConnection : public SerialConnection { public: - TestSerialConnection(device::mojom::SerialIoHandlerPtrInfo io_handler_info) - : SerialConnection("dummy_path", "dummy_id", std::move(io_handler_info)) { - } + TestSerialConnection(device::mojom::SerialPortPtrInfo port_ptr_info) + : SerialConnection("dummy_path", "dummy_id", std::move(port_ptr_info)) {} ~TestSerialConnection() override {} void SetReceiveBuffer(const std::vector<uint8_t>& receive_buffer) { @@ -104,11 +103,11 @@ class ViscaWebcamTest : public testing::Test { protected: ViscaWebcamTest() { - device::mojom::SerialIoHandlerPtrInfo io_handler_info; - mojo::MakeRequest(&io_handler_info); + device::mojom::SerialPortPtrInfo port_ptr_info; + mojo::MakeRequest(&port_ptr_info); webcam_ = new ViscaWebcam; webcam_->OpenForTesting( - std::make_unique<TestSerialConnection>(std::move(io_handler_info))); + std::make_unique<TestSerialConnection>(std::move(port_ptr_info))); } ~ViscaWebcamTest() override {}
diff --git a/extensions/browser/extension_event_histogram_value.h b/extensions/browser/extension_event_histogram_value.h index 9ae89704..841b2818 100644 --- a/extensions/browser/extension_event_histogram_value.h +++ b/extensions/browser/extension_event_histogram_value.h
@@ -448,6 +448,9 @@ AUTOMATION_INTERNAL_ON_GET_TEXT_LOCATION_RESULT = 427, INPUT_METHOD_PRIVATE_ON_SETTINGS_CHANGED = 428, INPUT_METHOD_PRIVATE_ON_SCREEN_PROJECTION_CHANGED = 429, + STORAGE_LOCAL_ON_CHANGE = 430, + STORAGE_SYNC_ON_CHANGE = 431, + STORAGE_MANAGED_ON_CHANGE = 432, // Last entry: Add new entries above, then run: // python tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 162320b7..00e0195 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -1360,6 +1360,10 @@ FILEMANAGERPRIVATEINTERNAL_UNSHAREPATHWITHCROSTINI = 1297, PASSWORDSPRIVATE_RECORDPASSWORDSPAGEACCESSINSETTINGS = 1298, AUTOFILLPRIVATE_SERVERCARDLINKCLICKED = 1299, + AUTOTESTPRIVATE_GETARCAPP = 1300, + AUTOTESTPRIVATE_GETARCPACKAGE = 1301, + AUTOTESTPRIVATE_LAUNCHARCAPP = 1302, + AUTOTESTPRIVATE_CLOSEAPP = 1303, // Last entry: Add new entries above, then run: // python tools/metrics/histograms/update_extension_histograms.py ENUM_BOUNDARY
diff --git a/extensions/common/api/storage.json b/extensions/common/api/storage.json index dc6a6bd..d53fe9dc6 100644 --- a/extensions/common/api/storage.json +++ b/extensions/common/api/storage.json
@@ -152,6 +152,20 @@ } ] } + ], + "events": [ + { + "name": "onChanged", + "description": "Fired when one or more items change.", + "parameters": [ + { + "name": "changes", + "type": "object", + "additionalProperties": { "$ref": "StorageChange" }, + "description": "Object mapping each key that changed to its corresponding $(ref:storage.StorageChange) for that item." + } + ] + } ] } ],
diff --git a/extensions/renderer/resources/storage_area.js b/extensions/renderer/resources/storage_area.js index ff9fafb7e..7ef4014 100644 --- a/extensions/renderer/resources/storage_area.js +++ b/extensions/renderer/resources/storage_area.js
@@ -5,6 +5,7 @@ var normalizeArgumentsAndValidate = require('schemaUtils').normalizeArgumentsAndValidate var sendRequest = require('sendRequest').sendRequest; +var jsEvent = require('event_bindings').Event; function extendSchema(schema) { var extendedSchema = $Array.slice(schema); @@ -18,6 +19,7 @@ // Binds an API function for a namespace to its browser-side call, e.g. // storage.sync.get('foo') -> (binds to) -> // storage.get('sync', 'foo'). + // Note that callback methods are handled sperately. var self = this; function bindApiFunction(functionName) { var rawFunSchema = @@ -42,6 +44,8 @@ } var apiFunctions = ['get', 'set', 'remove', 'clear', 'getBytesInUse']; $Array.forEach(apiFunctions, bindApiFunction); + + this.onChanged = new jsEvent('storage.' + namespace + '.onChanged'); } exports.$set('StorageArea', StorageArea);
diff --git a/extensions/renderer/storage_area.cc b/extensions/renderer/storage_area.cc index 658b827..a290eef 100644 --- a/extensions/renderer/storage_area.cc +++ b/extensions/renderer/storage_area.cc
@@ -7,6 +7,7 @@ #include "base/strings/stringprintf.h" #include "extensions/common/api/storage.h" #include "extensions/renderer/bindings/api_binding_util.h" +#include "extensions/renderer/bindings/api_event_handler.h" #include "extensions/renderer/bindings/api_invocation_errors.h" #include "extensions/renderer/bindings/api_request_handler.h" #include "extensions/renderer/bindings/api_signature.h" @@ -21,22 +22,28 @@ namespace { -#define DEFINE_STORAGE_AREA_HANDLERS() \ - const char* GetTypeName() override { return "StorageArea"; } \ - void Get(gin::Arguments* arguments) { \ - storage_area_.HandleFunctionCall("get", arguments); \ - } \ - void Set(gin::Arguments* arguments) { \ - storage_area_.HandleFunctionCall("set", arguments); \ - } \ - void Remove(gin::Arguments* arguments) { \ - storage_area_.HandleFunctionCall("remove", arguments); \ - } \ - void Clear(gin::Arguments* arguments) { \ - storage_area_.HandleFunctionCall("clear", arguments); \ - } \ - void GetBytesInUse(gin::Arguments* arguments) { \ - storage_area_.HandleFunctionCall("getBytesInUse", arguments); \ +#define DEFINE_STORAGE_AREA_HANDLERS() \ + const char* GetTypeName() override { return "StorageArea"; } \ + void Get(gin::Arguments* arguments) { \ + storage_area_.HandleFunctionCall("get", arguments); \ + } \ + void Set(gin::Arguments* arguments) { \ + storage_area_.HandleFunctionCall("set", arguments); \ + } \ + void Remove(gin::Arguments* arguments) { \ + storage_area_.HandleFunctionCall("remove", arguments); \ + } \ + void Clear(gin::Arguments* arguments) { \ + storage_area_.HandleFunctionCall("clear", arguments); \ + } \ + void GetBytesInUse(gin::Arguments* arguments) { \ + storage_area_.HandleFunctionCall("getBytesInUse", arguments); \ + } \ + v8::Local<v8::Value> GetOnChangedEvent(gin::Arguments* arguments) { \ + v8::Isolate* isolate = arguments->isolate(); \ + v8::Local<v8::Context> context = arguments->GetHolderCreationContext(); \ + v8::Local<v8::Object> wrapper = GetWrapper(isolate).ToLocalChecked(); \ + return storage_area_.GetOnChangedEvent(isolate, context, wrapper); \ } // gin::Wrappables for each of the storage areas. Since each has slightly @@ -45,9 +52,14 @@ class LocalStorageArea final : public gin::Wrappable<LocalStorageArea> { public: LocalStorageArea(APIRequestHandler* request_handler, + APIEventHandler* event_handler, const APITypeReferenceMap* type_refs, const BindingAccessChecker* access_checker) - : storage_area_(request_handler, type_refs, "local", access_checker) {} + : storage_area_(request_handler, + event_handler, + type_refs, + "local", + access_checker) {} ~LocalStorageArea() override = default; static gin::WrapperInfo kWrapperInfo; @@ -60,6 +72,7 @@ .SetMethod("remove", &LocalStorageArea::Remove) .SetMethod("clear", &LocalStorageArea::Clear) .SetMethod("getBytesInUse", &LocalStorageArea::GetBytesInUse) + .SetProperty("onChanged", &LocalStorageArea::GetOnChangedEvent) .SetValue("QUOTA_BYTES", api::storage::local::QUOTA_BYTES); } @@ -76,9 +89,14 @@ class SyncStorageArea final : public gin::Wrappable<SyncStorageArea> { public: SyncStorageArea(APIRequestHandler* request_handler, + APIEventHandler* event_handler, const APITypeReferenceMap* type_refs, const BindingAccessChecker* access_checker) - : storage_area_(request_handler, type_refs, "sync", access_checker) {} + : storage_area_(request_handler, + event_handler, + type_refs, + "sync", + access_checker) {} ~SyncStorageArea() override = default; static gin::WrapperInfo kWrapperInfo; @@ -91,6 +109,7 @@ .SetMethod("remove", &SyncStorageArea::Remove) .SetMethod("clear", &SyncStorageArea::Clear) .SetMethod("getBytesInUse", &SyncStorageArea::GetBytesInUse) + .SetProperty("onChanged", &SyncStorageArea::GetOnChangedEvent) .SetValue("QUOTA_BYTES", api::storage::sync::QUOTA_BYTES) .SetValue("QUOTA_BYTES_PER_ITEM", api::storage::sync::QUOTA_BYTES_PER_ITEM) @@ -117,9 +136,14 @@ class ManagedStorageArea final : public gin::Wrappable<ManagedStorageArea> { public: ManagedStorageArea(APIRequestHandler* request_handler, + APIEventHandler* event_handler, const APITypeReferenceMap* type_refs, const BindingAccessChecker* access_checker) - : storage_area_(request_handler, type_refs, "managed", access_checker) {} + : storage_area_(request_handler, + event_handler, + type_refs, + "managed", + access_checker) {} ~ManagedStorageArea() override = default; static gin::WrapperInfo kWrapperInfo; @@ -131,7 +155,8 @@ .SetMethod("set", &ManagedStorageArea::Set) .SetMethod("remove", &ManagedStorageArea::Remove) .SetMethod("clear", &ManagedStorageArea::Clear) - .SetMethod("getBytesInUse", &ManagedStorageArea::GetBytesInUse); + .SetMethod("getBytesInUse", &ManagedStorageArea::GetBytesInUse) + .SetProperty("onChanged", &ManagedStorageArea::GetOnChangedEvent); } private: @@ -149,10 +174,12 @@ } // namespace StorageArea::StorageArea(APIRequestHandler* request_handler, + APIEventHandler* event_handler, const APITypeReferenceMap* type_refs, const std::string& name, const BindingAccessChecker* access_checker) : request_handler_(request_handler), + event_handler_(event_handler), type_refs_(type_refs), name_(name), access_checker_(access_checker) {} @@ -170,19 +197,19 @@ v8::Local<v8::Object> object; if (property_name == "local") { gin::Handle<LocalStorageArea> handle = gin::CreateHandle( - isolate, - new LocalStorageArea(request_handler, type_refs, access_checker)); + isolate, new LocalStorageArea(request_handler, event_handler, type_refs, + access_checker)); object = handle.ToV8().As<v8::Object>(); } else if (property_name == "sync") { gin::Handle<SyncStorageArea> handle = gin::CreateHandle( - isolate, - new SyncStorageArea(request_handler, type_refs, access_checker)); + isolate, new SyncStorageArea(request_handler, event_handler, type_refs, + access_checker)); object = handle.ToV8().As<v8::Object>(); } else { CHECK_EQ("managed", property_name); gin::Handle<ManagedStorageArea> handle = gin::CreateHandle( - isolate, - new ManagedStorageArea(request_handler, type_refs, access_checker)); + isolate, new ManagedStorageArea(request_handler, event_handler, + type_refs, access_checker)); object = handle.ToV8().As<v8::Object>(); } return object; @@ -225,4 +252,36 @@ v8::Local<v8::Function>(), binding::RequestThread::UI); } +v8::Local<v8::Value> StorageArea::GetOnChangedEvent( + v8::Isolate* isolate, + v8::Local<v8::Context> context, + v8::Local<v8::Object> wrapper) { + if (!binding::IsContextValidOrThrowError(context)) + return v8::Undefined(isolate); + + v8::Local<v8::Private> key = v8::Private::ForApi( + isolate, gin::StringToSymbol(isolate, "onChangedEvent")); + v8::Local<v8::Value> event; + if (!wrapper->GetPrivate(context, key).ToLocal(&event)) { + NOTREACHED(); + return v8::Local<v8::Value>(); + } + + DCHECK(!event.IsEmpty()); + if (event->IsUndefined()) { + constexpr bool kSupportsFilters = false; + constexpr bool kSupportsLazyListeners = true; + event = event_handler_->CreateEventInstance( + base::StringPrintf("storage.%s.onChanged", name_.c_str()), + kSupportsFilters, kSupportsLazyListeners, binding::kNoListenerMax, true, + context); + v8::Maybe<bool> set_result = wrapper->SetPrivate(context, key, event); + if (!set_result.IsJust() || !set_result.FromJust()) { + NOTREACHED(); + return v8::Local<v8::Value>(); + } + } + return event; +} + } // namespace extensions
diff --git a/extensions/renderer/storage_area.h b/extensions/renderer/storage_area.h index e37e28c4..cf16374 100644 --- a/extensions/renderer/storage_area.h +++ b/extensions/renderer/storage_area.h
@@ -30,6 +30,7 @@ class StorageArea { public: StorageArea(APIRequestHandler* request_handler, + APIEventHandler* event_handler, const APITypeReferenceMap* type_refs, const std::string& name, const BindingAccessChecker* access_checker); @@ -48,9 +49,15 @@ void HandleFunctionCall(const std::string& method_name, gin::Arguments* arguments); + v8::Local<v8::Value> GetOnChangedEvent(v8::Isolate* isolate, + v8::Local<v8::Context> context, + v8::Local<v8::Object> wrapper); + private: APIRequestHandler* request_handler_; + APIEventHandler* event_handler_; + const APITypeReferenceMap* type_refs_; std::string name_;
diff --git a/extensions/renderer/storage_area_unittest.cc b/extensions/renderer/storage_area_unittest.cc index c955d242..7f3c404 100644 --- a/extensions/renderer/storage_area_unittest.cc +++ b/extensions/renderer/storage_area_unittest.cc
@@ -4,6 +4,7 @@ #include "extensions/renderer/storage_area.h" +#include "base/strings/stringprintf.h" #include "extensions/common/extension_builder.h" #include "extensions/renderer/bindings/api_binding_test_util.h" #include "extensions/renderer/bindings/api_binding_util.h" @@ -111,4 +112,41 @@ "No matching signature.")); } +TEST_F(StorageAreaTest, HasOnChanged) { + scoped_refptr<const Extension> extension = + ExtensionBuilder("foo").AddPermission("storage").Build(); + RegisterExtension(extension); + + v8::HandleScope handle_scope(isolate()); + v8::Local<v8::Context> context = MainContext(); + + ScriptContext* script_context = CreateScriptContext( + context, extension.get(), Feature::BLESSED_EXTENSION_CONTEXT); + script_context->set_url(extension->url()); + + bindings_system()->UpdateBindingsForContext(script_context); + + const char* kStorages[] = {"sync", "local", "managed"}; + for (size_t i = 0; i < base::size(kStorages); ++i) { + const std::string kRegisterListener = base::StringPrintf( + R"((function() { + chrome.storage.%s.onChanged.addListener( + function(change) { + this.change = change; + }); + }))", + kStorages[i]); + v8::Local<v8::Function> add_listener = + FunctionFromString(context, kRegisterListener); + RunFunctionOnGlobal(add_listener, context, 0, nullptr); + + bindings_system()->DispatchEventInContext( + base::StringPrintf("storage.%s.onChanged", kStorages[i]).c_str(), + ListValueFromString("['foo']").get(), nullptr, script_context); + + EXPECT_EQ("\"foo\"", GetStringPropertyFromObject(context->Global(), context, + "change")); + } +} + } // namespace extensions
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn index 7fe6fe0c..9bc19c2 100644 --- a/gpu/BUILD.gn +++ b/gpu/BUILD.gn
@@ -216,7 +216,6 @@ "command_buffer/tests/gl_ext_multisample_compatibility_unittest.cc", "command_buffer/tests/gl_ext_srgb_unittest.cc", "command_buffer/tests/gl_ext_window_rectangles_unittest.cc", - "command_buffer/tests/gl_fence_sync_unittest.cc", "command_buffer/tests/gl_gpu_memory_buffer_unittest.cc", "command_buffer/tests/gl_iosurface_readback_workaround_unittest.cc", "command_buffer/tests/gl_lose_context_chromium_unittest.cc", @@ -441,6 +440,7 @@ "ipc/service/gpu_channel_test_common.cc", "ipc/service/gpu_channel_test_common.h", "ipc/service/gpu_channel_unittest.cc", + "ipc/service/image_decode_accelerator_stub_unittest.cc", ] if (is_mac) { @@ -505,6 +505,7 @@ "//gpu/command_buffer/common", "//gpu/command_buffer/common:gles2_utils", "//gpu/command_buffer/service", + "//gpu/config", "//gpu/ipc:gl_in_process_context", "//gpu/ipc/client", "//gpu/ipc/common",
diff --git a/gpu/command_buffer/build_gles2_cmd_buffer.py b/gpu/command_buffer/build_gles2_cmd_buffer.py index 7dedd679..c740f9d 100755 --- a/gpu/command_buffer/build_gles2_cmd_buffer.py +++ b/gpu/command_buffer/build_gles2_cmd_buffer.py
@@ -3804,12 +3804,7 @@ 'extension': "CHROMIUM_sync_point", }, 'WaitSyncTokenCHROMIUM': { - 'type': 'Custom', - 'impl_func': False, - 'cmd_args': 'GLint namespace_id, ' - 'GLuint64 command_buffer_id, ' - 'GLuint64 release_count', - 'client_test': False, + 'type': 'NoCommand', 'extension': "CHROMIUM_sync_point", }, 'DiscardBackbufferCHROMIUM': {
diff --git a/gpu/command_buffer/build_raster_cmd_buffer.py b/gpu/command_buffer/build_raster_cmd_buffer.py index 6411c46..6e1c08c 100755 --- a/gpu/command_buffer/build_raster_cmd_buffer.py +++ b/gpu/command_buffer/build_raster_cmd_buffer.py
@@ -360,12 +360,7 @@ 'type': 'NoCommand', }, 'WaitSyncTokenCHROMIUM': { - 'type': 'Custom', - 'impl_func': False, - 'cmd_args': 'GLint namespace_id, ' - 'GLuint64 command_buffer_id, ' - 'GLuint64 release_count', - 'client_test': False, + 'type': 'NoCommand', }, 'InitializeDiscardableTextureCHROMIUM': { 'type': 'Custom',
diff --git a/gpu/command_buffer/client/client_test_helper.h b/gpu/command_buffer/client/client_test_helper.h index bdf51f95..462298fa 100644 --- a/gpu/command_buffer/client/client_test_helper.h +++ b/gpu/command_buffer/client/client_test_helper.h
@@ -134,7 +134,7 @@ DoSignalSyncToken(sync_token, &callback); } - MOCK_METHOD1(WaitSyncTokenHint, void(const SyncToken&)); + MOCK_METHOD1(WaitSyncToken, void(const SyncToken&)); MOCK_METHOD1(CanWaitUnverifiedSyncToken, bool(const SyncToken&)); MOCK_METHOD2(CreateGpuFence, void(uint32_t gpu_fence_id, ClientGpuFence source));
diff --git a/gpu/command_buffer/client/gles2_cmd_helper_autogen.h b/gpu/command_buffer/client/gles2_cmd_helper_autogen.h index dc2f2d47..828846a 100644 --- a/gpu/command_buffer/client/gles2_cmd_helper_autogen.h +++ b/gpu/command_buffer/client/gles2_cmd_helper_autogen.h
@@ -2798,16 +2798,6 @@ } } -void WaitSyncTokenCHROMIUM(GLint namespace_id, - GLuint64 command_buffer_id, - GLuint64 release_count) { - gles2::cmds::WaitSyncTokenCHROMIUM* c = - GetCmdSpace<gles2::cmds::WaitSyncTokenCHROMIUM>(); - if (c) { - c->Init(namespace_id, command_buffer_id, release_count); - } -} - void UnpremultiplyAndDitherCopyCHROMIUM(GLuint source_id, GLuint dest_id, GLint x,
diff --git a/gpu/command_buffer/client/gles2_implementation.cc b/gpu/command_buffer/client/gles2_implementation.cc index 170291e..b09114e 100644 --- a/gpu/command_buffer/client/gles2_implementation.cc +++ b/gpu/command_buffer/client/gles2_implementation.cc
@@ -6507,14 +6507,9 @@ return; } - helper_->WaitSyncTokenCHROMIUM( - static_cast<GLint>(sync_token.namespace_id()), - sync_token.command_buffer_id().GetUnsafeValue(), - sync_token.release_count()); - // Enqueue sync token in flush after inserting command so that it's not // included in an automatic flush. - gpu_control_->WaitSyncTokenHint(verified_sync_token); + gpu_control_->WaitSyncToken(verified_sync_token); } namespace {
diff --git a/gpu/command_buffer/client/gles2_implementation_unittest.cc b/gpu/command_buffer/client/gles2_implementation_unittest.cc index a81ef36d..bedd663 100644 --- a/gpu/command_buffer/client/gles2_implementation_unittest.cc +++ b/gpu/command_buffer/client/gles2_implementation_unittest.cc
@@ -3981,12 +3981,9 @@ struct Cmds { cmds::InsertFenceSyncCHROMIUM insert_fence_sync; - cmds::WaitSyncTokenCHROMIUM wait_sync_token; }; Cmds expected; expected.insert_fence_sync.Init(kFenceSync); - expected.wait_sync_token.Init(kNamespaceId, kCommandBufferId.GetUnsafeValue(), - kFenceSync); EXPECT_CALL(*gpu_control_, GetNamespaceID()).WillOnce(Return(kNamespaceId)); EXPECT_CALL(*gpu_control_, GetCommandBufferID()) @@ -3996,7 +3993,7 @@ EXPECT_CALL(*gpu_control_, EnsureWorkVisible()); gl_->GenSyncTokenCHROMIUM(sync_token_data); - EXPECT_CALL(*gpu_control_, WaitSyncTokenHint(sync_token)); + EXPECT_CALL(*gpu_control_, WaitSyncToken(sync_token)); gl_->WaitSyncTokenCHROMIUM(sync_token_data); EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected))); }
diff --git a/gpu/command_buffer/client/gpu_control.h b/gpu/command_buffer/client/gpu_control.h index dc40d19..61c8c34 100644 --- a/gpu/command_buffer/client/gpu_control.h +++ b/gpu/command_buffer/client/gpu_control.h
@@ -104,11 +104,9 @@ base::OnceClosure callback) = 0; // This allows the command buffer proxy to mark the next flush with sync token - // dependencies for the gpu scheduler. This is used in addition to the - // WaitSyncToken command in the command buffer which is still needed. For - // example, the WaitSyncToken command is used to pull texture updates when - // used in conjunction with MailboxManagerSync. - virtual void WaitSyncTokenHint(const SyncToken& sync_token) = 0; + // dependencies for the gpu scheduler, or to block prior to the flush in case + // of android webview. + virtual void WaitSyncToken(const SyncToken& sync_token) = 0; // Under some circumstances a sync token may be used which has not been // verified to have been flushed. For example, fence syncs queued on the same
diff --git a/gpu/command_buffer/client/raster_cmd_helper_autogen.h b/gpu/command_buffer/client/raster_cmd_helper_autogen.h index a95e987f..6eb1d98 100644 --- a/gpu/command_buffer/client/raster_cmd_helper_autogen.h +++ b/gpu/command_buffer/client/raster_cmd_helper_autogen.h
@@ -94,16 +94,6 @@ } } -void WaitSyncTokenCHROMIUM(GLint namespace_id, - GLuint64 command_buffer_id, - GLuint64 release_count) { - raster::cmds::WaitSyncTokenCHROMIUM* c = - GetCmdSpace<raster::cmds::WaitSyncTokenCHROMIUM>(); - if (c) { - c->Init(namespace_id, command_buffer_id, release_count); - } -} - void BeginRasterCHROMIUMImmediate(GLuint sk_color, GLuint msaa_sample_count, GLboolean can_use_lcd_text,
diff --git a/gpu/command_buffer/client/raster_implementation.cc b/gpu/command_buffer/client/raster_implementation.cc index d643822e..6379c585 100644 --- a/gpu/command_buffer/client/raster_implementation.cc +++ b/gpu/command_buffer/client/raster_implementation.cc
@@ -957,14 +957,7 @@ return; } - helper_->WaitSyncTokenCHROMIUM( - static_cast<GLint>(sync_token.namespace_id()), - sync_token.command_buffer_id().GetUnsafeValue(), - sync_token.release_count()); - - // Enqueue sync token in flush after inserting command so that it's not - // included in an automatic flush. - gpu_control_->WaitSyncTokenHint(verified_sync_token); + gpu_control_->WaitSyncToken(verified_sync_token); } void* RasterImplementation::MapRasterCHROMIUM(GLsizeiptr size) {
diff --git a/gpu/command_buffer/client/raster_implementation_unittest.cc b/gpu/command_buffer/client/raster_implementation_unittest.cc index e99f5449..d75d844 100644 --- a/gpu/command_buffer/client/raster_implementation_unittest.cc +++ b/gpu/command_buffer/client/raster_implementation_unittest.cc
@@ -712,12 +712,9 @@ struct Cmds { cmds::InsertFenceSyncCHROMIUM insert_fence_sync; - cmds::WaitSyncTokenCHROMIUM wait_sync_token; }; Cmds expected; expected.insert_fence_sync.Init(kFenceSync); - expected.wait_sync_token.Init(kNamespaceId, kCommandBufferId.GetUnsafeValue(), - kFenceSync); EXPECT_CALL(*gpu_control_, GetNamespaceID()).WillOnce(Return(kNamespaceId)); EXPECT_CALL(*gpu_control_, GetCommandBufferID()) @@ -727,7 +724,7 @@ EXPECT_CALL(*gpu_control_, EnsureWorkVisible()); gl_->GenSyncTokenCHROMIUM(sync_token_data); - EXPECT_CALL(*gpu_control_, WaitSyncTokenHint(sync_token)); + EXPECT_CALL(*gpu_control_, WaitSyncToken(sync_token)); gl_->WaitSyncTokenCHROMIUM(sync_token_data); EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected))); }
diff --git a/gpu/command_buffer/client/shared_image_interface.h b/gpu/command_buffer/client/shared_image_interface.h index 32d45a9..fa1f803 100644 --- a/gpu/command_buffer/client/shared_image_interface.h +++ b/gpu/command_buffer/client/shared_image_interface.h
@@ -6,6 +6,7 @@ #define GPU_COMMAND_BUFFER_CLIENT_SHARED_IMAGE_INTERFACE_H_ #include "base/compiler_specific.h" +#include "base/containers/span.h" #include "components/viz/common/resources/resource_format.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/sync_token.h" @@ -44,6 +45,16 @@ const gfx::ColorSpace& color_space, uint32_t usage) = 0; + // Same behavior as the above, except that this version takes |pixel_data| + // which is used to populate the SharedImage. |pixel_data| should have the + // same format which would be passed to glTexImage2D to populate a similarly + // specified texture. + virtual Mailbox CreateSharedImage(viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) = 0; + // Creates a shared image out of a GpuMemoryBuffer, using |color_space|. // |usage| is a combination of |SharedImageUsage| bits that describes which // API(s) the image will be used with. Format and size are derived from the
diff --git a/gpu/command_buffer/common/gles2_cmd_format_autogen.h b/gpu/command_buffer/common/gles2_cmd_format_autogen.h index d9fefe3..58f64e8d 100644 --- a/gpu/command_buffer/common/gles2_cmd_format_autogen.h +++ b/gpu/command_buffer/common/gles2_cmd_format_autogen.h
@@ -13851,73 +13851,6 @@ static_assert(offsetof(InsertFenceSyncCHROMIUM, release_count_1) == 8, "offset of InsertFenceSyncCHROMIUM release_count_1 should be 8"); -struct WaitSyncTokenCHROMIUM { - typedef WaitSyncTokenCHROMIUM ValueType; - static const CommandId kCmdId = kWaitSyncTokenCHROMIUM; - static const cmd::ArgFlags kArgFlags = cmd::kFixed; - static const uint8_t cmd_flags = CMD_FLAG_SET_TRACE_LEVEL(3); - - static uint32_t ComputeSize() { - return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT - } - - void SetHeader() { header.SetCmd<ValueType>(); } - - void Init(GLint _namespace_id, - GLuint64 _command_buffer_id, - GLuint64 _release_count) { - SetHeader(); - namespace_id = _namespace_id; - GLES2Util::MapUint64ToTwoUint32(static_cast<uint64_t>(_command_buffer_id), - &command_buffer_id_0, &command_buffer_id_1); - GLES2Util::MapUint64ToTwoUint32(static_cast<uint64_t>(_release_count), - &release_count_0, &release_count_1); - } - - void* Set(void* cmd, - GLint _namespace_id, - GLuint64 _command_buffer_id, - GLuint64 _release_count) { - static_cast<ValueType*>(cmd)->Init(_namespace_id, _command_buffer_id, - _release_count); - return NextCmdAddress<ValueType>(cmd); - } - - GLuint64 command_buffer_id() const volatile { - return static_cast<GLuint64>(GLES2Util::MapTwoUint32ToUint64( - command_buffer_id_0, command_buffer_id_1)); - } - - GLuint64 release_count() const volatile { - return static_cast<GLuint64>( - GLES2Util::MapTwoUint32ToUint64(release_count_0, release_count_1)); - } - - gpu::CommandHeader header; - int32_t namespace_id; - uint32_t command_buffer_id_0; - uint32_t command_buffer_id_1; - uint32_t release_count_0; - uint32_t release_count_1; -}; - -static_assert(sizeof(WaitSyncTokenCHROMIUM) == 24, - "size of WaitSyncTokenCHROMIUM should be 24"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, header) == 0, - "offset of WaitSyncTokenCHROMIUM header should be 0"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, namespace_id) == 4, - "offset of WaitSyncTokenCHROMIUM namespace_id should be 4"); -static_assert( - offsetof(WaitSyncTokenCHROMIUM, command_buffer_id_0) == 8, - "offset of WaitSyncTokenCHROMIUM command_buffer_id_0 should be 8"); -static_assert( - offsetof(WaitSyncTokenCHROMIUM, command_buffer_id_1) == 12, - "offset of WaitSyncTokenCHROMIUM command_buffer_id_1 should be 12"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, release_count_0) == 16, - "offset of WaitSyncTokenCHROMIUM release_count_0 should be 16"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, release_count_1) == 20, - "offset of WaitSyncTokenCHROMIUM release_count_1 should be 20"); - struct UnpremultiplyAndDitherCopyCHROMIUM { typedef UnpremultiplyAndDitherCopyCHROMIUM ValueType; static const CommandId kCmdId = kUnpremultiplyAndDitherCopyCHROMIUM;
diff --git a/gpu/command_buffer/common/gles2_cmd_format_test_autogen.h b/gpu/command_buffer/common/gles2_cmd_format_test_autogen.h index c092c1c..84d7ce4 100644 --- a/gpu/command_buffer/common/gles2_cmd_format_test_autogen.h +++ b/gpu/command_buffer/common/gles2_cmd_format_test_autogen.h
@@ -4636,21 +4636,6 @@ CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); } -TEST_F(GLES2FormatTest, WaitSyncTokenCHROMIUM) { - cmds::WaitSyncTokenCHROMIUM& cmd = - *GetBufferAs<cmds::WaitSyncTokenCHROMIUM>(); - void* next_cmd = - cmd.Set(&cmd, static_cast<GLint>(11), static_cast<GLuint64>(12), - static_cast<GLuint64>(13)); - EXPECT_EQ(static_cast<uint32_t>(cmds::WaitSyncTokenCHROMIUM::kCmdId), - cmd.header.command); - EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u); - EXPECT_EQ(static_cast<GLint>(11), cmd.namespace_id); - EXPECT_EQ(static_cast<GLuint64>(12), cmd.command_buffer_id()); - EXPECT_EQ(static_cast<GLuint64>(13), cmd.release_count()); - CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); -} - TEST_F(GLES2FormatTest, UnpremultiplyAndDitherCopyCHROMIUM) { cmds::UnpremultiplyAndDitherCopyCHROMIUM& cmd = *GetBufferAs<cmds::UnpremultiplyAndDitherCopyCHROMIUM>();
diff --git a/gpu/command_buffer/common/gles2_cmd_ids_autogen.h b/gpu/command_buffer/common/gles2_cmd_ids_autogen.h index 4b79206..61b3de1 100644 --- a/gpu/command_buffer/common/gles2_cmd_ids_autogen.h +++ b/gpu/command_buffer/common/gles2_cmd_ids_autogen.h
@@ -294,67 +294,66 @@ OP(DiscardFramebufferEXTImmediate) /* 535 */ \ OP(LoseContextCHROMIUM) /* 536 */ \ OP(InsertFenceSyncCHROMIUM) /* 537 */ \ - OP(WaitSyncTokenCHROMIUM) /* 538 */ \ - OP(UnpremultiplyAndDitherCopyCHROMIUM) /* 539 */ \ - OP(DrawBuffersEXTImmediate) /* 540 */ \ - OP(DiscardBackbufferCHROMIUM) /* 541 */ \ - OP(ScheduleOverlayPlaneCHROMIUM) /* 542 */ \ - OP(ScheduleCALayerSharedStateCHROMIUM) /* 543 */ \ - OP(ScheduleCALayerCHROMIUM) /* 544 */ \ - OP(ScheduleCALayerInUseQueryCHROMIUMImmediate) /* 545 */ \ - OP(CommitOverlayPlanesCHROMIUM) /* 546 */ \ - OP(FlushDriverCachesCHROMIUM) /* 547 */ \ - OP(ScheduleDCLayerCHROMIUM) /* 548 */ \ - OP(SetActiveURLCHROMIUM) /* 549 */ \ - OP(MatrixLoadfCHROMIUMImmediate) /* 550 */ \ - OP(MatrixLoadIdentityCHROMIUM) /* 551 */ \ - OP(GenPathsCHROMIUM) /* 552 */ \ - OP(DeletePathsCHROMIUM) /* 553 */ \ - OP(IsPathCHROMIUM) /* 554 */ \ - OP(PathCommandsCHROMIUM) /* 555 */ \ - OP(PathParameterfCHROMIUM) /* 556 */ \ - OP(PathParameteriCHROMIUM) /* 557 */ \ - OP(PathStencilFuncCHROMIUM) /* 558 */ \ - OP(StencilFillPathCHROMIUM) /* 559 */ \ - OP(StencilStrokePathCHROMIUM) /* 560 */ \ - OP(CoverFillPathCHROMIUM) /* 561 */ \ - OP(CoverStrokePathCHROMIUM) /* 562 */ \ - OP(StencilThenCoverFillPathCHROMIUM) /* 563 */ \ - OP(StencilThenCoverStrokePathCHROMIUM) /* 564 */ \ - OP(StencilFillPathInstancedCHROMIUM) /* 565 */ \ - OP(StencilStrokePathInstancedCHROMIUM) /* 566 */ \ - OP(CoverFillPathInstancedCHROMIUM) /* 567 */ \ - OP(CoverStrokePathInstancedCHROMIUM) /* 568 */ \ - OP(StencilThenCoverFillPathInstancedCHROMIUM) /* 569 */ \ - OP(StencilThenCoverStrokePathInstancedCHROMIUM) /* 570 */ \ - OP(BindFragmentInputLocationCHROMIUMBucket) /* 571 */ \ - OP(ProgramPathFragmentInputGenCHROMIUM) /* 572 */ \ - OP(CoverageModulationCHROMIUM) /* 573 */ \ - OP(BlendBarrierKHR) /* 574 */ \ - OP(ApplyScreenSpaceAntialiasingCHROMIUM) /* 575 */ \ - OP(BindFragDataLocationIndexedEXTBucket) /* 576 */ \ - OP(BindFragDataLocationEXTBucket) /* 577 */ \ - OP(GetFragDataIndexEXT) /* 578 */ \ - OP(UniformMatrix4fvStreamTextureMatrixCHROMIUMImmediate) /* 579 */ \ - OP(OverlayPromotionHintCHROMIUM) /* 580 */ \ - OP(SwapBuffersWithBoundsCHROMIUMImmediate) /* 581 */ \ - OP(SetDrawRectangleCHROMIUM) /* 582 */ \ - OP(SetEnableDCLayersCHROMIUM) /* 583 */ \ - OP(InitializeDiscardableTextureCHROMIUM) /* 584 */ \ - OP(UnlockDiscardableTextureCHROMIUM) /* 585 */ \ - OP(LockDiscardableTextureCHROMIUM) /* 586 */ \ - OP(TexStorage2DImageCHROMIUM) /* 587 */ \ - OP(SetColorSpaceMetadataCHROMIUM) /* 588 */ \ - OP(WindowRectanglesEXTImmediate) /* 589 */ \ - OP(CreateGpuFenceINTERNAL) /* 590 */ \ - OP(WaitGpuFenceCHROMIUM) /* 591 */ \ - OP(DestroyGpuFenceCHROMIUM) /* 592 */ \ - OP(SetReadbackBufferShadowAllocationINTERNAL) /* 593 */ \ - OP(FramebufferTextureMultiviewLayeredANGLE) /* 594 */ \ - OP(MaxShaderCompilerThreadsKHR) /* 595 */ \ - OP(CreateAndTexStorage2DSharedImageINTERNALImmediate) /* 596 */ \ - OP(BeginSharedImageAccessDirectCHROMIUM) /* 597 */ \ - OP(EndSharedImageAccessDirectCHROMIUM) /* 598 */ + OP(UnpremultiplyAndDitherCopyCHROMIUM) /* 538 */ \ + OP(DrawBuffersEXTImmediate) /* 539 */ \ + OP(DiscardBackbufferCHROMIUM) /* 540 */ \ + OP(ScheduleOverlayPlaneCHROMIUM) /* 541 */ \ + OP(ScheduleCALayerSharedStateCHROMIUM) /* 542 */ \ + OP(ScheduleCALayerCHROMIUM) /* 543 */ \ + OP(ScheduleCALayerInUseQueryCHROMIUMImmediate) /* 544 */ \ + OP(CommitOverlayPlanesCHROMIUM) /* 545 */ \ + OP(FlushDriverCachesCHROMIUM) /* 546 */ \ + OP(ScheduleDCLayerCHROMIUM) /* 547 */ \ + OP(SetActiveURLCHROMIUM) /* 548 */ \ + OP(MatrixLoadfCHROMIUMImmediate) /* 549 */ \ + OP(MatrixLoadIdentityCHROMIUM) /* 550 */ \ + OP(GenPathsCHROMIUM) /* 551 */ \ + OP(DeletePathsCHROMIUM) /* 552 */ \ + OP(IsPathCHROMIUM) /* 553 */ \ + OP(PathCommandsCHROMIUM) /* 554 */ \ + OP(PathParameterfCHROMIUM) /* 555 */ \ + OP(PathParameteriCHROMIUM) /* 556 */ \ + OP(PathStencilFuncCHROMIUM) /* 557 */ \ + OP(StencilFillPathCHROMIUM) /* 558 */ \ + OP(StencilStrokePathCHROMIUM) /* 559 */ \ + OP(CoverFillPathCHROMIUM) /* 560 */ \ + OP(CoverStrokePathCHROMIUM) /* 561 */ \ + OP(StencilThenCoverFillPathCHROMIUM) /* 562 */ \ + OP(StencilThenCoverStrokePathCHROMIUM) /* 563 */ \ + OP(StencilFillPathInstancedCHROMIUM) /* 564 */ \ + OP(StencilStrokePathInstancedCHROMIUM) /* 565 */ \ + OP(CoverFillPathInstancedCHROMIUM) /* 566 */ \ + OP(CoverStrokePathInstancedCHROMIUM) /* 567 */ \ + OP(StencilThenCoverFillPathInstancedCHROMIUM) /* 568 */ \ + OP(StencilThenCoverStrokePathInstancedCHROMIUM) /* 569 */ \ + OP(BindFragmentInputLocationCHROMIUMBucket) /* 570 */ \ + OP(ProgramPathFragmentInputGenCHROMIUM) /* 571 */ \ + OP(CoverageModulationCHROMIUM) /* 572 */ \ + OP(BlendBarrierKHR) /* 573 */ \ + OP(ApplyScreenSpaceAntialiasingCHROMIUM) /* 574 */ \ + OP(BindFragDataLocationIndexedEXTBucket) /* 575 */ \ + OP(BindFragDataLocationEXTBucket) /* 576 */ \ + OP(GetFragDataIndexEXT) /* 577 */ \ + OP(UniformMatrix4fvStreamTextureMatrixCHROMIUMImmediate) /* 578 */ \ + OP(OverlayPromotionHintCHROMIUM) /* 579 */ \ + OP(SwapBuffersWithBoundsCHROMIUMImmediate) /* 580 */ \ + OP(SetDrawRectangleCHROMIUM) /* 581 */ \ + OP(SetEnableDCLayersCHROMIUM) /* 582 */ \ + OP(InitializeDiscardableTextureCHROMIUM) /* 583 */ \ + OP(UnlockDiscardableTextureCHROMIUM) /* 584 */ \ + OP(LockDiscardableTextureCHROMIUM) /* 585 */ \ + OP(TexStorage2DImageCHROMIUM) /* 586 */ \ + OP(SetColorSpaceMetadataCHROMIUM) /* 587 */ \ + OP(WindowRectanglesEXTImmediate) /* 588 */ \ + OP(CreateGpuFenceINTERNAL) /* 589 */ \ + OP(WaitGpuFenceCHROMIUM) /* 590 */ \ + OP(DestroyGpuFenceCHROMIUM) /* 591 */ \ + OP(SetReadbackBufferShadowAllocationINTERNAL) /* 592 */ \ + OP(FramebufferTextureMultiviewLayeredANGLE) /* 593 */ \ + OP(MaxShaderCompilerThreadsKHR) /* 594 */ \ + OP(CreateAndTexStorage2DSharedImageINTERNALImmediate) /* 595 */ \ + OP(BeginSharedImageAccessDirectCHROMIUM) /* 596 */ \ + OP(EndSharedImageAccessDirectCHROMIUM) /* 597 */ enum CommandId { kOneBeforeStartPoint =
diff --git a/gpu/command_buffer/common/raster_cmd_format_autogen.h b/gpu/command_buffer/common/raster_cmd_format_autogen.h index ae0eba0..8cc5f03 100644 --- a/gpu/command_buffer/common/raster_cmd_format_autogen.h +++ b/gpu/command_buffer/common/raster_cmd_format_autogen.h
@@ -398,75 +398,6 @@ static_assert(offsetof(InsertFenceSyncCHROMIUM, release_count_1) == 8, "offset of InsertFenceSyncCHROMIUM release_count_1 should be 8"); -struct WaitSyncTokenCHROMIUM { - typedef WaitSyncTokenCHROMIUM ValueType; - static const CommandId kCmdId = kWaitSyncTokenCHROMIUM; - static const cmd::ArgFlags kArgFlags = cmd::kFixed; - static const uint8_t cmd_flags = CMD_FLAG_SET_TRACE_LEVEL(3); - - static uint32_t ComputeSize() { - return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT - } - - void SetHeader() { header.SetCmd<ValueType>(); } - - void Init(GLint _namespace_id, - GLuint64 _command_buffer_id, - GLuint64 _release_count) { - SetHeader(); - namespace_id = _namespace_id; - gles2::GLES2Util::MapUint64ToTwoUint32( - static_cast<uint64_t>(_command_buffer_id), &command_buffer_id_0, - &command_buffer_id_1); - gles2::GLES2Util::MapUint64ToTwoUint32( - static_cast<uint64_t>(_release_count), &release_count_0, - &release_count_1); - } - - void* Set(void* cmd, - GLint _namespace_id, - GLuint64 _command_buffer_id, - GLuint64 _release_count) { - static_cast<ValueType*>(cmd)->Init(_namespace_id, _command_buffer_id, - _release_count); - return NextCmdAddress<ValueType>(cmd); - } - - GLuint64 command_buffer_id() const volatile { - return static_cast<GLuint64>(gles2::GLES2Util::MapTwoUint32ToUint64( - command_buffer_id_0, command_buffer_id_1)); - } - - GLuint64 release_count() const volatile { - return static_cast<GLuint64>(gles2::GLES2Util::MapTwoUint32ToUint64( - release_count_0, release_count_1)); - } - - gpu::CommandHeader header; - int32_t namespace_id; - uint32_t command_buffer_id_0; - uint32_t command_buffer_id_1; - uint32_t release_count_0; - uint32_t release_count_1; -}; - -static_assert(sizeof(WaitSyncTokenCHROMIUM) == 24, - "size of WaitSyncTokenCHROMIUM should be 24"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, header) == 0, - "offset of WaitSyncTokenCHROMIUM header should be 0"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, namespace_id) == 4, - "offset of WaitSyncTokenCHROMIUM namespace_id should be 4"); -static_assert( - offsetof(WaitSyncTokenCHROMIUM, command_buffer_id_0) == 8, - "offset of WaitSyncTokenCHROMIUM command_buffer_id_0 should be 8"); -static_assert( - offsetof(WaitSyncTokenCHROMIUM, command_buffer_id_1) == 12, - "offset of WaitSyncTokenCHROMIUM command_buffer_id_1 should be 12"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, release_count_0) == 16, - "offset of WaitSyncTokenCHROMIUM release_count_0 should be 16"); -static_assert(offsetof(WaitSyncTokenCHROMIUM, release_count_1) == 20, - "offset of WaitSyncTokenCHROMIUM release_count_1 should be 20"); - struct BeginRasterCHROMIUMImmediate { typedef BeginRasterCHROMIUMImmediate ValueType; static const CommandId kCmdId = kBeginRasterCHROMIUMImmediate;
diff --git a/gpu/command_buffer/common/raster_cmd_format_test_autogen.h b/gpu/command_buffer/common/raster_cmd_format_test_autogen.h index 05a838d3..7b91c2a 100644 --- a/gpu/command_buffer/common/raster_cmd_format_test_autogen.h +++ b/gpu/command_buffer/common/raster_cmd_format_test_autogen.h
@@ -16,7 +16,9 @@ TEST_F(RasterFormatTest, DeleteTexturesImmediate) { static GLuint ids[] = { - 12, 23, 34, + 12, + 23, + 34, }; cmds::DeleteTexturesImmediate& cmd = *GetBufferAs<cmds::DeleteTexturesImmediate>(); @@ -61,7 +63,9 @@ TEST_F(RasterFormatTest, GenQueriesEXTImmediate) { static GLuint ids[] = { - 12, 23, 34, + 12, + 23, + 34, }; cmds::GenQueriesEXTImmediate& cmd = *GetBufferAs<cmds::GenQueriesEXTImmediate>(); @@ -79,7 +83,9 @@ TEST_F(RasterFormatTest, DeleteQueriesEXTImmediate) { static GLuint ids[] = { - 12, 23, 34, + 12, + 23, + 34, }; cmds::DeleteQueriesEXTImmediate& cmd = *GetBufferAs<cmds::DeleteQueriesEXTImmediate>(); @@ -145,21 +151,6 @@ CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); } -TEST_F(RasterFormatTest, WaitSyncTokenCHROMIUM) { - cmds::WaitSyncTokenCHROMIUM& cmd = - *GetBufferAs<cmds::WaitSyncTokenCHROMIUM>(); - void* next_cmd = - cmd.Set(&cmd, static_cast<GLint>(11), static_cast<GLuint64>(12), - static_cast<GLuint64>(13)); - EXPECT_EQ(static_cast<uint32_t>(cmds::WaitSyncTokenCHROMIUM::kCmdId), - cmd.header.command); - EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u); - EXPECT_EQ(static_cast<GLint>(11), cmd.namespace_id); - EXPECT_EQ(static_cast<GLuint64>(12), cmd.command_buffer_id()); - EXPECT_EQ(static_cast<GLuint64>(13), cmd.release_count()); - CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); -} - TEST_F(RasterFormatTest, BeginRasterCHROMIUMImmediate) { const int kSomeBaseValueToTestWith = 51; static GLbyte data[] = { @@ -277,7 +268,9 @@ TEST_F(RasterFormatTest, DeletePaintCacheTextBlobsINTERNALImmediate) { static GLuint ids[] = { - 12, 23, 34, + 12, + 23, + 34, }; cmds::DeletePaintCacheTextBlobsINTERNALImmediate& cmd = *GetBufferAs<cmds::DeletePaintCacheTextBlobsINTERNALImmediate>(); @@ -296,7 +289,9 @@ TEST_F(RasterFormatTest, DeletePaintCachePathsINTERNALImmediate) { static GLuint ids[] = { - 12, 23, 34, + 12, + 23, + 34, }; cmds::DeletePaintCachePathsINTERNALImmediate& cmd = *GetBufferAs<cmds::DeletePaintCachePathsINTERNALImmediate>();
diff --git a/gpu/command_buffer/common/raster_cmd_ids_autogen.h b/gpu/command_buffer/common/raster_cmd_ids_autogen.h index 626e2b04..c0d00ae 100644 --- a/gpu/command_buffer/common/raster_cmd_ids_autogen.h +++ b/gpu/command_buffer/common/raster_cmd_ids_autogen.h
@@ -22,21 +22,20 @@ OP(EndQueryEXT) /* 263 */ \ OP(LoseContextCHROMIUM) /* 264 */ \ OP(InsertFenceSyncCHROMIUM) /* 265 */ \ - OP(WaitSyncTokenCHROMIUM) /* 266 */ \ - OP(BeginRasterCHROMIUMImmediate) /* 267 */ \ - OP(RasterCHROMIUM) /* 268 */ \ - OP(EndRasterCHROMIUM) /* 269 */ \ - OP(CreateTransferCacheEntryINTERNAL) /* 270 */ \ - OP(DeleteTransferCacheEntryINTERNAL) /* 271 */ \ - OP(UnlockTransferCacheEntryINTERNAL) /* 272 */ \ - OP(DeletePaintCacheTextBlobsINTERNALImmediate) /* 273 */ \ - OP(DeletePaintCachePathsINTERNALImmediate) /* 274 */ \ - OP(ClearPaintCacheINTERNAL) /* 275 */ \ - OP(CreateAndConsumeTextureINTERNALImmediate) /* 276 */ \ - OP(CopySubTexture) /* 277 */ \ - OP(TraceBeginCHROMIUM) /* 278 */ \ - OP(TraceEndCHROMIUM) /* 279 */ \ - OP(SetActiveURLCHROMIUM) /* 280 */ + OP(BeginRasterCHROMIUMImmediate) /* 266 */ \ + OP(RasterCHROMIUM) /* 267 */ \ + OP(EndRasterCHROMIUM) /* 268 */ \ + OP(CreateTransferCacheEntryINTERNAL) /* 269 */ \ + OP(DeleteTransferCacheEntryINTERNAL) /* 270 */ \ + OP(UnlockTransferCacheEntryINTERNAL) /* 271 */ \ + OP(DeletePaintCacheTextBlobsINTERNALImmediate) /* 272 */ \ + OP(DeletePaintCachePathsINTERNALImmediate) /* 273 */ \ + OP(ClearPaintCacheINTERNAL) /* 274 */ \ + OP(CreateAndConsumeTextureINTERNALImmediate) /* 275 */ \ + OP(CopySubTexture) /* 276 */ \ + OP(TraceBeginCHROMIUM) /* 277 */ \ + OP(TraceEndCHROMIUM) /* 278 */ \ + OP(SetActiveURLCHROMIUM) /* 279 */ enum CommandId { kOneBeforeStartPoint =
diff --git a/gpu/command_buffer/service/command_buffer_direct.cc b/gpu/command_buffer/service/command_buffer_direct.cc index 8c7f861..03fd9a5 100644 --- a/gpu/command_buffer/service/command_buffer_direct.cc +++ b/gpu/command_buffer/service/command_buffer_direct.cc
@@ -6,7 +6,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" -#include "gpu/command_buffer/service/sync_point_manager.h" #include "gpu/command_buffer/service/transfer_buffer_manager.h" namespace gpu { @@ -19,37 +18,11 @@ CommandBufferDirect::CommandBufferDirect( TransferBufferManager* transfer_buffer_manager) - : CommandBufferDirect(transfer_buffer_manager, nullptr) {} - -CommandBufferDirect::CommandBufferDirect( - TransferBufferManager* transfer_buffer_manager, - SyncPointManager* sync_point_manager) : service_(this, transfer_buffer_manager), - sync_point_manager_(sync_point_manager), command_buffer_id_( - CommandBufferId::FromUnsafeValue(g_next_command_buffer_id++)) { - if (sync_point_manager_) { - sync_point_order_data_ = sync_point_manager_->CreateSyncPointOrderData(); - sync_point_client_state_ = sync_point_manager_->CreateSyncPointClientState( - GetNamespaceID(), GetCommandBufferID(), - sync_point_order_data_->sequence_id()); - } else { - sync_point_order_data_ = nullptr; - sync_point_client_state_ = nullptr; - } -} + CommandBufferId::FromUnsafeValue(g_next_command_buffer_id++)) {} -CommandBufferDirect::~CommandBufferDirect() { - sync_point_manager_ = nullptr; - if (sync_point_order_data_) { - sync_point_order_data_->Destroy(); - sync_point_order_data_ = nullptr; - } - if (sync_point_client_state_) { - sync_point_client_state_->Destroy(); - sync_point_client_state_ = nullptr; - } -} +CommandBufferDirect::~CommandBufferDirect() = default; CommandBuffer::State CommandBufferDirect::GetLastState() { service_.UpdateState(); @@ -76,32 +49,7 @@ void CommandBufferDirect::Flush(int32_t put_offset) { DCHECK(handler_); - uint32_t order_num = 0; - if (sync_point_manager_) { - // If sync point manager is supported, assign order numbers to commands. - if (paused_order_num_) { - // Was previous paused, continue to process the order number. - order_num = paused_order_num_; - paused_order_num_ = 0; - } else { - order_num = sync_point_order_data_->GenerateUnprocessedOrderNumber(); - } - sync_point_order_data_->BeginProcessingOrderNumber(order_num); - } - - if (pause_commands_) { - // Do not process commands, simply store the current order number. - paused_order_num_ = order_num; - - sync_point_order_data_->PauseProcessingOrderNumber(order_num); - return; - } - service_.Flush(put_offset, handler_); - if (sync_point_manager_) { - // Finish processing order number here. - sync_point_order_data_->FinishProcessingOrderNumber(order_num); - } } void CommandBufferDirect::OrderingBarrier(int32_t put_offset) { @@ -135,17 +83,7 @@ const std::string& shader) {} void CommandBufferDirect::OnFenceSyncRelease(uint64_t release) { - DCHECK(sync_point_client_state_); - service_.SetReleaseCount(release); - sync_point_client_state_->ReleaseFenceSync(release); -} - -bool CommandBufferDirect::OnWaitSyncToken(const gpu::SyncToken& sync_token) { - DCHECK(sync_point_manager_); - if (sync_point_manager_->IsSyncTokenReleased(sync_token)) - return false; - service_.SetScheduled(false); - return true; + NOTIMPLEMENTED(); } void CommandBufferDirect::OnDescheduleUntilFinished() { @@ -158,35 +96,6 @@ void CommandBufferDirect::OnSwapBuffers(uint64_t swap_id, uint32_t flags) {} -gpu::CommandBufferNamespace CommandBufferDirect::GetNamespaceID() const { - return gpu::CommandBufferNamespace::IN_PROCESS; -} - -CommandBufferId CommandBufferDirect::GetCommandBufferID() const { - return command_buffer_id_; -} - -void CommandBufferDirect::SetCommandsPaused(bool paused) { - pause_commands_ = paused; -} - -void CommandBufferDirect::SignalSyncToken(const gpu::SyncToken& sync_token, - base::OnceClosure callback) { - if (sync_point_manager_) { - DCHECK(!paused_order_num_); - uint32_t order_num = - sync_point_order_data_->GenerateUnprocessedOrderNumber(); - sync_point_order_data_->BeginProcessingOrderNumber(order_num); - base::RepeatingClosure maybe_pass_callback = - base::AdaptCallbackForRepeating(std::move(callback)); - if (!sync_point_client_state_->Wait(sync_token, maybe_pass_callback)) - maybe_pass_callback.Run(); - sync_point_order_data_->FinishProcessingOrderNumber(order_num); - } else { - std::move(callback).Run(); - } -} - scoped_refptr<Buffer> CommandBufferDirect::CreateTransferBufferWithId( size_t size, int32_t id) {
diff --git a/gpu/command_buffer/service/command_buffer_direct.h b/gpu/command_buffer/service/command_buffer_direct.h index 7897b08..0eec8e6 100644 --- a/gpu/command_buffer/service/command_buffer_direct.h +++ b/gpu/command_buffer/service/command_buffer_direct.h
@@ -16,10 +16,6 @@ class AsyncAPIInterface; class TransferBufferManager; -class SyncPointClientState; -class SyncPointManager; -class SyncPointOrderData; -struct SyncToken; class GPU_EXPORT CommandBufferDirect : public CommandBuffer, public CommandBufferServiceClient, @@ -27,10 +23,7 @@ public: using MakeCurrentCallback = base::Callback<bool()>; - CommandBufferDirect(TransferBufferManager* transfer_buffer_manager, - SyncPointManager* sync_point_manager); explicit CommandBufferDirect(TransferBufferManager* transfer_buffer_manager); - ~CommandBufferDirect() override; void set_handler(AsyncAPIInterface* handler) { handler_ = handler; } @@ -56,19 +49,11 @@ void OnConsoleMessage(int32_t id, const std::string& message) override; void CacheShader(const std::string& key, const std::string& shader) override; void OnFenceSyncRelease(uint64_t release) override; - bool OnWaitSyncToken(const gpu::SyncToken&) override; void OnDescheduleUntilFinished() override; void OnRescheduleAfterFinished() override; void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override; void ScheduleGrContextCleanup() override {} - CommandBufferNamespace GetNamespaceID() const; - CommandBufferId GetCommandBufferID() const; - - void SetCommandsPaused(bool paused); - void SignalSyncToken(const gpu::SyncToken& sync_token, - base::OnceClosure callback); - scoped_refptr<Buffer> CreateTransferBufferWithId(size_t size, int32_t id); void SetGetOffsetForTest(int32_t get_offset) { @@ -77,13 +62,7 @@ private: CommandBufferService service_; - SyncPointManager* sync_point_manager_; - AsyncAPIInterface* handler_ = nullptr; - scoped_refptr<SyncPointOrderData> sync_point_order_data_; - scoped_refptr<SyncPointClientState> sync_point_client_state_; - bool pause_commands_ = false; - uint32_t paused_order_num_ = 0; const CommandBufferId command_buffer_id_; };
diff --git a/gpu/command_buffer/service/decoder_client.h b/gpu/command_buffer/service/decoder_client.h index 4bdf653..66da71f 100644 --- a/gpu/command_buffer/service/decoder_client.h +++ b/gpu/command_buffer/service/decoder_client.h
@@ -14,8 +14,6 @@ namespace gpu { -struct SyncToken; - class GPU_EXPORT DecoderClient { public: virtual ~DecoderClient() = default; @@ -31,14 +29,6 @@ // reschedule waiting decoders. virtual void OnFenceSyncRelease(uint64_t release) = 0; - // Called when the decoder needs to wait on a sync token. If the wait is valid - // (fence sync is not released yet), the client must unschedule the command - // buffer and return true. The client is responsible for rescheduling the - // command buffer when the fence is released. If the wait is a noop (fence is - // already released) or invalid, the client must leave the command buffer - // scheduled, and return false. - virtual bool OnWaitSyncToken(const gpu::SyncToken&) = 0; - // Called when the decoder needs to be descheduled while waiting for a fence // completion. The client is responsible for descheduling the command buffer // before returning, and then calling PerformPollingWork periodically to test
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder.cc b/gpu/command_buffer/service/gles2_cmd_decoder.cc index 6ddbef4..c069827 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder.cc
@@ -16705,34 +16705,6 @@ return error::kNoError; } -error::Error GLES2DecoderImpl::HandleWaitSyncTokenCHROMIUM( - uint32_t immediate_data_size, - const volatile void* cmd_data) { - const volatile gles2::cmds::WaitSyncTokenCHROMIUM& c = - *static_cast<const volatile gles2::cmds::WaitSyncTokenCHROMIUM*>( - cmd_data); - - const gpu::CommandBufferNamespace kMinNamespaceId = - gpu::CommandBufferNamespace::INVALID; - const gpu::CommandBufferNamespace kMaxNamespaceId = - gpu::CommandBufferNamespace::NUM_COMMAND_BUFFER_NAMESPACES; - - gpu::CommandBufferNamespace namespace_id = - static_cast<gpu::CommandBufferNamespace>(c.namespace_id); - if ((namespace_id < static_cast<int32_t>(kMinNamespaceId)) || - (namespace_id >= static_cast<int32_t>(kMaxNamespaceId))) { - namespace_id = gpu::CommandBufferNamespace::INVALID; - } - const CommandBufferId command_buffer_id = - CommandBufferId::FromUnsafeValue(c.command_buffer_id()); - const uint64_t release = c.release_count(); - - gpu::SyncToken sync_token; - sync_token.Set(namespace_id, command_buffer_id, release); - return client_->OnWaitSyncToken(sync_token) ? error::kDeferCommandUntilLater - : error::kNoError; -} - error::Error GLES2DecoderImpl::HandleDiscardBackbufferCHROMIUM( uint32_t immediate_data_size, const volatile void* cmd_data) {
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 5c1cd278..0c5c3138 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc
@@ -4350,15 +4350,6 @@ return error::kNoError; } -error::Error GLES2DecoderPassthroughImpl::DoWaitSyncTokenCHROMIUM( - CommandBufferNamespace namespace_id, - CommandBufferId command_buffer_id, - GLuint64 release_count) { - SyncToken sync_token(namespace_id, command_buffer_id, release_count); - return client_->OnWaitSyncToken(sync_token) ? error::kDeferCommandUntilLater - : error::kNoError; -} - error::Error GLES2DecoderPassthroughImpl::DoDrawBuffersEXT( GLsizei count, const volatile GLenum* bufs) {
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers.cc index 5c0ff756..eb3165d7 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_handlers.cc
@@ -1893,31 +1893,6 @@ return DoInsertFenceSyncCHROMIUM(release_count); } -error::Error GLES2DecoderPassthroughImpl::HandleWaitSyncTokenCHROMIUM( - uint32_t immediate_data_size, - const volatile void* cmd_data) { - const volatile gles2::cmds::WaitSyncTokenCHROMIUM& c = - *static_cast<const volatile gles2::cmds::WaitSyncTokenCHROMIUM*>( - cmd_data); - CommandBufferNamespace namespace_id = - static_cast<gpu::CommandBufferNamespace>(c.namespace_id); - const uint64_t release_count = c.release_count(); - CommandBufferId command_buffer_id = - CommandBufferId::FromUnsafeValue(c.command_buffer_id()); - - const CommandBufferNamespace kMinNamespaceId = - CommandBufferNamespace::INVALID; - const CommandBufferNamespace kMaxNamespaceId = - CommandBufferNamespace::NUM_COMMAND_BUFFER_NAMESPACES; - if ((namespace_id < static_cast<int32_t>(kMinNamespaceId)) || - (namespace_id >= static_cast<int32_t>(kMaxNamespaceId))) { - namespace_id = gpu::CommandBufferNamespace::INVALID; - } - - return DoWaitSyncTokenCHROMIUM(namespace_id, command_buffer_id, - release_count); -} - error::Error GLES2DecoderPassthroughImpl::HandleDiscardBackbufferCHROMIUM( uint32_t immediate_data_size, const volatile void* cmd_data) {
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc index c3ba97e7..8ac4b41 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc
@@ -141,9 +141,6 @@ void GLES2DecoderTestBase::CacheShader(const std::string& key, const std::string& shader) {} void GLES2DecoderTestBase::OnFenceSyncRelease(uint64_t release) {} -bool GLES2DecoderTestBase::OnWaitSyncToken(const gpu::SyncToken&) { - return false; -} void GLES2DecoderTestBase::OnDescheduleUntilFinished() {} void GLES2DecoderTestBase::OnRescheduleAfterFinished() {} void GLES2DecoderTestBase::OnSwapBuffers(uint64_t swap_id, uint32_t flags) {} @@ -2444,9 +2441,6 @@ void GLES2DecoderPassthroughTestBase::CacheShader(const std::string& key, const std::string& shader) {} void GLES2DecoderPassthroughTestBase::OnFenceSyncRelease(uint64_t release) {} -bool GLES2DecoderPassthroughTestBase::OnWaitSyncToken(const gpu::SyncToken&) { - return false; -} void GLES2DecoderPassthroughTestBase::OnDescheduleUntilFinished() {} void GLES2DecoderPassthroughTestBase::OnRescheduleAfterFinished() {} void GLES2DecoderPassthroughTestBase::OnSwapBuffers(uint64_t swap_id,
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.h b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.h index 9098e64..47979044 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.h +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.h
@@ -61,7 +61,6 @@ void OnConsoleMessage(int32_t id, const std::string& message) override; void CacheShader(const std::string& key, const std::string& shader) override; void OnFenceSyncRelease(uint64_t release) override; - bool OnWaitSyncToken(const gpu::SyncToken&) override; void OnDescheduleUntilFinished() override; void OnRescheduleAfterFinished() override; void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override; @@ -853,7 +852,6 @@ void OnConsoleMessage(int32_t id, const std::string& message) override; void CacheShader(const std::string& key, const std::string& shader) override; void OnFenceSyncRelease(uint64_t release) override; - bool OnWaitSyncToken(const gpu::SyncToken&) override; void OnDescheduleUntilFinished() override; void OnRescheduleAfterFinished() override; void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override;
diff --git a/gpu/command_buffer/service/memory_program_cache_unittest.cc b/gpu/command_buffer/service/memory_program_cache_unittest.cc index d221cb7..0aa22b2 100644 --- a/gpu/command_buffer/service/memory_program_cache_unittest.cc +++ b/gpu/command_buffer/service/memory_program_cache_unittest.cc
@@ -94,7 +94,6 @@ shader_cache_shader_ = shader; } void OnFenceSyncRelease(uint64_t release) override {} - bool OnWaitSyncToken(const gpu::SyncToken&) override { return false; } void OnDescheduleUntilFinished() override {} void OnRescheduleAfterFinished() override {} void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override {}
diff --git a/gpu/command_buffer/service/passthrough_program_cache_unittest.cc b/gpu/command_buffer/service/passthrough_program_cache_unittest.cc index 7ca3d73..394f47e 100644 --- a/gpu/command_buffer/service/passthrough_program_cache_unittest.cc +++ b/gpu/command_buffer/service/passthrough_program_cache_unittest.cc
@@ -44,7 +44,6 @@ void CacheShader(const std::string& key, const std::string& shader) override { } void OnFenceSyncRelease(uint64_t release) override {} - bool OnWaitSyncToken(const gpu::SyncToken&) override { return false; } void OnDescheduleUntilFinished() override {} void OnRescheduleAfterFinished() override {} void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override {}
diff --git a/gpu/command_buffer/service/program_manager_unittest.cc b/gpu/command_buffer/service/program_manager_unittest.cc index a6a1e4c..e2e55c7 100644 --- a/gpu/command_buffer/service/program_manager_unittest.cc +++ b/gpu/command_buffer/service/program_manager_unittest.cc
@@ -90,7 +90,6 @@ void CacheShader(const std::string& key, const std::string& shader) override { } void OnFenceSyncRelease(uint64_t release) override {} - bool OnWaitSyncToken(const gpu::SyncToken&) override { return false; } void OnDescheduleUntilFinished() override {} void OnRescheduleAfterFinished() override {} void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override {}
diff --git a/gpu/command_buffer/service/raster_cmd_validation_implementation_autogen.h b/gpu/command_buffer/service/raster_cmd_validation_implementation_autogen.h index 71a3fa5d..d7e5536 100644 --- a/gpu/command_buffer/service/raster_cmd_validation_implementation_autogen.h +++ b/gpu/command_buffer/service/raster_cmd_validation_implementation_autogen.h
@@ -54,7 +54,9 @@ }; static const GLenum valid_texture_parameter_table[] = { - GL_TEXTURE_MAG_FILTER, GL_TEXTURE_MIN_FILTER, GL_TEXTURE_WRAP_S, + GL_TEXTURE_MAG_FILTER, + GL_TEXTURE_MIN_FILTER, + GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_T, }; @@ -63,7 +65,8 @@ }; static const gfx::BufferUsage valid_gfx_buffer_usage_table[] = { - gfx::BufferUsage::GPU_READ, gfx::BufferUsage::SCANOUT, + gfx::BufferUsage::GPU_READ, + gfx::BufferUsage::SCANOUT, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE, gfx::BufferUsage::GPU_READ_CPU_READ_WRITE_PERSISTENT, };
diff --git a/gpu/command_buffer/service/raster_decoder.cc b/gpu/command_buffer/service/raster_decoder.cc index e020829..dab7cc8 100644 --- a/gpu/command_buffer/service/raster_decoder.cc +++ b/gpu/command_buffer/service/raster_decoder.cc
@@ -1482,34 +1482,6 @@ } } -error::Error RasterDecoderImpl::HandleWaitSyncTokenCHROMIUM( - uint32_t immediate_data_size, - const volatile void* cmd_data) { - const volatile gles2::cmds::WaitSyncTokenCHROMIUM& c = - *static_cast<const volatile gles2::cmds::WaitSyncTokenCHROMIUM*>( - cmd_data); - - static constexpr CommandBufferNamespace kMinNamespaceId = - CommandBufferNamespace::INVALID; - static constexpr CommandBufferNamespace kMaxNamespaceId = - CommandBufferNamespace::NUM_COMMAND_BUFFER_NAMESPACES; - - CommandBufferNamespace namespace_id = - static_cast<CommandBufferNamespace>(c.namespace_id); - if ((namespace_id < static_cast<int32_t>(kMinNamespaceId)) || - (namespace_id >= static_cast<int32_t>(kMaxNamespaceId))) { - namespace_id = CommandBufferNamespace::INVALID; - } - const CommandBufferId command_buffer_id = - CommandBufferId::FromUnsafeValue(c.command_buffer_id()); - const uint64_t release = c.release_count(); - - SyncToken sync_token; - sync_token.Set(namespace_id, command_buffer_id, release); - return client_->OnWaitSyncToken(sync_token) ? error::kDeferCommandUntilLater - : error::kNoError; -} - error::Error RasterDecoderImpl::HandleBeginQueryEXT( uint32_t immediate_data_size, const volatile void* cmd_data) {
diff --git a/gpu/command_buffer/service/raster_decoder_unittest.cc b/gpu/command_buffer/service/raster_decoder_unittest.cc index 620842ab..5c01948 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest.cc +++ b/gpu/command_buffer/service/raster_decoder_unittest.cc
@@ -248,7 +248,6 @@ void CacheShader(const std::string& key, const std::string& shader) override { } void OnFenceSyncRelease(uint64_t release) override {} - bool OnWaitSyncToken(const gpu::SyncToken&) override { return false; } void OnDescheduleUntilFinished() override {} void OnRescheduleAfterFinished() override {} void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override {}
diff --git a/gpu/command_buffer/service/raster_decoder_unittest_base.cc b/gpu/command_buffer/service/raster_decoder_unittest_base.cc index af44348..28caf24 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest_base.cc +++ b/gpu/command_buffer/service/raster_decoder_unittest_base.cc
@@ -72,9 +72,6 @@ void RasterDecoderTestBase::CacheShader(const std::string& key, const std::string& shader) {} void RasterDecoderTestBase::OnFenceSyncRelease(uint64_t release) {} -bool RasterDecoderTestBase::OnWaitSyncToken(const gpu::SyncToken&) { - return false; -} void RasterDecoderTestBase::OnDescheduleUntilFinished() {} void RasterDecoderTestBase::OnRescheduleAfterFinished() {} void RasterDecoderTestBase::OnSwapBuffers(uint64_t swap_id, uint32_t flags) {}
diff --git a/gpu/command_buffer/service/raster_decoder_unittest_base.h b/gpu/command_buffer/service/raster_decoder_unittest_base.h index 84e84f9b..ad43b76 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest_base.h +++ b/gpu/command_buffer/service/raster_decoder_unittest_base.h
@@ -59,7 +59,6 @@ void OnConsoleMessage(int32_t id, const std::string& message) override; void CacheShader(const std::string& key, const std::string& shader) override; void OnFenceSyncRelease(uint64_t release) override; - bool OnWaitSyncToken(const gpu::SyncToken&) override; void OnDescheduleUntilFinished() override; void OnRescheduleAfterFinished() override; void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override;
diff --git a/gpu/command_buffer/service/scheduler.cc b/gpu/command_buffer/service/scheduler.cc index af1cbff..112948d 100644 --- a/gpu/command_buffer/service/scheduler.cc +++ b/gpu/command_buffer/service/scheduler.cc
@@ -103,8 +103,9 @@ } bool Scheduler::Sequence::NeedsRescheduling() const { - return running_state_ != IDLE && - scheduling_state_.priority != current_priority(); + return (running_state_ != IDLE && + scheduling_state_.priority != current_priority()) || + (running_state_ == SCHEDULED && !IsRunnable()); } bool Scheduler::Sequence::IsRunnable() const { @@ -122,16 +123,15 @@ void Scheduler::Sequence::SetEnabled(bool enabled) { if (enabled_ == enabled) return; - DCHECK_EQ(running_state_, enabled ? IDLE : RUNNING); enabled_ = enabled; if (enabled) { TRACE_EVENT_ASYNC_BEGIN1("gpu", "SequenceEnabled", this, "sequence_id", sequence_id_.GetUnsafeValue()); - scheduler_->TryScheduleSequence(this); } else { TRACE_EVENT_ASYNC_END1("gpu", "SequenceEnabled", this, "sequence_id", sequence_id_.GetUnsafeValue()); } + scheduler_->TryScheduleSequence(this); } Scheduler::SchedulingState Scheduler::Sequence::SetScheduled() {
diff --git a/gpu/command_buffer/service/shared_image_backing_factory.h b/gpu/command_buffer/service/shared_image_backing_factory.h index f1ae9af..14dcb5b 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory.h +++ b/gpu/command_buffer/service/shared_image_backing_factory.h
@@ -32,6 +32,13 @@ uint32_t usage) = 0; virtual std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) = 0; + virtual std::unique_ptr<SharedImageBacking> CreateSharedImage( + const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format,
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc index 37b766eae..43588d6f 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.cc
@@ -463,6 +463,18 @@ return backing; } +std::unique_ptr<SharedImageBacking> +SharedImageBackingFactoryAHB::CreateSharedImage( + const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) { + NOTIMPLEMENTED(); + return nullptr; +} + SharedImageBackingFactoryAHB::FormatInfo::FormatInfo() = default; SharedImageBackingFactoryAHB::FormatInfo::~FormatInfo() = default;
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.h b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.h index 7562545..4988f47e 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.h +++ b/gpu/command_buffer/service/shared_image_backing_factory_ahardwarebuffer.h
@@ -40,6 +40,13 @@ uint32_t usage) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) override; + std::unique_ptr<SharedImageBacking> CreateSharedImage( + const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format,
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.cc b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.cc index 9fa3c3c..ef4d836 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.cc
@@ -8,6 +8,7 @@ #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/trace_event.h" #include "components/viz/common/resources/resource_format_utils.h" +#include "gpu/command_buffer/common/gles2_cmd_utils.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" #include "gpu/command_buffer/common/shared_image_trace_utils.h" #include "gpu/command_buffer/common/shared_image_usage.h" @@ -33,6 +34,106 @@ namespace { +class ScopedResetAndRestoreUnpackState { + public: + ScopedResetAndRestoreUnpackState(gl::GLApi* api, + bool es3_capable, + bool desktop_gl, + bool supports_unpack_subimage, + bool uploading_data) + : api_(api) { + if (es3_capable) { + // Need to unbind any GL_PIXEL_UNPACK_BUFFER for the nullptr in + // glTexImage2D to mean "no pixels" (as opposed to offset 0 in the + // buffer). + api_->glGetIntegervFn(GL_PIXEL_UNPACK_BUFFER_BINDING, &unpack_buffer_); + if (unpack_buffer_) + api_->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, 0); + } + if (uploading_data) { + api_->glGetIntegervFn(GL_UNPACK_ALIGNMENT, &unpack_alignment_); + if (unpack_alignment_ != 4) + api_->glPixelStoreiFn(GL_UNPACK_ALIGNMENT, 4); + + if (es3_capable || supports_unpack_subimage) { + api_->glGetIntegervFn(GL_UNPACK_ROW_LENGTH, &unpack_row_length_); + if (unpack_row_length_) + api_->glPixelStoreiFn(GL_UNPACK_ROW_LENGTH, 0); + api_->glGetIntegervFn(GL_UNPACK_SKIP_ROWS, &unpack_skip_rows_); + if (unpack_skip_rows_) + api_->glPixelStoreiFn(GL_UNPACK_SKIP_ROWS, 0); + api_->glGetIntegervFn(GL_UNPACK_SKIP_PIXELS, &unpack_skip_pixels_); + if (unpack_skip_pixels_) + api_->glPixelStoreiFn(GL_UNPACK_SKIP_PIXELS, 0); + } + + if (es3_capable) { + api_->glGetIntegervFn(GL_UNPACK_SKIP_IMAGES, &unpack_skip_images_); + if (unpack_skip_images_) + api_->glPixelStoreiFn(GL_UNPACK_SKIP_IMAGES, 0); + api_->glGetIntegervFn(GL_UNPACK_IMAGE_HEIGHT, &unpack_image_height_); + if (unpack_image_height_) + api_->glPixelStoreiFn(GL_UNPACK_IMAGE_HEIGHT, 0); + } + + if (desktop_gl) { + api->glGetBooleanvFn(GL_UNPACK_SWAP_BYTES, &unpack_swap_bytes_); + if (unpack_swap_bytes_) + api->glPixelStoreiFn(GL_UNPACK_SWAP_BYTES, GL_FALSE); + api->glGetBooleanvFn(GL_UNPACK_LSB_FIRST, &unpack_lsb_first_); + if (unpack_lsb_first_) + api->glPixelStoreiFn(GL_UNPACK_LSB_FIRST, GL_FALSE); + } + } + } + + ~ScopedResetAndRestoreUnpackState() { + if (unpack_buffer_) + api_->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, unpack_buffer_); + if (unpack_alignment_ != 4) + api_->glPixelStoreiFn(GL_UNPACK_ALIGNMENT, unpack_alignment_); + if (unpack_row_length_) + api_->glPixelStoreiFn(GL_UNPACK_ROW_LENGTH, unpack_row_length_); + if (unpack_image_height_) + api_->glPixelStoreiFn(GL_UNPACK_IMAGE_HEIGHT, unpack_image_height_); + if (unpack_skip_rows_) + api_->glPixelStoreiFn(GL_UNPACK_SKIP_ROWS, unpack_skip_rows_); + if (unpack_skip_images_) + api_->glPixelStoreiFn(GL_UNPACK_SKIP_IMAGES, unpack_skip_images_); + if (unpack_skip_pixels_) + api_->glPixelStoreiFn(GL_UNPACK_SKIP_PIXELS, unpack_skip_pixels_); + if (unpack_swap_bytes_) + api_->glPixelStoreiFn(GL_UNPACK_SWAP_BYTES, unpack_swap_bytes_); + if (unpack_lsb_first_) + api_->glPixelStoreiFn(GL_UNPACK_LSB_FIRST, unpack_lsb_first_); + } + + private: + gl::GLApi* const api_; + + // Always used if |es3_capable|. + GLint unpack_buffer_ = 0; + + // Always used when |uploading_data|. + GLint unpack_alignment_ = 4; + + // Used when |uploading_data_| and (|es3_capable| or + // |supports_unpack_subimage|). + GLint unpack_row_length_ = 0; + GLint unpack_skip_pixels_ = 0; + GLint unpack_skip_rows_ = 0; + + // Used when |uploading_data| and |es3_capable|. + GLint unpack_skip_images_ = 0; + GLint unpack_image_height_ = 0; + + // Used when |desktop_gl|. + GLboolean unpack_swap_bytes_ = GL_FALSE; + GLboolean unpack_lsb_first_ = GL_FALSE; + + DISALLOW_COPY_AND_ASSIGN(ScopedResetAndRestoreUnpackState); +}; + class ScopedRestoreTexture { public: ScopedRestoreTexture(gl::GLApi* api, GLenum target) @@ -312,7 +413,8 @@ uint32_t usage, scoped_refptr<gles2::TexturePassthrough> passthrough_texture, GLenum internal_format, - GLenum driver_internal_format) + GLenum driver_internal_format, + bool is_cleared) : SharedImageBacking(mailbox, format, size, @@ -321,7 +423,8 @@ passthrough_texture->estimated_size()), texture_passthrough_(std::move(passthrough_texture)), internal_format_(internal_format), - driver_internal_format_(driver_internal_format) { + driver_internal_format_(driver_internal_format), + is_cleared_(is_cleared) { DCHECK(texture_passthrough_); } @@ -406,6 +509,12 @@ feature_info->feature_flags().gpu_memory_buffer_formats; texture_usage_angle_ = feature_info->feature_flags().angle_texture_usage; es3_capable_ = feature_info->IsES3Capable(); + desktop_gl_ = !feature_info->gl_version_info().is_es; + // Can't use the value from feature_info, as we unconditionally enable this + // extension, and assume it can't be used if PBOs are not used (which isn't + // true for Skia used direclty against GL). + supports_unpack_subimage_ = + gl::g_current_gl_driver->ext.b_GL_EXT_unpack_subimage; bool enable_texture_storage = feature_info->feature_flags().ext_texture_storage; bool enable_scanout_images = @@ -414,17 +523,20 @@ for (int i = 0; i <= viz::RESOURCE_FORMAT_MAX; ++i) { auto format = static_cast<viz::ResourceFormat>(i); FormatInfo& info = format_info_[i]; - // TODO(piman): do we need to support ETC1? - if (!viz::GLSupportsFormat(format) || - viz::IsResourceFormatCompressed(format)) + if (!viz::GLSupportsFormat(format)) continue; GLuint image_internal_format = viz::GLInternalFormat(format); GLenum gl_format = viz::GLDataFormat(format); GLenum gl_type = viz::GLDataType(format); - if (validators->texture_internal_format.IsValid(image_internal_format) && - validators->texture_format.IsValid(gl_format) && + bool uncompressed_format_valid = + validators->texture_internal_format.IsValid(image_internal_format) && + validators->texture_format.IsValid(gl_format); + bool compressed_format_valid = + validators->compressed_texture_format.IsValid(image_internal_format); + if ((uncompressed_format_valid || compressed_format_valid) && validators->pixel_type.IsValid(gl_type)) { info.enabled = true; + info.is_compressed = compressed_format_valid; info.gl_format = gl_format; info.gl_type = gl_type; info.swizzle = gles2::TextureManager::GetCompatibilitySwizzle( @@ -437,7 +549,7 @@ } if (!info.enabled) continue; - if (enable_texture_storage) { + if (enable_texture_storage && !info.is_compressed) { GLuint storage_internal_format = viz::TextureStorageFormat(format); if (validators->texture_internal_format_storage.IsValid( storage_internal_format)) { @@ -481,6 +593,18 @@ const gfx::Size& size, const gfx::ColorSpace& color_space, uint32_t usage) { + return CreateSharedImage(mailbox, format, size, color_space, usage, + base::span<const uint8_t>()); +} + +std::unique_ptr<SharedImageBacking> +SharedImageBackingFactoryGLTexture::CreateSharedImage( + const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) { const FormatInfo& format_info = format_info_[format]; if (!format_info.enabled) { LOG(ERROR) << "CreateSharedImage: invalid format"; @@ -501,6 +625,54 @@ GLenum target = use_buffer ? format_info.target_for_scanout : GL_TEXTURE_2D; + // If we have initial data to upload, ensure it is sized appropriately. + if (!pixel_data.empty()) { + if (format_info.is_compressed) { + const char* error_message = "unspecified"; + if (!gles2::ValidateCompressedTexDimensions( + target, 0 /* level */, size.width(), size.height(), 1 /* depth */, + format_info.gl_format, false /* restrict_for_webgl */, + &error_message)) { + LOG(ERROR) << "CreateSharedImage: " + "ValidateCompressedTexDimensionsFailed with error: " + << error_message; + return nullptr; + } + + GLsizei bytes_required = 0; + if (!gles2::GetCompressedTexSizeInBytes( + nullptr /* function_name */, size.width(), size.height(), + 1 /* depth */, format_info.gl_format, &bytes_required, + nullptr /* error_state */)) { + LOG(ERROR) << "CreateSharedImage: Unable to compute required size for " + "initial texture upload."; + return nullptr; + } + + if (bytes_required < 0 || + pixel_data.size() != static_cast<size_t>(bytes_required)) { + LOG(ERROR) << "CreateSharedImage: Initial data does not have expected " + "size."; + return nullptr; + } + } else { + uint32_t bytes_required; + if (!gles2::GLES2Util::ComputeImageDataSizes( + size.width(), size.height(), 1 /* depth */, format_info.gl_format, + format_info.gl_type, 4 /* alignment */, &bytes_required, nullptr, + nullptr)) { + LOG(ERROR) << "CreateSharedImage: Unable to compute required size for " + "initial texture upload."; + return nullptr; + } + if (pixel_data.size() != bytes_required) { + LOG(ERROR) << "CreateSharedImage: Initial data does not have expected " + "size."; + return nullptr; + } + } + } + gl::GLApi* api = gl::g_current_gl_context; ScopedRestoreTexture scoped_restore(api, target); @@ -516,6 +688,7 @@ // the internal format in the LevelInfo. https://crbug.com/628064 GLuint level_info_internal_format = format_info.gl_format; bool is_cleared = false; + bool needs_subimage_upload = false; if (use_buffer) { image = image_factory_->CreateAnonymousImage( size, format_info.buffer_format, gfx::BufferUsage::SCANOUT, @@ -528,32 +701,44 @@ level_info_internal_format = image->GetInternalFormat(); if (color_space.IsValid()) image->SetColorSpace(color_space); + needs_subimage_upload = !pixel_data.empty(); } else if (format_info.supports_storage) { api->glTexStorage2DEXTFn(target, 1, format_info.storage_internal_format, size.width(), size.height()); + needs_subimage_upload = !pixel_data.empty(); + } else if (format_info.is_compressed) { + ScopedResetAndRestoreUnpackState scoped_unpack_state( + api, es3_capable_, desktop_gl_, supports_unpack_subimage_, + !pixel_data.empty()); + api->glCompressedTexImage2DFn(target, 0, format_info.gl_format, + size.width(), size.height(), 0, + pixel_data.size(), pixel_data.data()); } else { - // Need to unbind any GL_PIXEL_UNPACK_BUFFER for the nullptr in - // glTexImage2D to mean "no pixels" (as opposed to offset 0 in the - // buffer). - GLint bound_pixel_unpack_buffer = 0; - if (es3_capable_) { - api->glGetIntegervFn(GL_PIXEL_UNPACK_BUFFER_BINDING, - &bound_pixel_unpack_buffer); - if (bound_pixel_unpack_buffer) - api->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, 0); - } + ScopedResetAndRestoreUnpackState scoped_unpack_state( + api, es3_capable_, desktop_gl_, supports_unpack_subimage_, + !pixel_data.empty()); api->glTexImage2DFn(target, 0, format_info.image_internal_format, size.width(), size.height(), 0, format_info.adjusted_format, format_info.gl_type, - nullptr); - if (bound_pixel_unpack_buffer) - api->glBindBufferFn(GL_PIXEL_UNPACK_BUFFER, bound_pixel_unpack_buffer); + pixel_data.data()); + } + + // If we are using a buffer or TexStorage API but have data to upload, do so + // now via TexSubImage2D. + if (needs_subimage_upload) { + ScopedResetAndRestoreUnpackState scoped_unpack_state( + api, es3_capable_, desktop_gl_, supports_unpack_subimage_, + !pixel_data.empty()); + api->glTexSubImage2DFn(target, 0, 0, 0, size.width(), size.height(), + format_info.adjusted_format, format_info.gl_type, + pixel_data.data()); } return MakeBacking(mailbox, target, service_id, image, gles2::Texture::BOUND, level_info_internal_format, format_info.gl_format, - format_info.gl_type, format_info.swizzle, is_cleared, - format, size, color_space, usage); + format_info.gl_type, format_info.swizzle, + pixel_data.empty() ? is_cleared : true, format, size, + color_space, usage); } std::unique_ptr<SharedImageBacking> @@ -687,7 +872,7 @@ return std::make_unique<SharedImageBackingPassthroughGLTexture>( mailbox, format, size, color_space, usage, std::move(passthrough_texture), level_info_internal_format, - driver_internal_format); + driver_internal_format, is_cleared); } else { gles2::Texture* texture = new gles2::Texture(service_id); texture->SetLightweightRef();
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.h b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.h index 6fec6d23..5705b92 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.h +++ b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture.h
@@ -50,6 +50,13 @@ uint32_t usage) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) override; + std::unique_ptr<SharedImageBacking> CreateSharedImage( + const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format, @@ -92,6 +99,9 @@ // Whether to allow SHARED_IMAGE_USAGE_SCANOUT. bool allow_scanout = false; + // Whether the texture is a compressed type. + bool is_compressed = false; + GLenum gl_format = 0; GLenum gl_type = 0; const gles2::Texture::CompatibilitySwizzle* swizzle = nullptr; @@ -126,6 +136,8 @@ int32_t max_texture_size_ = 0; bool texture_usage_angle_ = false; bool es3_capable_ = false; + bool desktop_gl_ = false; + bool supports_unpack_subimage_ = false; }; } // namespace gpu
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc index c813a51..2685a68 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc +++ b/gpu/command_buffer/service/shared_image_backing_factory_gl_texture_unittest.cc
@@ -6,6 +6,7 @@ #include "base/bind_helpers.h" #include "components/viz/common/resources/resource_format_utils.h" +#include "components/viz/common/resources/resource_sizes.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/shared_image_usage.h" @@ -65,12 +66,20 @@ shared_image_representation_factory_ = std::make_unique<SharedImageRepresentationFactory>( &shared_image_manager_, nullptr); + + scoped_refptr<gles2::FeatureInfo> feature_info = + new gles2::FeatureInfo(workarounds, GpuFeatureInfo()); + supports_etc1_ = + feature_info->validators()->compressed_texture_format.IsValid( + GL_ETC1_RGB8_OES); } bool use_passthrough() { return GetParam() && gles2::PassthroughCommandDecoderSupported(); } + bool supports_etc1() { return supports_etc1_; } + GrContext* gr_context() { return context_state_->gr_context; } protected: @@ -83,6 +92,7 @@ std::unique_ptr<MemoryTypeTracker> memory_type_tracker_; std::unique_ptr<SharedImageRepresentationFactory> shared_image_representation_factory_; + bool supports_etc1_ = false; }; class SharedImageBackingFactoryGLTextureTest @@ -299,6 +309,115 @@ } } +TEST_P(SharedImageBackingFactoryGLTextureTest, InitialData) { + for (auto format : + {viz::ResourceFormat::RGBA_8888, viz::ResourceFormat::ETC1}) { + if (format == viz::ResourceFormat::ETC1 && !supports_etc1()) + continue; + + auto mailbox = Mailbox::Generate(); + gfx::Size size(256, 256); + auto color_space = gfx::ColorSpace::CreateSRGB(); + uint32_t usage = SHARED_IMAGE_USAGE_GLES2; + std::vector<uint8_t> initial_data( + viz::ResourceSizes::CheckedSizeInBytes<unsigned int>(size, format)); + auto backing = backing_factory_->CreateSharedImage( + mailbox, format, size, color_space, usage, initial_data); + EXPECT_TRUE(backing); + EXPECT_TRUE(backing->IsCleared()); + + // Validate via a SharedImageRepresentationGLTexture(Passthrough). + std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = + shared_image_manager_.Register(std::move(backing), + memory_type_tracker_.get()); + EXPECT_TRUE(shared_image); + GLenum expected_target = GL_TEXTURE_2D; + if (!use_passthrough()) { + auto gl_representation = + shared_image_representation_factory_->ProduceGLTexture(mailbox); + EXPECT_TRUE(gl_representation); + EXPECT_TRUE(gl_representation->GetTexture()->service_id()); + EXPECT_EQ(expected_target, gl_representation->GetTexture()->target()); + EXPECT_EQ(size, gl_representation->size()); + EXPECT_EQ(format, gl_representation->format()); + EXPECT_EQ(color_space, gl_representation->color_space()); + EXPECT_EQ(usage, gl_representation->usage()); + gl_representation.reset(); + } else { + auto gl_representation = + shared_image_representation_factory_->ProduceGLTexturePassthrough( + mailbox); + EXPECT_TRUE(gl_representation); + EXPECT_TRUE(gl_representation->GetTexturePassthrough()->service_id()); + EXPECT_EQ(expected_target, + gl_representation->GetTexturePassthrough()->target()); + EXPECT_EQ(size, gl_representation->size()); + EXPECT_EQ(format, gl_representation->format()); + EXPECT_EQ(color_space, gl_representation->color_space()); + EXPECT_EQ(usage, gl_representation->usage()); + gl_representation.reset(); + } + + shared_image.reset(); + EXPECT_FALSE(mailbox_manager_.ConsumeTexture(mailbox)); + } +} + +TEST_P(SharedImageBackingFactoryGLTextureTest, InitialDataImage) { + auto mailbox = Mailbox::Generate(); + auto format = viz::ResourceFormat::RGBA_8888; + gfx::Size size(256, 256); + auto color_space = gfx::ColorSpace::CreateSRGB(); + uint32_t usage = SHARED_IMAGE_USAGE_GLES2 | SHARED_IMAGE_USAGE_SCANOUT; + std::vector<uint8_t> initial_data(256 * 256 * 4); + auto backing = backing_factory_->CreateSharedImage( + mailbox, format, size, color_space, usage, initial_data); + + // Validate via a SharedImageRepresentationGLTexture(Passthrough). + std::unique_ptr<SharedImageRepresentationFactoryRef> shared_image = + shared_image_manager_.Register(std::move(backing), + memory_type_tracker_.get()); + EXPECT_TRUE(shared_image); + if (!use_passthrough()) { + auto gl_representation = + shared_image_representation_factory_->ProduceGLTexture(mailbox); + EXPECT_TRUE(gl_representation); + EXPECT_TRUE(gl_representation->GetTexture()->service_id()); + EXPECT_EQ(size, gl_representation->size()); + EXPECT_EQ(format, gl_representation->format()); + EXPECT_EQ(color_space, gl_representation->color_space()); + EXPECT_EQ(usage, gl_representation->usage()); + gl_representation.reset(); + } else { + auto gl_representation = + shared_image_representation_factory_->ProduceGLTexturePassthrough( + mailbox); + EXPECT_TRUE(gl_representation); + EXPECT_TRUE(gl_representation->GetTexturePassthrough()->service_id()); + EXPECT_EQ(size, gl_representation->size()); + EXPECT_EQ(format, gl_representation->format()); + EXPECT_EQ(color_space, gl_representation->color_space()); + EXPECT_EQ(usage, gl_representation->usage()); + gl_representation.reset(); + } +} + +TEST_P(SharedImageBackingFactoryGLTextureTest, InitialDataWrongSize) { + auto mailbox = Mailbox::Generate(); + auto format = viz::ResourceFormat::RGBA_8888; + gfx::Size size(256, 256); + auto color_space = gfx::ColorSpace::CreateSRGB(); + uint32_t usage = SHARED_IMAGE_USAGE_GLES2; + std::vector<uint8_t> initial_data_small(256 * 128 * 4); + std::vector<uint8_t> initial_data_large(256 * 512 * 4); + auto backing = backing_factory_->CreateSharedImage( + mailbox, format, size, color_space, usage, initial_data_small); + EXPECT_FALSE(backing); + backing = backing_factory_->CreateSharedImage( + mailbox, format, size, color_space, usage, initial_data_large); + EXPECT_FALSE(backing); +} + TEST_P(SharedImageBackingFactoryGLTextureTest, InvalidFormat) { auto mailbox = Mailbox::Generate(); auto format = viz::ResourceFormat::UYVY_422;
diff --git a/gpu/command_buffer/service/shared_image_factory.cc b/gpu/command_buffer/service/shared_image_factory.cc index 91fbc519..7f2ff16 100644 --- a/gpu/command_buffer/service/shared_image_factory.cc +++ b/gpu/command_buffer/service/shared_image_factory.cc
@@ -88,6 +88,19 @@ return RegisterBacking(std::move(backing), !using_wrapped_sk_image); } +bool SharedImageFactory::CreateSharedImage( + const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) { + std::unique_ptr<SharedImageBacking> backing = + backing_factory_->CreateSharedImage(mailbox, format, size, color_space, + usage, pixel_data); + return RegisterBacking(std::move(backing), true); +} + bool SharedImageFactory::CreateSharedImage(const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle,
diff --git a/gpu/command_buffer/service/shared_image_factory.h b/gpu/command_buffer/service/shared_image_factory.h index 78c7933..2a537ed 100644 --- a/gpu/command_buffer/service/shared_image_factory.h +++ b/gpu/command_buffer/service/shared_image_factory.h
@@ -53,6 +53,12 @@ const gfx::ColorSpace& color_space, uint32_t usage); bool CreateSharedImage(const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data); + bool CreateSharedImage(const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format,
diff --git a/gpu/command_buffer/service/wrapped_sk_image.cc b/gpu/command_buffer/service/wrapped_sk_image.cc index ae7940f..dadbed1 100644 --- a/gpu/command_buffer/service/wrapped_sk_image.cc +++ b/gpu/command_buffer/service/wrapped_sk_image.cc
@@ -237,6 +237,17 @@ std::unique_ptr<SharedImageBacking> WrappedSkImageFactory::CreateSharedImage( const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) { + NOTREACHED(); + return nullptr; +} + +std::unique_ptr<SharedImageBacking> WrappedSkImageFactory::CreateSharedImage( + const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat buffer_format,
diff --git a/gpu/command_buffer/service/wrapped_sk_image.h b/gpu/command_buffer/service/wrapped_sk_image.h index 02458e5..a733080 100644 --- a/gpu/command_buffer/service/wrapped_sk_image.h +++ b/gpu/command_buffer/service/wrapped_sk_image.h
@@ -35,6 +35,13 @@ uint32_t usage) override; std::unique_ptr<SharedImageBacking> CreateSharedImage( const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) override; + std::unique_ptr<SharedImageBacking> CreateSharedImage( + const Mailbox& mailbox, int client_id, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format,
diff --git a/gpu/command_buffer/tests/decoder_perftest.cc b/gpu/command_buffer/tests/decoder_perftest.cc index f530fec5..35592b75 100644 --- a/gpu/command_buffer/tests/decoder_perftest.cc +++ b/gpu/command_buffer/tests/decoder_perftest.cc
@@ -269,55 +269,57 @@ return -1; } - void DestroyImage(int32_t id) override { NOTIMPLEMENTED(); } + void DestroyImage(int32_t id) override { NOTREACHED(); } void SignalQuery(uint32_t query, base::OnceClosure callback) override { - NOTIMPLEMENTED(); + NOTREACHED(); } void CreateGpuFence(uint32_t gpu_fence_id, ClientGpuFence source) override { - NOTIMPLEMENTED(); + NOTREACHED(); } void GetGpuFence(uint32_t gpu_fence_id, base::OnceCallback<void(std::unique_ptr<gfx::GpuFence>)> callback) override { - NOTIMPLEMENTED(); + NOTREACHED(); } - void SetLock(base::Lock*) override { NOTIMPLEMENTED(); } + void SetLock(base::Lock*) override { NOTREACHED(); } - void EnsureWorkVisible() override {} + void EnsureWorkVisible() override { NOTREACHED(); } gpu::CommandBufferNamespace GetNamespaceID() const override { - return command_buffer_->GetNamespaceID(); + return gpu::CommandBufferNamespace::INVALID; } CommandBufferId GetCommandBufferID() const override { - return command_buffer_->GetCommandBufferID(); + return gpu::CommandBufferId(); } - void FlushPendingWork() override {} + void FlushPendingWork() override { NOTREACHED(); } uint64_t GenerateFenceSyncRelease() override { - NOTIMPLEMENTED(); + NOTREACHED(); return 0; } bool IsFenceSyncReleased(uint64_t release) override { - NOTIMPLEMENTED(); + NOTREACHED(); return true; } void SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) override { - NOTIMPLEMENTED(); + NOTREACHED(); } - void WaitSyncTokenHint(const gpu::SyncToken& sync_token) override {} + void WaitSyncToken(const gpu::SyncToken& sync_token) override { + NOTREACHED(); + } bool CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) override { - NOTIMPLEMENTED(); + NOTREACHED(); return true; }
diff --git a/gpu/command_buffer/tests/fuzzer_main.cc b/gpu/command_buffer/tests/fuzzer_main.cc index cf0e8a5..8f10415 100644 --- a/gpu/command_buffer/tests/fuzzer_main.cc +++ b/gpu/command_buffer/tests/fuzzer_main.cc
@@ -18,7 +18,6 @@ #include "build/build_config.h" #include "gpu/command_buffer/common/constants.h" #include "gpu/command_buffer/common/context_creation_attribs.h" -#include "gpu/command_buffer/common/sync_token.h" #include "gpu/command_buffer/service/buffer_manager.h" #include "gpu/command_buffer/service/command_buffer_direct.h" #include "gpu/command_buffer/service/context_group.h" @@ -33,7 +32,6 @@ #include "gpu/command_buffer/service/raster_decoder_context_state.h" #include "gpu/command_buffer/service/service_discardable_manager.h" #include "gpu/command_buffer/service/shared_image_manager.h" -#include "gpu/command_buffer/service/sync_point_manager.h" #include "gpu/command_buffer/service/transfer_buffer_manager.h" #include "ui/gfx/geometry/size.h" #include "ui/gl/gl_context.h" @@ -356,8 +354,8 @@ nullptr /* image_factory */, nullptr /* progress_reporter */, gpu_feature_info, discardable_manager_.get(), passthrough_discardable_manager_.get(), &shared_image_manager_); - command_buffer_.reset(new CommandBufferDirect( - context_group->transfer_buffer_manager(), &sync_point_manager_)); + command_buffer_.reset( + new CommandBufferDirect(context_group->transfer_buffer_manager())); #if defined(GPU_FUZZER_USE_RASTER_DECODER) CHECK(feature_info->feature_flags().chromium_raster_transport); @@ -518,7 +516,6 @@ gles2::MailboxManagerImpl mailbox_manager_; gles2::TraceOutputter outputter_; scoped_refptr<gl::GLShareGroup> share_group_; - SyncPointManager sync_point_manager_; gles2::ImageManager image_manager_; std::unique_ptr<ServiceDiscardableManager> discardable_manager_; std::unique_ptr<PassthroughDiscardableManager>
diff --git a/gpu/command_buffer/tests/gl_fence_sync_unittest.cc b/gpu/command_buffer/tests/gl_fence_sync_unittest.cc deleted file mode 100644 index 5695997..0000000 --- a/gpu/command_buffer/tests/gl_fence_sync_unittest.cc +++ /dev/null
@@ -1,91 +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 <GLES2/gl2.h> -#include <GLES2/gl2ext.h> -#include <GLES2/gl2extchromium.h> - -#include <memory> - -#include "base/bind.h" -#include "gpu/command_buffer/common/sync_token.h" -#include "gpu/command_buffer/service/sync_point_manager.h" -#include "gpu/command_buffer/tests/gl_manager.h" -#include "gpu/command_buffer/tests/gl_test_utils.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -#define SHADER(Src) #Src - -namespace gpu { - -class GLFenceSyncTest : public testing::Test { - protected: - void SetUp() override { - sync_point_manager_.reset(new SyncPointManager()); - - GLManager::Options options; - options.sync_point_manager = sync_point_manager_.get(); - gl1_.Initialize(options); - gl2_.Initialize(options); - } - - void TearDown() override { - gl2_.Destroy(); - gl1_.Destroy(); - - sync_point_manager_.reset(); - } - - std::unique_ptr<SyncPointManager> sync_point_manager_; - GLManager gl1_; - GLManager gl2_; -}; - -TEST_F(GLFenceSyncTest, SimpleReleaseWait) { - gl1_.MakeCurrent(); - - SyncToken sync_token; - glFlush(); - glGenSyncTokenCHROMIUM(sync_token.GetData()); - ASSERT_TRUE(GL_NO_ERROR == glGetError()); - - // Make sure it is actually released. - EXPECT_TRUE(sync_point_manager_->IsSyncTokenReleased(sync_token)); - - gl2_.MakeCurrent(); - glWaitSyncTokenCHROMIUM(sync_token.GetConstData()); - glFinish(); -} - -static void TestCallback(int* storage, int assign) { - *storage = assign; -} - -TEST_F(GLFenceSyncTest, SimpleReleaseSignal) { - gl1_.MakeCurrent(); - - // Pause the command buffer so the fence sync does not immediately trigger. - gl1_.SetCommandsPaused(true); - - SyncToken sync_token; - glGenUnverifiedSyncTokenCHROMIUM(sync_token.GetData()); - glFlush(); - ASSERT_TRUE(sync_token.HasData()); - - gl2_.MakeCurrent(); - int callback_called = 0; - gl2_.SignalSyncToken(sync_token, - base::Bind(TestCallback, &callback_called, 1)); - - gl1_.MakeCurrent(); - EXPECT_EQ(0, callback_called); - - gl1_.SetCommandsPaused(false); - glFinish(); - - EXPECT_EQ(1, callback_called); -} - -} // namespace gpu
diff --git a/gpu/command_buffer/tests/gl_manager.cc b/gpu/command_buffer/tests/gl_manager.cc index 72eca7e..66f4e4f 100644 --- a/gpu/command_buffer/tests/gl_manager.cc +++ b/gpu/command_buffer/tests/gl_manager.cc
@@ -197,9 +197,8 @@ class CommandBufferCheckLostContext : public CommandBufferDirect { public: CommandBufferCheckLostContext(TransferBufferManager* transfer_buffer_manager, - SyncPointManager* sync_point_manager, bool context_lost_allowed) - : CommandBufferDirect(transfer_buffer_manager, sync_point_manager), + : CommandBufferDirect(transfer_buffer_manager), context_lost_allowed_(context_lost_allowed) {} ~CommandBufferCheckLostContext() override = default; @@ -359,8 +358,7 @@ } command_buffer_.reset(new CommandBufferCheckLostContext( - context_group->transfer_buffer_manager(), options.sync_point_manager, - options.context_lost_allowed)); + context_group->transfer_buffer_manager(), options.context_lost_allowed)); decoder_.reset(::gpu::gles2::GLES2Decoder::Create( command_buffer_.get(), command_buffer_->service(), &outputter_, @@ -467,10 +465,6 @@ decoder_->PerformIdleWork(); } -void GLManager::SetCommandsPaused(bool paused) { - command_buffer_->SetCommandsPaused(paused); -} - void GLManager::Destroy() { if (gles2_implementation_.get()) { MakeCurrent(); @@ -565,56 +559,60 @@ } void GLManager::SignalQuery(uint32_t query, base::OnceClosure callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } void GLManager::CreateGpuFence(uint32_t gpu_fence_id, ClientGpuFence source) { - NOTIMPLEMENTED(); + NOTREACHED(); } void GLManager::GetGpuFence( uint32_t gpu_fence_id, base::OnceCallback<void(std::unique_ptr<gfx::GpuFence>)> callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } void GLManager::SetLock(base::Lock*) { - NOTIMPLEMENTED(); + NOTREACHED(); } void GLManager::EnsureWorkVisible() { - // This is only relevant for out-of-process command buffers. + NOTREACHED(); } gpu::CommandBufferNamespace GLManager::GetNamespaceID() const { - return command_buffer_->GetNamespaceID(); + return CommandBufferNamespace::INVALID; } CommandBufferId GLManager::GetCommandBufferID() const { - return command_buffer_->GetCommandBufferID(); + return CommandBufferId(); } void GLManager::FlushPendingWork() { - // This is only relevant for out-of-process command buffers. + NOTREACHED(); } uint64_t GLManager::GenerateFenceSyncRelease() { - return next_fence_sync_release_++; + NOTREACHED(); + return 0; } bool GLManager::IsFenceSyncReleased(uint64_t release) { - return release <= command_buffer_->GetLastState().release_count; + NOTREACHED(); + return false; } void GLManager::SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) { - command_buffer_->SignalSyncToken( - sync_token, base::AdaptCallbackForRepeating(std::move(callback))); + NOTREACHED(); } -void GLManager::WaitSyncTokenHint(const gpu::SyncToken& sync_token) {} +void GLManager::WaitSyncToken(const gpu::SyncToken& sync_token) { + NOTREACHED(); +} bool GLManager::CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) { + NOTREACHED(); return false; }
diff --git a/gpu/command_buffer/tests/gl_manager.h b/gpu/command_buffer/tests/gl_manager.h index befc608..a0d61b8 100644 --- a/gpu/command_buffer/tests/gl_manager.h +++ b/gpu/command_buffer/tests/gl_manager.h
@@ -39,7 +39,6 @@ class GpuMemoryBufferFactory; class ImageFactory; class MailboxManager; -class SyncPointManager; class TransferBuffer; namespace gles2 { @@ -55,8 +54,6 @@ Options(); // The size of the backbuffer. gfx::Size size = gfx::Size(4, 4); - // If not null will have a corresponding sync point manager. - SyncPointManager* sync_point_manager = nullptr; // If not null will share resources with this context. GLManager* share_group_manager = nullptr; // If not null will share a mailbox manager with this context. @@ -115,8 +112,6 @@ use_native_pixmap_memory_buffers_ = use_native_pixmap_memory_buffers; } - void SetCommandsPaused(bool paused); - gles2::GLES2Decoder* decoder() const { return decoder_.get(); } @@ -164,7 +159,7 @@ bool IsFenceSyncReleased(uint64_t release) override; void SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) override; - void WaitSyncTokenHint(const gpu::SyncToken& sync_token) override; + void WaitSyncToken(const gpu::SyncToken& sync_token) override; bool CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) override; size_t GetSharedMemoryBytesAllocated() const; @@ -200,8 +195,6 @@ std::unique_ptr<gpu::GpuMemoryBufferFactory> gpu_memory_buffer_factory_; SharedImageManager shared_image_manager_; - uint64_t next_fence_sync_release_ = 1; - bool use_iosurface_memory_buffers_ = false; bool use_native_pixmap_memory_buffers_ = false;
diff --git a/gpu/gles2_conform_support/egl/context.cc b/gpu/gles2_conform_support/egl/context.cc index 9009b10b9..f5352c0 100644 --- a/gpu/gles2_conform_support/egl/context.cc +++ b/gpu/gles2_conform_support/egl/context.cc
@@ -172,38 +172,38 @@ } int32_t Context::CreateImage(ClientBuffer buffer, size_t width, size_t height) { - NOTIMPLEMENTED(); + NOTREACHED(); return -1; } void Context::DestroyImage(int32_t id) { - NOTIMPLEMENTED(); + NOTREACHED(); } void Context::SignalQuery(uint32_t query, base::OnceClosure callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } void Context::CreateGpuFence(uint32_t gpu_fence_id, ClientGpuFence source) { - NOTIMPLEMENTED(); + NOTREACHED(); } void Context::GetGpuFence( uint32_t gpu_fence_id, base::OnceCallback<void(std::unique_ptr<gfx::GpuFence>)> callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } void Context::SetLock(base::Lock*) { - NOTIMPLEMENTED(); + NOTREACHED(); } void Context::EnsureWorkVisible() { - // This is only relevant for out-of-process command buffers. + NOTREACHED(); } gpu::CommandBufferNamespace Context::GetNamespaceID() const { - return gpu::CommandBufferNamespace::IN_PROCESS; + return gpu::CommandBufferNamespace::INVALID; } gpu::CommandBufferId Context::GetCommandBufferID() const { @@ -211,24 +211,27 @@ } void Context::FlushPendingWork() { - // This is only relevant for out-of-process command buffers. + NOTREACHED(); } uint64_t Context::GenerateFenceSyncRelease() { - return display_->GenerateFenceSyncRelease(); + NOTREACHED(); + return 0; } bool Context::IsFenceSyncReleased(uint64_t release) { - NOTIMPLEMENTED(); + NOTREACHED(); return false; } void Context::SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } -void Context::WaitSyncTokenHint(const gpu::SyncToken& sync_token) {} +void Context::WaitSyncToken(const gpu::SyncToken& sync_token) { + NOTREACHED(); +} bool Context::CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) { return false;
diff --git a/gpu/gles2_conform_support/egl/context.h b/gpu/gles2_conform_support/egl/context.h index 3123401..914d3bd0 100644 --- a/gpu/gles2_conform_support/egl/context.h +++ b/gpu/gles2_conform_support/egl/context.h
@@ -80,7 +80,7 @@ bool IsFenceSyncReleased(uint64_t release) override; void SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) override; - void WaitSyncTokenHint(const gpu::SyncToken& sync_token) override; + void WaitSyncToken(const gpu::SyncToken& sync_token) override; bool CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) override; // Called by ThreadState to set the needed global variables when this context
diff --git a/gpu/ipc/client/command_buffer_proxy_impl.cc b/gpu/ipc/client/command_buffer_proxy_impl.cc index 3828b8b..2d5cc9fe 100644 --- a/gpu/ipc/client/command_buffer_proxy_impl.cc +++ b/gpu/ipc/client/command_buffer_proxy_impl.cc
@@ -270,10 +270,6 @@ last_put_offset_ = put_offset; last_flush_id_ = channel_->OrderingBarrier( route_id_, put_offset, std::move(pending_sync_token_fences_)); - - pending_sync_token_fences_.clear(); - - flushed_fence_sync_release_ = next_fence_sync_release_ - 1; } void CommandBufferProxyImpl::SetUpdateVSyncParametersCallback( @@ -436,13 +432,9 @@ bool requires_sync_token = handle.type == gfx::IO_SURFACE_BUFFER; uint64_t image_fence_sync = 0; - if (requires_sync_token) { + if (requires_sync_token) image_fence_sync = GenerateFenceSyncRelease(); - // Make sure fence syncs were flushed before CreateImage() was called. - DCHECK_EQ(image_fence_sync, flushed_fence_sync_release_ + 1); - } - DCHECK(gpu::IsImageFromGpuMemoryBufferFormatSupported( gpu_memory_buffer->GetFormat(), capabilities_)); DCHECK(gpu::IsImageSizeValidForGpuMemoryBufferFormat( @@ -548,8 +540,7 @@ signal_tasks_.insert(std::make_pair(signal_id, std::move(callback))); } -void CommandBufferProxyImpl::WaitSyncTokenHint( - const gpu::SyncToken& sync_token) { +void CommandBufferProxyImpl::WaitSyncToken(const gpu::SyncToken& sync_token) { CheckLock(); base::AutoLock lock(last_state_lock_); if (last_state_.error != gpu::error::kNoError) @@ -656,8 +647,9 @@ if (last_state_.error != gpu::error::kNoError) return; - Send(new GpuCommandBufferMsg_WaitSyncToken(route_id_, sync_token)); - Send(new GpuCommandBufferMsg_ReturnFrontBuffer(route_id_, mailbox, is_lost)); + last_flush_id_ = channel_->EnqueueDeferredMessage( + GpuCommandBufferMsg_ReturnFrontBuffer(route_id_, mailbox, is_lost), + {sync_token}); } bool CommandBufferProxyImpl::Send(IPC::Message* msg) {
diff --git a/gpu/ipc/client/command_buffer_proxy_impl.h b/gpu/ipc/client/command_buffer_proxy_impl.h index 6f74b8a..f4406ba 100644 --- a/gpu/ipc/client/command_buffer_proxy_impl.h +++ b/gpu/ipc/client/command_buffer_proxy_impl.h
@@ -128,7 +128,7 @@ bool IsFenceSyncReleased(uint64_t release) override; void SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) override; - void WaitSyncTokenHint(const gpu::SyncToken& sync_token) override; + void WaitSyncToken(const gpu::SyncToken& sync_token) override; bool CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) override; void TakeFrontBuffer(const gpu::Mailbox& mailbox); void ReturnFrontBuffer(const gpu::Mailbox& mailbox, @@ -262,12 +262,6 @@ // Sync token waits that haven't been flushed yet. std::vector<SyncToken> pending_sync_token_fences_; - // Last flushed fence sync release, same as last item in queue if not empty. - uint64_t flushed_fence_sync_release_ = 0; - - // Last verified fence sync. - uint64_t verified_fence_sync_release_ = 0; - GpuConsoleMessageCallback console_message_callback_; // Tasks to be invoked in SignalSyncPoint responses.
diff --git a/gpu/ipc/client/gpu_channel_host.cc b/gpu/ipc/client/gpu_channel_host.cc index ca15352..b54f89c 100644 --- a/gpu/ipc/client/gpu_channel_host.cc +++ b/gpu/ipc/client/gpu_channel_host.cc
@@ -154,7 +154,8 @@ deferred_message.message = GpuCommandBufferMsg_AsyncFlush( pending_ordering_barrier_->route_id, pending_ordering_barrier_->put_offset, - pending_ordering_barrier_->deferred_message_id); + pending_ordering_barrier_->deferred_message_id, + pending_ordering_barrier_->sync_token_fences); deferred_message.sync_token_fences = std::move(pending_ordering_barrier_->sync_token_fences); deferred_messages_.push_back(std::move(deferred_message));
diff --git a/gpu/ipc/client/shared_image_interface_proxy.cc b/gpu/ipc/client/shared_image_interface_proxy.cc index 7dccdbf..5b4ceff 100644 --- a/gpu/ipc/client/shared_image_interface_proxy.cc +++ b/gpu/ipc/client/shared_image_interface_proxy.cc
@@ -4,20 +4,57 @@ #include "gpu/ipc/client/shared_image_interface_proxy.h" +#include "base/bits.h" #include "gpu/command_buffer/client/gpu_memory_buffer_manager.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" #include "gpu/ipc/client/gpu_channel_host.h" #include "gpu/ipc/common/command_buffer_id.h" #include "gpu/ipc/common/gpu_messages.h" #include "gpu/ipc/common/gpu_param_traits_macros.h" +#include "mojo/public/cpp/base/shared_memory_utils.h" namespace gpu { +namespace { + +bool SafeIncrementAndAlign(size_t aligned_value, + size_t increment, + size_t alignment, + size_t* result) { + base::CheckedNumeric<size_t> sum = aligned_value; + sum += increment; + // Taken from base::bits::Align. + // TODO(ericrk): Update base::bits::Align to handle CheckedNumeric. + DCHECK(base::bits::IsPowerOfTwo(alignment)); + sum = (sum + alignment - 1) & ~(alignment - 1); + return sum.AssignIfValid(result); +} + +size_t GetRemainingSize(const base::MappedReadOnlyRegion& region, + size_t offset) { + if (offset > region.mapping.size()) + return 0; + return region.mapping.size() - offset; +} + +void* GetDataAddress(const base::MappedReadOnlyRegion& region, + size_t offset, + size_t size) { + base::CheckedNumeric<size_t> safe_end = offset; + safe_end += size; + size_t end; + if (!safe_end.AssignIfValid(&end) || end > region.mapping.size()) + return nullptr; + return region.mapping.GetMemoryAs<uint8_t>() + offset; +} + +} // namespace SharedImageInterfaceProxy::SharedImageInterfaceProxy(GpuChannelHost* host, int32_t route_id) : host_(host), route_id_(route_id) {} SharedImageInterfaceProxy::~SharedImageInterfaceProxy() = default; + Mailbox SharedImageInterfaceProxy::CreateSharedImage( viz::ResourceFormat format, const gfx::Size& size, @@ -41,6 +78,47 @@ } Mailbox SharedImageInterfaceProxy::CreateSharedImage( + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) { + // Pixel data's size must fit into a uint32_t to be sent via + // GpuChannelMsg_CreateSharedImageWithData_Params. + if (!base::IsValueInRangeForNumericType<uint32_t>(pixel_data.size())) { + LOG(ERROR) + << "CreateSharedImage: SharedImage upload data overflows uint32_t"; + return Mailbox(); + } + + // Hold the lock for the rest of this function, as we need to ensure that SHM + // reallocation / registration and the following use of that SHM via deferred + // message are not interrupted by a SHM allocation on another thread. + base::AutoLock lock(lock_); + + bool done_with_shm; + size_t shm_offset; + if (!GetSHMForPixelData(pixel_data, &shm_offset, &done_with_shm)) { + LOG(ERROR) << "CreateSharedImage: Could not get SHM for data upload."; + return Mailbox(); + } + + GpuChannelMsg_CreateSharedImageWithData_Params params; + params.mailbox = Mailbox::Generate(); + params.format = format; + params.size = size; + params.color_space = color_space; + params.usage = usage; + params.pixel_data_offset = shm_offset; + params.pixel_data_size = pixel_data.size(); + params.done_with_shm = done_with_shm; + params.release_id = ++next_release_id_; + last_flush_id_ = host_->EnqueueDeferredMessage( + GpuChannelMsg_CreateSharedImageWithData(route_id_, params)); + return params.mailbox; +} + +Mailbox SharedImageInterfaceProxy::CreateSharedImage( gfx::GpuMemoryBuffer* gpu_memory_buffer, GpuMemoryBufferManager* gpu_memory_buffer_manager, const gfx::ColorSpace& color_space, @@ -140,4 +218,67 @@ next_release_id_); } +bool SharedImageInterfaceProxy::GetSHMForPixelData( + base::span<const uint8_t> pixel_data, + size_t* shm_offset, + bool* done_with_shm) { + const size_t kUploadBufferSize = 1 * 1024 * 1024; // 1MB + *shm_offset = 0; + *done_with_shm = false; + + lock_.AssertAcquired(); + if (!upload_buffer_.IsValid() || + GetRemainingSize(upload_buffer_, upload_buffer_offset_) < + pixel_data.size()) { + size_t size_to_alloc = std::max(kUploadBufferSize, pixel_data.size()); + auto shm = mojo::CreateReadOnlySharedMemoryRegion(size_to_alloc); + if (!shm.IsValid()) + return false; + + // Duplicate the buffer for sharing to the GPU process. + base::ReadOnlySharedMemoryRegion shared_shm = shm.region.Duplicate(); + if (!shared_shm.IsValid()) + return false; + + // Share the SHM to the GPU process. In order to ensure that any deferred + // messages which rely on the previous SHM have a chance to execute before + // it is replaced, flush before sending. + host_->EnsureFlush(last_flush_id_); + host_->Send(new GpuChannelMsg_RegisterSharedImageUploadBuffer( + route_id_, std::move(shared_shm))); + + upload_buffer_ = std::move(shm); + upload_buffer_offset_ = 0; + } + + // We now have an |upload_buffer_| that fits our data. + + void* target = + GetDataAddress(upload_buffer_, upload_buffer_offset_, pixel_data.size()); + DCHECK(target); + memcpy(target, pixel_data.data(), pixel_data.size()); + *shm_offset = upload_buffer_offset_; + + // Now that we've successfully used up a portion of our buffer, increase our + // |upload_buffer_offset_|. If our |upload_buffer_offset_| is at the end (or + // past the end with rounding), we discard the current buffer. We'll allocate + // a new buffer the next time we enter this function. + bool discard_buffer = false; + if (SafeIncrementAndAlign(upload_buffer_offset_, pixel_data.size(), + 4 /* alignment */, &upload_buffer_offset_)) { + discard_buffer = + GetRemainingSize(upload_buffer_, upload_buffer_offset_) == 0; + } else { + discard_buffer = true; + } + + if (discard_buffer) { + *done_with_shm = true; + upload_buffer_ = base::MappedReadOnlyRegion(); + upload_buffer_offset_ = 0; + } + + return true; +} + } // namespace gpu
diff --git a/gpu/ipc/client/shared_image_interface_proxy.h b/gpu/ipc/client/shared_image_interface_proxy.h index 1a833f09..4717899 100644 --- a/gpu/ipc/client/shared_image_interface_proxy.h +++ b/gpu/ipc/client/shared_image_interface_proxy.h
@@ -5,9 +5,11 @@ #ifndef GPU_IPC_CLIENT_SHARED_IMAGE_INTERFACE_PROXY_H_ #define GPU_IPC_CLIENT_SHARED_IMAGE_INTERFACE_PROXY_H_ +#include "base/memory/read_only_shared_memory_region.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "gpu/command_buffer/client/shared_image_interface.h" +#include "gpu/command_buffer/common/buffer.h" namespace gpu { class GpuChannelHost; @@ -22,6 +24,11 @@ const gfx::Size& size, const gfx::ColorSpace& color_space, uint32_t usage) override; + Mailbox CreateSharedImage(viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) override; Mailbox CreateSharedImage(gfx::GpuMemoryBuffer* gpu_memory_buffer, GpuMemoryBufferManager* gpu_memory_buffer_manager, const gfx::ColorSpace& color_space, @@ -34,11 +41,20 @@ SyncToken GenUnverifiedSyncToken() override; private: + bool GetSHMForPixelData(base::span<const uint8_t> pixel_data, + size_t* shm_offset, + bool* done_with_shm) EXCLUSIVE_LOCKS_REQUIRED(lock_); + GpuChannelHost* const host_; const int32_t route_id_; base::Lock lock_; uint32_t next_release_id_ GUARDED_BY(lock_) = 0; uint32_t last_flush_id_ GUARDED_BY(lock_) = 0; + + // A buffer used to upload initial data during SharedImage creation. + base::MappedReadOnlyRegion upload_buffer_ GUARDED_BY(lock_); + // The offset into |upload_buffer_| at which data is no longer used. + size_t upload_buffer_offset_ GUARDED_BY(lock_) = 0; }; } // namespace gpu
diff --git a/gpu/ipc/command_buffer_task_executor.h b/gpu/ipc/command_buffer_task_executor.h index 0e593ae7..02fe7c51 100644 --- a/gpu/ipc/command_buffer_task_executor.h +++ b/gpu/ipc/command_buffer_task_executor.h
@@ -57,9 +57,6 @@ // Returns true if sequence should yield while running its current task. virtual bool ShouldYield() = 0; - // Enables or disables further execution of tasks in this sequence. - virtual void SetEnabled(bool enabled) = 0; - // Schedule a task with provided sync token dependencies. The dependencies // are hints for sync token waits within the task, and can be ignored by the // implementation. @@ -83,10 +80,6 @@ // Creates a memory tracker for the context group if this returns true. virtual bool ShouldCreateMemoryTracker() const = 0; - // Block thread when a WaitSyncToken command is encountered instead of calling - // OnWaitSyncToken(). - virtual bool BlockThreadOnWaitSyncToken() const = 0; - // Schedules |task| to run out of order with respect to other sequenced tasks. virtual void ScheduleOutOfOrderTask(base::OnceClosure task) = 0;
diff --git a/gpu/ipc/common/gpu_messages.h b/gpu/ipc/common/gpu_messages.h index fa20b5ab..4d8771b 100644 --- a/gpu/ipc/common/gpu_messages.h +++ b/gpu/ipc/common/gpu_messages.h
@@ -83,6 +83,18 @@ IPC_STRUCT_MEMBER(uint32_t, release_id) IPC_STRUCT_END() +IPC_STRUCT_BEGIN(GpuChannelMsg_CreateSharedImageWithData_Params) + IPC_STRUCT_MEMBER(gpu::Mailbox, mailbox) + IPC_STRUCT_MEMBER(viz::ResourceFormat, format) + IPC_STRUCT_MEMBER(gfx::Size, size) + IPC_STRUCT_MEMBER(gfx::ColorSpace, color_space) + IPC_STRUCT_MEMBER(uint32_t, usage) + IPC_STRUCT_MEMBER(uint32_t, release_id) + IPC_STRUCT_MEMBER(uint32_t, pixel_data_offset) + IPC_STRUCT_MEMBER(uint32_t, pixel_data_size) + IPC_STRUCT_MEMBER(bool, done_with_shm) +IPC_STRUCT_END() + IPC_STRUCT_BEGIN(GpuChannelMsg_CreateGMBSharedImage_Params) IPC_STRUCT_MEMBER(gpu::Mailbox, mailbox) IPC_STRUCT_MEMBER(gfx::GpuMemoryBufferHandle, handle) @@ -136,12 +148,16 @@ IPC_MESSAGE_ROUTED1(GpuChannelMsg_CreateSharedImage, GpuChannelMsg_CreateSharedImage_Params /* params */) +IPC_MESSAGE_ROUTED1(GpuChannelMsg_CreateSharedImageWithData, + GpuChannelMsg_CreateSharedImageWithData_Params /* params */) IPC_MESSAGE_ROUTED1(GpuChannelMsg_CreateGMBSharedImage, GpuChannelMsg_CreateGMBSharedImage_Params /* params */) IPC_MESSAGE_ROUTED2(GpuChannelMsg_UpdateSharedImage, gpu::Mailbox /* id */, uint32_t /* release_id */) IPC_MESSAGE_ROUTED1(GpuChannelMsg_DestroySharedImage, gpu::Mailbox /* id */) +IPC_MESSAGE_ROUTED1(GpuChannelMsg_RegisterSharedImageUploadBuffer, + base::ReadOnlySharedMemoryRegion /* shm */) // Schedules a hardware-accelerated image decode in the GPU process. Renderers // should use gpu::ImageDecodeAcceleratorProxy to schedule decode requests which @@ -216,9 +232,10 @@ // TODO(sunnyps): This is an internal implementation detail of the gpu service // and is not sent by the client. Remove this once the non-scheduler code path // is removed. -IPC_MESSAGE_ROUTED2(GpuCommandBufferMsg_AsyncFlush, +IPC_MESSAGE_ROUTED3(GpuCommandBufferMsg_AsyncFlush, int32_t /* put_offset */, - uint32_t /* flush_id */) + uint32_t /* flush_id */, + std::vector<gpu::SyncToken> /* sync_token_fences */) // Sent by the GPU process to display messages in the console. IPC_MESSAGE_ROUTED1(GpuCommandBufferMsg_ConsoleMsg, @@ -248,10 +265,6 @@ uint64_t, /* swap_id */ gfx::PresentationFeedback /* feedback */) -// The receiver will stop processing messages until the Synctoken is signaled. -IPC_MESSAGE_ROUTED1(GpuCommandBufferMsg_WaitSyncToken, - gpu::SyncToken /* sync_token */) - // The receiver will asynchronously wait until the SyncToken is signaled, and // then return a GpuCommandBufferMsg_SignalAck message. IPC_MESSAGE_ROUTED2(GpuCommandBufferMsg_SignalSyncToken,
diff --git a/gpu/ipc/gpu_in_process_thread_service.cc b/gpu/ipc/gpu_in_process_thread_service.cc index 3d3c773..c0d6edd 100644 --- a/gpu/ipc/gpu_in_process_thread_service.cc +++ b/gpu/ipc/gpu_in_process_thread_service.cc
@@ -28,13 +28,6 @@ bool ShouldYield() override { return scheduler_->ShouldYield(sequence_id_); } - void SetEnabled(bool enabled) override { - if (enabled) - scheduler_->EnableSequence(sequence_id_); - else - scheduler_->DisableSequence(sequence_id_); - } - void ScheduleTask(base::OnceClosure task, std::vector<SyncToken> sync_token_fences) override { scheduler_->ScheduleTask(Scheduler::Task(sequence_id_, std::move(task), @@ -82,10 +75,6 @@ return true; } -bool GpuInProcessThreadService::BlockThreadOnWaitSyncToken() const { - return false; -} - std::unique_ptr<CommandBufferTaskExecutor::Sequence> GpuInProcessThreadService::CreateSequence() { return std::make_unique<SchedulerSequence>(scheduler_);
diff --git a/gpu/ipc/gpu_in_process_thread_service.h b/gpu/ipc/gpu_in_process_thread_service.h index 1527230..df52823 100644 --- a/gpu/ipc/gpu_in_process_thread_service.h +++ b/gpu/ipc/gpu_in_process_thread_service.h
@@ -35,7 +35,6 @@ // CommandBufferTaskExecutor implementation. bool ForceVirtualizedGLContexts() const override; bool ShouldCreateMemoryTracker() const override; - bool BlockThreadOnWaitSyncToken() const override; std::unique_ptr<CommandBufferTaskExecutor::Sequence> CreateSequence() override; void ScheduleOutOfOrderTask(base::OnceClosure task) override;
diff --git a/gpu/ipc/in_process_command_buffer.cc b/gpu/ipc/in_process_command_buffer.cc index ec9ba9d..62b04ec 100644 --- a/gpu/ipc/in_process_command_buffer.cc +++ b/gpu/ipc/in_process_command_buffer.cc
@@ -148,6 +148,28 @@ return mailbox; } + Mailbox CreateSharedImage(viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + base::span<const uint8_t> pixel_data) override { + auto mailbox = Mailbox::Generate(); + std::vector<uint8_t> pixel_data_copy(pixel_data.begin(), pixel_data.end()); + { + base::AutoLock lock(lock_); + // Note: we enqueue the task under the lock to guarantee monotonicity of + // the release ids as seen by the service. Unretained is safe because + // InProcessCommandBuffer synchronizes with the GPU thread at destruction + // time, cancelling tasks, before |this| is destroyed. + parent_->ScheduleGpuTask(base::BindOnce( + &InProcessCommandBuffer::CreateSharedImageWithDataOnGpuThread, + gpu_thread_weak_ptr_, mailbox, format, size, color_space, usage, + MakeSyncToken(next_fence_sync_release_++), + std::move(pixel_data_copy))); + } + return mailbox; + } + Mailbox CreateSharedImage(gfx::GpuMemoryBuffer* gpu_memory_buffer, GpuMemoryBufferManager* gpu_memory_buffer_manager, const gfx::ColorSpace& color_space, @@ -794,16 +816,29 @@ return false; } -void InProcessCommandBuffer::FlushOnGpuThread(int32_t put_offset) { +void InProcessCommandBuffer::FlushOnGpuThread( + int32_t put_offset, + const std::vector<SyncToken>& sync_token_fences) { DCHECK_CALLED_ON_VALID_SEQUENCE(gpu_sequence_checker_); TRACE_EVENT1("gpu", "InProcessCommandBuffer::FlushOnGpuThread", "put_offset", put_offset); ScopedEvent handle_flush(&flush_event_); + // Check if sync token waits are invalid or already complete. Do not use + // SyncPointManager::IsSyncTokenReleased() as it can't say if the wait is + // invalid. + for (const auto& sync_token : sync_token_fences) + DCHECK(!sync_point_client_state_->Wait(sync_token, base::DoNothing())); if (!MakeCurrent()) return; + MailboxManager* mailbox_manager = context_group_->mailbox_manager(); + if (mailbox_manager->UsesSync()) { + for (const auto& sync_token : sync_token_fences) + mailbox_manager->PullTextureUpdates(sync_token); + } + { base::Optional<raster::GrShaderCache::ScopedCacheUse> cache_use; if (gr_shader_cache_) @@ -816,10 +851,9 @@ bool has_unprocessed_commands = HasUnprocessedCommandsOnGpuThread(); if (!command_buffer_->scheduled() || has_unprocessed_commands) { - DCHECK(!task_executor_->BlockThreadOnWaitSyncToken()); ContinueGpuTask(base::BindOnce(&InProcessCommandBuffer::FlushOnGpuThread, gpu_thread_weak_ptr_factory_.GetWeakPtr(), - put_offset)); + put_offset, sync_token_fences)); } // If we've processed all pending commands but still have pending queries, @@ -866,15 +900,16 @@ put_offset); last_put_offset_ = put_offset; - flushed_fence_sync_release_ = next_fence_sync_release_ - 1; std::vector<SyncToken> sync_token_fences; next_flush_sync_token_fences_.swap(sync_token_fences); - ScheduleGpuTask( - base::BindOnce(&InProcessCommandBuffer::FlushOnGpuThread, - gpu_thread_weak_ptr_factory_.GetWeakPtr(), put_offset), - std::move(sync_token_fences)); + // Don't use std::move() for |sync_token_fences| because evaluation order for + // arguments is not defined. + ScheduleGpuTask(base::BindOnce(&InProcessCommandBuffer::FlushOnGpuThread, + gpu_thread_weak_ptr_factory_.GetWeakPtr(), + put_offset, sync_token_fences), + sync_token_fences); } void InProcessCommandBuffer::OrderingBarrier(int32_t put_offset) { @@ -998,13 +1033,9 @@ bool requires_sync_point = handle.type == gfx::IO_SURFACE_BUFFER; uint64_t fence_sync = 0; - if (requires_sync_point) { + if (requires_sync_point) fence_sync = GenerateFenceSyncRelease(); - // Previous fence syncs should be flushed already. - DCHECK_EQ(fence_sync - 1, flushed_fence_sync_release_); - } - ScheduleGpuTask(base::BindOnce( &InProcessCommandBuffer::CreateImageOnGpuThread, gpu_thread_weak_ptr_factory_.GetWeakPtr(), new_id, std::move(handle), @@ -1013,7 +1044,6 @@ gpu_memory_buffer->GetFormat(), fence_sync)); if (fence_sync) { - flushed_fence_sync_release_ = fence_sync; SyncToken sync_token(GetNamespaceID(), GetCommandBufferID(), fence_sync); sync_token.SetVerifyFlush(); gpu_memory_buffer_manager_->SetDestructionSyncToken(gpu_memory_buffer, @@ -1112,58 +1142,13 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(gpu_sequence_checker_); SyncToken sync_token(GetNamespaceID(), GetCommandBufferID(), release); - context_group_->mailbox_manager()->PushTextureUpdates(sync_token); - sync_point_client_state_->ReleaseFenceSync(release); -} - -// TODO(sunnyps): Remove the wait command once all sync tokens are passed as -// task dependencies. -bool InProcessCommandBuffer::OnWaitSyncToken(const SyncToken& sync_token) { - DCHECK_CALLED_ON_VALID_SEQUENCE(gpu_sequence_checker_); - DCHECK(!waiting_for_sync_point_); - TRACE_EVENT0("gpu", "InProcessCommandBuffer::OnWaitSyncToken"); - - SyncPointManager* sync_point_manager = task_executor_->sync_point_manager(); - DCHECK(sync_point_manager); MailboxManager* mailbox_manager = context_group_->mailbox_manager(); - DCHECK(mailbox_manager); + if (mailbox_manager->UsesSync()) + mailbox_manager->PushTextureUpdates(sync_token); - if (task_executor_->BlockThreadOnWaitSyncToken()) { - // Wait if sync point wait is valid. - if (sync_point_client_state_->Wait( - sync_token, - base::Bind(&base::WaitableEvent::Signal, - base::Unretained(&fence_sync_wait_event_)))) { - fence_sync_wait_event_.Wait(); - } - - mailbox_manager->PullTextureUpdates(sync_token); - return false; - } - - waiting_for_sync_point_ = sync_point_client_state_->Wait( - sync_token, - base::Bind(&InProcessCommandBuffer::OnWaitSyncTokenCompleted, - gpu_thread_weak_ptr_factory_.GetWeakPtr(), sync_token)); - if (!waiting_for_sync_point_) { - mailbox_manager->PullTextureUpdates(sync_token); - return false; - } - - command_buffer_->SetScheduled(false); - task_sequence_->SetEnabled(false); - return true; -} - -void InProcessCommandBuffer::OnWaitSyncTokenCompleted( - const SyncToken& sync_token) { - DCHECK_CALLED_ON_VALID_SEQUENCE(gpu_sequence_checker_); - DCHECK(waiting_for_sync_point_); - context_group_->mailbox_manager()->PullTextureUpdates(sync_token); - waiting_for_sync_point_ = false; - command_buffer_->SetScheduled(true); - task_sequence_->SetEnabled(true); + command_buffer_->SetReleaseCount(release); + sync_point_client_state_->ReleaseFenceSync(release); } void InProcessCommandBuffer::OnDescheduleUntilFinished() { @@ -1341,6 +1326,30 @@ shared_image_client_state_->ReleaseFenceSync(sync_token.release_count()); } +void InProcessCommandBuffer::CreateSharedImageWithDataOnGpuThread( + const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + const SyncToken& sync_token, + std::vector<uint8_t> pixel_data) { + DCHECK_CALLED_ON_VALID_SEQUENCE(gpu_sequence_checker_); + // |shared_image_factory_| never writes to the surface, so skip unnecessary + // MakeCurrent to improve performance. https://crbug.com/457431 + if (!context_->IsCurrent(nullptr) && !MakeCurrent()) + return; + LazyCreateSharedImageFactory(); + if (!shared_image_factory_->CreateSharedImage( + mailbox, format, size, color_space, usage, pixel_data)) { + // Signal errors by losing the command buffer. + command_buffer_->SetParseError(error::kLostContext); + return; + } + context_group_->mailbox_manager()->PushTextureUpdates(sync_token); + shared_image_client_state_->ReleaseFenceSync(sync_token.release_count()); +} + void InProcessCommandBuffer::CreateGMBSharedImageOnGpuThread( const Mailbox& mailbox, gfx::GpuMemoryBufferHandle handle, @@ -1425,7 +1434,7 @@ return release <= GetLastState().release_count; } -void InProcessCommandBuffer::WaitSyncTokenHint(const SyncToken& sync_token) { +void InProcessCommandBuffer::WaitSyncToken(const SyncToken& sync_token) { next_flush_sync_token_fences_.push_back(sync_token); }
diff --git a/gpu/ipc/in_process_command_buffer.h b/gpu/ipc/in_process_command_buffer.h index 038ddf3..0e82c3f 100644 --- a/gpu/ipc/in_process_command_buffer.h +++ b/gpu/ipc/in_process_command_buffer.h
@@ -139,7 +139,7 @@ bool IsFenceSyncReleased(uint64_t release) override; void SignalSyncToken(const SyncToken& sync_token, base::OnceClosure callback) override; - void WaitSyncTokenHint(const SyncToken& sync_token) override; + void WaitSyncToken(const SyncToken& sync_token) override; bool CanWaitUnverifiedSyncToken(const SyncToken& sync_token) override; // CommandBufferServiceClient implementation (called on gpu thread): @@ -150,7 +150,6 @@ void OnConsoleMessage(int32_t id, const std::string& message) override; void CacheShader(const std::string& key, const std::string& shader) override; void OnFenceSyncRelease(uint64_t release) override; - bool OnWaitSyncToken(const SyncToken& sync_token) override; void OnDescheduleUntilFinished() override; void OnRescheduleAfterFinished() override; void OnSwapBuffers(uint64_t swap_id, uint32_t flags) override; @@ -227,7 +226,8 @@ // Flush up to put_offset. If execution is deferred either by yielding, or due // to a sync token wait, HasUnprocessedCommandsOnGpuThread() returns true. - void FlushOnGpuThread(int32_t put_offset); + void FlushOnGpuThread(int32_t put_offset, + const std::vector<SyncToken>& sync_token_fences); bool HasUnprocessedCommandsOnGpuThread(); void UpdateLastStateOnGpuThread(); @@ -275,6 +275,13 @@ const gfx::ColorSpace& color_space, uint32_t usage, const SyncToken& sync_token); + void CreateSharedImageWithDataOnGpuThread(const Mailbox& mailbox, + viz::ResourceFormat format, + const gfx::Size& size, + const gfx::ColorSpace& color_space, + uint32_t usage, + const SyncToken& sync_token, + std::vector<uint8_t> pixel_data); void CreateGMBSharedImageOnGpuThread(const Mailbox& mailbox, gfx::GpuMemoryBufferHandle handle, gfx::BufferFormat format, @@ -288,7 +295,6 @@ // Callbacks on the gpu thread. void PerformDelayedWorkOnGpuThread(); - void OnWaitSyncTokenCompleted(const SyncToken& sync_token); // Callback implementations on the client thread. void OnContextLost(); @@ -301,7 +307,6 @@ // Members accessed on the gpu thread (possibly with the exception of // creation): - bool waiting_for_sync_point_ = false; bool use_virtualized_gl_context_ = false; raster::GrShaderCache* gr_shader_cache_ = nullptr; scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner_; @@ -333,7 +338,6 @@ Capabilities capabilities_; GpuMemoryBufferManager* gpu_memory_buffer_manager_ = nullptr; uint64_t next_fence_sync_release_ = 1; - uint64_t flushed_fence_sync_release_ = 0; std::vector<SyncToken> next_flush_sync_token_fences_; // Sequence checker for client sequence used for initialization, destruction, // callbacks, such as context loss, and methods which provide such callbacks,
diff --git a/gpu/ipc/service/BUILD.gn b/gpu/ipc/service/BUILD.gn index d72bdb1..e33a4d3 100644 --- a/gpu/ipc/service/BUILD.gn +++ b/gpu/ipc/service/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. -import("//testing/test.gni") import("//build/config/jumbo.gni") import("//build/config/ui.gni") import("//gpu/vulkan/features.gni") +import("//testing/test.gni") if (is_mac) { import("//build/config/mac/mac_sdk.gni") } @@ -31,6 +31,7 @@ "gpu_watchdog_thread.h", "image_decode_accelerator_stub.cc", "image_decode_accelerator_stub.h", + "image_decode_accelerator_worker.h", "image_transport_surface.h", "image_transport_surface_delegate.h", "pass_through_image_transport_surface.cc",
diff --git a/gpu/ipc/service/command_buffer_stub.cc b/gpu/ipc/service/command_buffer_stub.cc index 4192a23..d1bc3cf 100644 --- a/gpu/ipc/service/command_buffer_stub.cc +++ b/gpu/ipc/service/command_buffer_stub.cc
@@ -150,7 +150,6 @@ stream_id_(stream_id), route_id_(route_id), last_flush_id_(0), - waiting_for_sync_point_(false), previous_processed_num_(0), wait_set_get_buffer_count_(0) {} @@ -176,7 +175,6 @@ message.type() != GpuCommandBufferMsg_WaitForGetOffsetInRange::ID && message.type() != GpuCommandBufferMsg_RegisterTransferBuffer::ID && message.type() != GpuCommandBufferMsg_DestroyTransferBuffer::ID && - message.type() != GpuCommandBufferMsg_WaitSyncToken::ID && message.type() != GpuCommandBufferMsg_SignalSyncToken::ID && message.type() != GpuCommandBufferMsg_SignalQuery::ID) { if (!MakeCurrent()) @@ -201,7 +199,6 @@ OnRegisterTransferBuffer); IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_DestroyTransferBuffer, OnDestroyTransferBuffer); - IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_WaitSyncToken, OnWaitSyncToken) IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalSyncToken, OnSignalSyncToken) IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_SignalQuery, OnSignalQuery) IPC_MESSAGE_HANDLER(GpuCommandBufferMsg_CreateImage, OnCreateImage); @@ -517,7 +514,10 @@ } } -void CommandBufferStub::OnAsyncFlush(int32_t put_offset, uint32_t flush_id) { +void CommandBufferStub::OnAsyncFlush( + int32_t put_offset, + uint32_t flush_id, + const std::vector<SyncToken>& sync_token_fences) { TRACE_EVENT1("gpu", "CommandBufferStub::OnAsyncFlush", "put_offset", put_offset); DCHECK(command_buffer_); @@ -525,11 +525,22 @@ // to catch regressions. Ignore the message. DVLOG_IF(0, flush_id - last_flush_id_ >= 0x8000000U) << "Received a Flush message out-of-order"; + // Check if sync token waits are invalid or already complete. Do not use + // SyncPointManager::IsSyncTokenReleased() as it can't say if the wait is + // invalid. + for (const auto& sync_token : sync_token_fences) + DCHECK(!sync_point_client_state_->Wait(sync_token, base::DoNothing())); last_flush_id_ = flush_id; CommandBuffer::State pre_state = command_buffer_->GetState(); FastSetActiveURL(active_url_, active_url_hash_, channel_); + MailboxManager* mailbox_manager = context_group_->mailbox_manager(); + if (mailbox_manager->UsesSync()) { + for (const auto& sync_token : sync_token_fences) + mailbox_manager->PullTextureUpdates(sync_token); + } + { auto* gr_shader_cache = channel_->gpu_channel_manager()->gr_shader_cache(); base::Optional<raster::GrShaderCache::ScopedCacheUse> cache_use; @@ -680,43 +691,6 @@ channel_->gpu_channel_manager()->ScheduleGrContextCleanup(); } -// TODO(sunnyps): Remove the wait command once all sync tokens are passed as -// task dependencies. -bool CommandBufferStub::OnWaitSyncToken(const SyncToken& sync_token) { - DCHECK(!waiting_for_sync_point_); - DCHECK(command_buffer_->scheduled()); - TRACE_EVENT_ASYNC_BEGIN1("gpu", "WaitSyncToken", this, "CommandBufferStub", - this); - - waiting_for_sync_point_ = sync_point_client_state_->WaitNonThreadSafe( - sync_token, channel_->task_runner(), - base::Bind(&CommandBufferStub::OnWaitSyncTokenCompleted, AsWeakPtr(), - sync_token)); - - if (waiting_for_sync_point_) { - command_buffer_->SetScheduled(false); - channel_->OnCommandBufferDescheduled(this); - return true; - } - - MailboxManager* mailbox_manager = context_group_->mailbox_manager(); - if (mailbox_manager->UsesSync() && MakeCurrent()) - mailbox_manager->PullTextureUpdates(sync_token); - return false; -} - -void CommandBufferStub::OnWaitSyncTokenCompleted(const SyncToken& sync_token) { - DCHECK(waiting_for_sync_point_); - TRACE_EVENT_ASYNC_END1("gpu", "WaitSyncToken", this, "CommandBufferStub", - this); - // Don't call PullTextureUpdates here because we can't MakeCurrent if we're - // executing commands on another context. The WaitSyncToken command will run - // again and call PullTextureUpdates once this command buffer gets scheduled. - waiting_for_sync_point_ = false; - command_buffer_->SetScheduled(true); - channel_->OnCommandBufferScheduled(this); -} - void CommandBufferStub::OnCreateImage( GpuCommandBufferMsg_CreateImage_Params params) { TRACE_EVENT0("gpu", "CommandBufferStub::OnCreateImage");
diff --git a/gpu/ipc/service/command_buffer_stub.h b/gpu/ipc/service/command_buffer_stub.h index 32a979f..6a561de 100644 --- a/gpu/ipc/service/command_buffer_stub.h +++ b/gpu/ipc/service/command_buffer_stub.h
@@ -97,7 +97,6 @@ void OnConsoleMessage(int32_t id, const std::string& message) override; void CacheShader(const std::string& key, const std::string& shader) override; void OnFenceSyncRelease(uint64_t release) override; - bool OnWaitSyncToken(const SyncToken& sync_token) override; void OnDescheduleUntilFinished() override; void OnRescheduleAfterFinished() override; void ScheduleGrContextCleanup() override; @@ -189,7 +188,9 @@ int32_t start, int32_t end, IPC::Message* reply_message); - void OnAsyncFlush(int32_t put_offset, uint32_t flush_id); + void OnAsyncFlush(int32_t put_offset, + uint32_t flush_id, + const std::vector<SyncToken>& sync_token_fences); void OnRegisterTransferBuffer(int32_t id, base::UnsafeSharedMemoryRegion transfer_buffer); void OnDestroyTransferBuffer(int32_t id); @@ -204,8 +205,6 @@ const gfx::GpuFenceHandle& handle); void OnGetGpuFenceHandle(uint32_t gpu_fence_id); - void OnWaitSyncTokenCompleted(const SyncToken& sync_token); - void OnCreateImage(GpuCommandBufferMsg_CreateImage_Params params); void OnDestroyImage(int32_t id); void OnCreateStreamTexture(uint32_t texture_id, @@ -237,8 +236,6 @@ base::ObserverList<DestructionObserver>::Unchecked destruction_observers_; - bool waiting_for_sync_point_; - base::TimeTicks process_delayed_work_time_; uint32_t previous_processed_num_; base::TimeTicks last_idle_time_;
diff --git a/gpu/ipc/service/gles2_command_buffer_stub.cc b/gpu/ipc/service/gles2_command_buffer_stub.cc index 6602a32..791436b 100644 --- a/gpu/ipc/service/gles2_command_buffer_stub.cc +++ b/gpu/ipc/service/gles2_command_buffer_stub.cc
@@ -441,6 +441,8 @@ void GLES2CommandBufferStub::OnReturnFrontBuffer(const Mailbox& mailbox, bool is_lost) { + // No need to pull texture updates. + DCHECK(!context_group_->mailbox_manager()->UsesSync()); gles2_decoder_->ReturnFrontBuffer(mailbox, is_lost); }
diff --git a/gpu/ipc/service/gpu_channel.cc b/gpu/ipc/service/gpu_channel.cc index a7ff763..2c5ff18 100644 --- a/gpu/ipc/service/gpu_channel.cc +++ b/gpu/ipc/service/gpu_channel.cc
@@ -81,6 +81,7 @@ GpuChannelMessageFilter( GpuChannel* gpu_channel, Scheduler* scheduler, + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker, scoped_refptr<base::SingleThreadTaskRunner> main_task_runner); // Methods called on main thread. @@ -105,6 +106,10 @@ private: ~GpuChannelMessageFilter() override; + SequenceId GetSequenceId(int32_t route_id) const; + + bool HandleFlushMessage(const IPC::Message& message); + bool MessageErrorHandler(const IPC::Message& message, const char* error_msg); IPC::Channel* ipc_channel_ = nullptr; @@ -128,12 +133,14 @@ GpuChannelMessageFilter::GpuChannelMessageFilter( GpuChannel* gpu_channel, Scheduler* scheduler, + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker, scoped_refptr<base::SingleThreadTaskRunner> main_task_runner) : gpu_channel_(gpu_channel), scheduler_(scheduler), main_task_runner_(std::move(main_task_runner)), image_decode_accelerator_stub_( base::MakeRefCounted<ImageDecodeAcceleratorStub>( + image_decode_accelerator_worker, gpu_channel, static_cast<int32_t>( GpuChannelReservedRoutes::kImageDecodeAccelerator))) { @@ -226,6 +233,17 @@ if (message.should_unblock() || message.is_reply()) return MessageErrorHandler(message, "Unexpected message type"); + switch (message.type()) { + case GpuCommandBufferMsg_AsyncFlush::ID: + case GpuCommandBufferMsg_DestroyTransferBuffer::ID: + case GpuCommandBufferMsg_ReturnFrontBuffer::ID: + case GpuChannelMsg_CreateSharedImage::ID: + case GpuChannelMsg_DestroySharedImage::ID: + return MessageErrorHandler(message, "Invalid message"); + default: + break; + } + if (message.type() == GpuChannelMsg_Nop::ID) { IPC::Message* reply = IPC::SyncMessage::GenerateReply(&message); ipc_channel_->Send(reply); @@ -241,68 +259,77 @@ if (!gpu_channel_) return MessageErrorHandler(message, "Channel destroyed"); - switch (message.type()) { - case GpuCommandBufferMsg_AsyncFlush::ID: - case GpuCommandBufferMsg_DestroyTransferBuffer::ID: - case GpuChannelMsg_CreateSharedImage::ID: - case GpuChannelMsg_DestroySharedImage::ID: - return MessageErrorHandler(message, "Invalid message"); - default: - break; - } + // Handle flush first so that it doesn't get handled out of order. + if (message.type() == GpuChannelMsg_FlushDeferredMessages::ID) + return HandleFlushMessage(message); - if (message.type() == GpuChannelMsg_FlushDeferredMessages::ID) { - GpuChannelMsg_FlushDeferredMessages::Param params; - - if (!GpuChannelMsg_FlushDeferredMessages::Read(&message, ¶ms)) - return MessageErrorHandler(message, "Invalid flush message"); - - std::vector<GpuDeferredMessage> deferred_messages = - std::get<0>(std::move(params)); - std::vector<Scheduler::Task> tasks; - tasks.reserve(deferred_messages.size()); - - for (auto& deferred_message : deferred_messages) { - auto it = route_sequences_.find(deferred_message.message.routing_id()); - if (it == route_sequences_.end()) { - DLOG(ERROR) << "Invalid route id in flush list"; - continue; - } - - tasks.emplace_back( - it->second /* sequence_id */, - base::BindOnce(&GpuChannel::HandleMessage, gpu_channel_->AsWeakPtr(), - std::move(deferred_message.message)), - std::move(deferred_message.sync_token_fences)); - } - - scheduler_->ScheduleTasks(std::move(tasks)); - } else if (message.routing_id() == - static_cast<int32_t>( - GpuChannelReservedRoutes::kImageDecodeAccelerator)) { + if (message.routing_id() == + static_cast<int32_t>(GpuChannelReservedRoutes::kImageDecodeAccelerator)) { if (!image_decode_accelerator_stub_->OnMessageReceived(message)) return MessageErrorHandler(message, "Invalid image decode request"); - } else if (message.routing_id() == MSG_ROUTING_CONTROL || - message.type() == GpuCommandBufferMsg_WaitForTokenInRange::ID || - message.type() == - GpuCommandBufferMsg_WaitForGetOffsetInRange::ID) { - // It's OK to post task that may never run even for sync messages, because - // if the channel is destroyed, the client Send will fail. - main_task_runner_->PostTask(FROM_HERE, - base::Bind(&GpuChannel::HandleOutOfOrderMessage, - gpu_channel_->AsWeakPtr(), message)); - } else { - auto it = route_sequences_.find(message.routing_id()); - if (it == route_sequences_.end()) - return MessageErrorHandler(message, "Invalid route id"); - - scheduler_->ScheduleTask( - Scheduler::Task(it->second /* sequence_id */, - base::BindOnce(&GpuChannel::HandleMessage, - gpu_channel_->AsWeakPtr(), message), - std::vector<SyncToken>())); } + bool handle_out_of_order = + message.routing_id() == MSG_ROUTING_CONTROL || + message.type() == GpuCommandBufferMsg_WaitForTokenInRange::ID || + message.type() == GpuCommandBufferMsg_WaitForGetOffsetInRange::ID; + + if (handle_out_of_order) { + // It's OK to post task that may never run even for sync messages, because + // if the channel is destroyed, the client Send will fail. + main_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&GpuChannel::HandleOutOfOrderMessage, + gpu_channel_->AsWeakPtr(), message)); + return true; + } + + // Messages which do not have sync token dependencies. + SequenceId sequence_id = GetSequenceId(message.routing_id()); + if (sequence_id.is_null()) + return MessageErrorHandler(message, "Invalid route id"); + + scheduler_->ScheduleTask( + Scheduler::Task(sequence_id, + base::BindOnce(&GpuChannel::HandleMessage, + gpu_channel_->AsWeakPtr(), message), + std::vector<SyncToken>())); + return true; +} + +SequenceId GpuChannelMessageFilter::GetSequenceId(int32_t route_id) const { + gpu_channel_lock_.AssertAcquired(); + auto it = route_sequences_.find(route_id); + if (it == route_sequences_.end()) + return SequenceId(); + return it->second; +} + +bool GpuChannelMessageFilter::HandleFlushMessage(const IPC::Message& message) { + DCHECK_EQ(message.type(), GpuChannelMsg_FlushDeferredMessages::ID); + gpu_channel_lock_.AssertAcquired(); + + GpuChannelMsg_FlushDeferredMessages::Param params; + if (!GpuChannelMsg_FlushDeferredMessages::Read(&message, ¶ms)) + return MessageErrorHandler(message, "Invalid flush message"); + + std::vector<GpuDeferredMessage> deferred_messages = + std::get<0>(std::move(params)); + + std::vector<Scheduler::Task> tasks; + tasks.reserve(deferred_messages.size()); + for (auto& deferred_message : deferred_messages) { + auto it = route_sequences_.find(deferred_message.message.routing_id()); + if (it == route_sequences_.end()) { + DLOG(ERROR) << "Invalid route id in flush list"; + continue; + } + tasks.emplace_back( + it->second /* sequence_id */, + base::BindOnce(&GpuChannel::HandleMessage, gpu_channel_->AsWeakPtr(), + std::move(deferred_message.message)), + std::move(deferred_message.sync_token_fences)); + } + scheduler_->ScheduleTasks(std::move(tasks)); return true; } @@ -326,7 +353,8 @@ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, int32_t client_id, uint64_t client_tracing_id, - bool is_gpu_host) + bool is_gpu_host, + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker) : gpu_channel_manager_(gpu_channel_manager), scheduler_(scheduler), sync_point_manager_(sync_point_manager), @@ -340,7 +368,8 @@ weak_factory_(this) { DCHECK(gpu_channel_manager_); DCHECK(client_id_); - filter_ = new GpuChannelMessageFilter(this, scheduler, task_runner); + filter_ = new GpuChannelMessageFilter( + this, scheduler, image_decode_accelerator_worker, task_runner); // SharedImageInterfaceProxy/Stub is a singleton per channel, using a reserved // route. const int32_t shared_image_route_id = @@ -499,8 +528,7 @@ // If we get descheduled or yield while processing a message. if (stub && (stub->HasUnprocessedCommands() || !stub->IsScheduled())) { - DCHECK((uint32_t)GpuCommandBufferMsg_AsyncFlush::ID == msg.type() || - (uint32_t)GpuCommandBufferMsg_WaitSyncToken::ID == msg.type()); + DCHECK_EQ(GpuCommandBufferMsg_AsyncFlush::ID, msg.type()); scheduler_->ContinueTask( stub->sequence_id(), base::BindOnce(&GpuChannel::HandleMessage, AsWeakPtr(), msg));
diff --git a/gpu/ipc/service/gpu_channel.h b/gpu/ipc/service/gpu_channel.h index 849ea0e..2937600 100644 --- a/gpu/ipc/service/gpu_channel.h +++ b/gpu/ipc/service/gpu_channel.h
@@ -44,6 +44,7 @@ class GpuChannelManager; class GpuChannelMessageFilter; +class ImageDecodeAcceleratorWorker; class Scheduler; class SharedImageStub; class SyncPointManager; @@ -62,7 +63,8 @@ scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, int32_t client_id, uint64_t client_tracing_id, - bool is_gpu_host); + bool is_gpu_host, + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker); ~GpuChannel() override; // Init() sets up the underlying IPC channel. Use a separate method because
diff --git a/gpu/ipc/service/gpu_channel_manager.cc b/gpu/ipc/service/gpu_channel_manager.cc index 9e8ea36..5e0543e 100644 --- a/gpu/ipc/service/gpu_channel_manager.cc +++ b/gpu/ipc/service/gpu_channel_manager.cc
@@ -64,6 +64,7 @@ const GpuFeatureInfo& gpu_feature_info, GpuProcessActivityFlags activity_flags, scoped_refptr<gl::GLSurface> default_offscreen_surface, + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker, viz::VulkanContextProvider* vulkan_context_provider) : task_runner_(task_runner), io_task_runner_(io_task_runner), @@ -80,6 +81,7 @@ default_offscreen_surface_(std::move(default_offscreen_surface)), gpu_memory_buffer_factory_(gpu_memory_buffer_factory), gpu_feature_info_(gpu_feature_info), + image_decode_accelerator_worker_(image_decode_accelerator_worker), exiting_for_lost_context_(false), activity_flags_(std::move(activity_flags)), memory_pressure_listener_( @@ -157,7 +159,8 @@ std::unique_ptr<GpuChannel> gpu_channel = std::make_unique<GpuChannel>( this, scheduler_, sync_point_manager_, share_group_, task_runner_, - io_task_runner_, client_id, client_tracing_id, is_gpu_host); + io_task_runner_, client_id, client_tracing_id, is_gpu_host, + image_decode_accelerator_worker_); GpuChannel* gpu_channel_ptr = gpu_channel.get(); gpu_channels_[client_id] = std::move(gpu_channel); @@ -488,4 +491,10 @@ delegate_->StoreShaderToDisk(kGrShaderCacheClientId, key, shader); } +void GpuChannelManager::SetImageDecodeAcceleratorWorkerForTesting( + ImageDecodeAcceleratorWorker* worker) { + DCHECK(gpu_channels_.empty()); + image_decode_accelerator_worker_ = worker; +} + } // namespace gpu
diff --git a/gpu/ipc/service/gpu_channel_manager.h b/gpu/ipc/service/gpu_channel_manager.h index 44fccc79..5296f4a 100644 --- a/gpu/ipc/service/gpu_channel_manager.h +++ b/gpu/ipc/service/gpu_channel_manager.h
@@ -50,6 +50,7 @@ class GpuChannelManagerDelegate; class GpuMemoryBufferFactory; class GpuWatchdogThread; +class ImageDecodeAcceleratorWorker; class MailboxManager; class Scheduler; class SyncPointManager; @@ -78,6 +79,7 @@ const GpuFeatureInfo& gpu_feature_info, GpuProcessActivityFlags activity_flags, scoped_refptr<gl::GLSurface> default_offscreen_surface, + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker, viz::VulkanContextProvider* vulkan_context_provider = nullptr); ~GpuChannelManager() override; @@ -166,6 +168,9 @@ // raster::GrShaderCache::Client implementation. void StoreShader(const std::string& key, const std::string& shader) override; + void SetImageDecodeAcceleratorWorkerForTesting( + ImageDecodeAcceleratorWorker* worker); + private: void InternalDestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id, int client_id); void InternalDestroyGpuMemoryBufferOnIO(gfx::GpuMemoryBufferId id, @@ -219,6 +224,8 @@ base::TimeTicks begin_wake_up_time_; #endif + ImageDecodeAcceleratorWorker* image_decode_accelerator_worker_ = nullptr; + // Set during intentional GPU process shutdown. bool exiting_for_lost_context_;
diff --git a/gpu/ipc/service/gpu_channel_test_common.cc b/gpu/ipc/service/gpu_channel_test_common.cc index 787b918..579bfb8 100644 --- a/gpu/ipc/service/gpu_channel_test_common.cc +++ b/gpu/ipc/service/gpu_channel_test_common.cc
@@ -60,7 +60,8 @@ task_runner_.get(), io_task_runner_.get(), scheduler_.get(), sync_point_manager_.get(), nullptr, /* gpu_memory_buffer_factory */ GpuFeatureInfo(), GpuProcessActivityFlags(), - gl::init::CreateOffscreenGLSurface(gfx::Size()))); + gl::init::CreateOffscreenGLSurface(gfx::Size()), + nullptr /* image_decode_accelerator_worker */)); } GpuChannelTestCommon::~GpuChannelTestCommon() {
diff --git a/gpu/ipc/service/gpu_channel_test_common.h b/gpu/ipc/service/gpu_channel_test_common.h index cd3aae11..b292bb9d 100644 --- a/gpu/ipc/service/gpu_channel_test_common.h +++ b/gpu/ipc/service/gpu_channel_test_common.h
@@ -33,8 +33,11 @@ ~GpuChannelTestCommon() override; protected: - GpuChannelManager* channel_manager() { return channel_manager_.get(); } - base::TestSimpleTaskRunner* task_runner() { return task_runner_.get(); } + GpuChannelManager* channel_manager() const { return channel_manager_.get(); } + base::TestSimpleTaskRunner* task_runner() const { return task_runner_.get(); } + base::TestSimpleTaskRunner* io_task_runner() const { + return io_task_runner_.get(); + } GpuChannel* CreateChannel(int32_t client_id, bool is_gpu_host);
diff --git a/gpu/ipc/service/image_decode_accelerator_stub.cc b/gpu/ipc/service/image_decode_accelerator_stub.cc index c1c0c9a7..241c576 100644 --- a/gpu/ipc/service/image_decode_accelerator_stub.cc +++ b/gpu/ipc/service/image_decode_accelerator_stub.cc
@@ -4,25 +4,32 @@ #include "gpu/ipc/service/image_decode_accelerator_stub.h" +#include "base/bind.h" #include "base/feature_list.h" +#include "base/location.h" #include "base/logging.h" +#include "base/numerics/checked_math.h" #include "base/single_thread_task_runner.h" #include "gpu/command_buffer/common/constants.h" #include "gpu/command_buffer/common/scheduling_priority.h" +#include "gpu/command_buffer/common/sync_token.h" #include "gpu/command_buffer/service/scheduler.h" #include "gpu/command_buffer/service/sync_point_manager.h" #include "gpu/config/gpu_finch_features.h" #include "gpu/ipc/common/command_buffer_id.h" -#include "gpu/ipc/common/gpu_messages.h" #include "gpu/ipc/service/gpu_channel.h" +#include "gpu/ipc/service/image_decode_accelerator_worker.h" #include "ipc/ipc_message.h" #include "ipc/ipc_message_macros.h" namespace gpu { -ImageDecodeAcceleratorStub::ImageDecodeAcceleratorStub(GpuChannel* channel, - int32_t route_id) - : channel_(channel), +ImageDecodeAcceleratorStub::ImageDecodeAcceleratorStub( + ImageDecodeAcceleratorWorker* worker, + GpuChannel* channel, + int32_t route_id) + : worker_(worker), + channel_(channel), sequence_(channel->scheduler()->CreateSequence(SchedulingPriority::kLow)), sync_point_client_state_( channel->sync_point_manager()->CreateSyncPointClientState( @@ -31,7 +38,12 @@ route_id), sequence_)), main_task_runner_(channel->task_runner()), - io_task_runner_(channel->io_task_runner()) {} + io_task_runner_(channel->io_task_runner()) { + // We need the sequence to be initially disabled so that when we schedule a + // task to release the decode sync token, it doesn't run immediately (we want + // it to run when the decode is done). + channel_->scheduler()->DisableSequence(sequence_); +} bool ImageDecodeAcceleratorStub::OnMessageReceived(const IPC::Message& msg) { DCHECK(io_task_runner_->BelongsToCurrentThread()); @@ -70,8 +82,96 @@ // The channel is no longer available, so don't schedule a decode. return; } - // TODO(andrescj): schedule the release of the decode sync token and start the - // decode. + + // TODO(andrescj): validate all the |decode_params|. + + // Make sure the output data size won't overflow. + base::CheckedNumeric<size_t> rgba_bytes = 4u; + rgba_bytes *= decode_params.output_size.width(); + rgba_bytes *= decode_params.output_size.height(); + if (!rgba_bytes.IsValid()) { + OnError(); + return; + } + + // Start the actual decode. + worker_->Decode(std::move(decode_params.encoded_data), + decode_params.output_size, + base::BindOnce(&ImageDecodeAcceleratorStub::OnDecodeCompleted, + base::WrapRefCounted(this))); + + // Schedule a task to eventually release the decode sync token. Note that this + // task won't run until the sequence is re-enabled when a decode completes. + channel_->scheduler()->ScheduleTask(Scheduler::Task( + sequence_, + base::BindOnce(&ImageDecodeAcceleratorStub::ProcessCompletedDecode, + base::WrapRefCounted(this), std::move(decode_params), + release_count), + std::vector<SyncToken>())); +} + +void ImageDecodeAcceleratorStub::ProcessCompletedDecode( + GpuChannelMsg_ScheduleImageDecode_Params params, + uint64_t decode_release_count) { + DCHECK(main_task_runner_->BelongsToCurrentThread()); + base::AutoLock lock(lock_); + if (!channel_) { + // The channel is no longer available, so don't do anything. + return; + } + + // TODO(andrescj): create the transfer cache entry. Doing so will also upload + // the decoded image to a GPU texture. + + sync_point_client_state_->ReleaseFenceSync(decode_release_count); + + // If there are no more completed decodes to be processed, we can disable the + // sequence: when the next decode is completed, the sequence will be + // re-enabled. + pending_completed_decodes_.pop(); + if (pending_completed_decodes_.empty()) + channel_->scheduler()->DisableSequence(sequence_); +} + +void ImageDecodeAcceleratorStub::OnDecodeCompleted( + std::vector<uint8_t> rgba_output) { + base::AutoLock lock(lock_); + if (!channel_) { + // The channel is no longer available, so don't do anything. + return; + } + + if (!accepting_completed_decodes_) { + // We're still waiting for the channel to be destroyed because of an earlier + // failure, so don't do anything. + return; + } + + if (rgba_output.empty()) { + OnError(); + return; + } + + pending_completed_decodes_.push(std::move(rgba_output)); + + // We only need to enable the sequence when the number of pending completed + // decodes is 1. If there are more, the sequence should already be enabled. + if (pending_completed_decodes_.size() == 1u) + channel_->scheduler()->EnableSequence(sequence_); +} + +void ImageDecodeAcceleratorStub::OnError() { + DCHECK(channel_); + + // Trigger the destruction of the channel and stop processing further + // completed decodes, even if they're successful. We can't call + // GpuChannel::OnChannelError() directly because that will end up calling + // ImageDecodeAcceleratorStub::Shutdown() while |lock_| is still acquired. So, + // we post a task to the main thread instead. + accepting_completed_decodes_ = false; + channel_->task_runner()->PostTask( + FROM_HERE, + base::BindOnce(&GpuChannel::OnChannelError, channel_->AsWeakPtr())); } } // namespace gpu
diff --git a/gpu/ipc/service/image_decode_accelerator_stub.h b/gpu/ipc/service/image_decode_accelerator_stub.h index ba767275..0aa5e8a3 100644 --- a/gpu/ipc/service/image_decode_accelerator_stub.h +++ b/gpu/ipc/service/image_decode_accelerator_stub.h
@@ -5,14 +5,16 @@ #ifndef GPU_IPC_SERVICE_IMAGE_DECODE_ACCELERATOR_STUB_H_ #define GPU_IPC_SERVICE_IMAGE_DECODE_ACCELERATOR_STUB_H_ +#include <vector> + +#include "base/containers/queue.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/synchronization/lock.h" #include "base/thread_annotations.h" #include "gpu/command_buffer/service/sequence_id.h" - -struct GpuChannelMsg_ScheduleImageDecode_Params; +#include "gpu/ipc/common/gpu_messages.h" namespace base { class SingleThreadTaskRunner; @@ -24,6 +26,7 @@ namespace gpu { class GpuChannel; +class ImageDecodeAcceleratorWorker; class SyncPointClientState; // Processes incoming image decode requests from renderers: it schedules the @@ -43,7 +46,12 @@ class ImageDecodeAcceleratorStub : public base::RefCountedThreadSafe<ImageDecodeAcceleratorStub> { public: - ImageDecodeAcceleratorStub(GpuChannel* channel, int32_t route_id); + // TODO(andrescj): right now, we only accept one worker to be used for JPEG + // decoding. If we want to use multiple workers, we need to ensure that sync + // tokens are released in order. + ImageDecodeAcceleratorStub(ImageDecodeAcceleratorWorker* worker, + GpuChannel* channel, + int32_t route_id); // Processes a message from the renderer. Should be called on the IO thread. bool OnMessageReceived(const IPC::Message& msg); @@ -60,11 +68,33 @@ const GpuChannelMsg_ScheduleImageDecode_Params& params, uint64_t release_count); + // Creates the service-side cache entry for a completed decode and releases + // the decode sync token. + void ProcessCompletedDecode(GpuChannelMsg_ScheduleImageDecode_Params params, + uint64_t decode_release_count); + + // The |worker_| calls this when a decode is completed. If the decode is + // successful (i.e., |rgba_output| is not empty), |sequence_| will be enabled + // so that ProcessCompletedDecode() is called. If the decode is not + // successful, we destroy the channel (see OnError()). + void OnDecodeCompleted(std::vector<uint8_t> rgba_output); + + // Triggers the destruction of the channel asynchronously and makes it so that + // we stop accepting completed decodes. On entry, |channel_| must not be + // nullptr. + void OnError() EXCLUSIVE_LOCKS_REQUIRED(lock_); + + // The object to which the actual decoding can be delegated. + ImageDecodeAcceleratorWorker* worker_ = nullptr; + base::Lock lock_; - GpuChannel* channel_ GUARDED_BY(lock_); + GpuChannel* channel_ GUARDED_BY(lock_) = nullptr; SequenceId sequence_ GUARDED_BY(lock_); scoped_refptr<SyncPointClientState> sync_point_client_state_ GUARDED_BY(lock_); + base::queue<std::vector<uint8_t>> pending_completed_decodes_ + GUARDED_BY(lock_); + bool accepting_completed_decodes_ GUARDED_BY(lock_) = true; scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
diff --git a/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc b/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc new file mode 100644 index 0000000..62e661c --- /dev/null +++ b/gpu/ipc/service/image_decode_accelerator_stub_unittest.cc
@@ -0,0 +1,281 @@ +// 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 <memory> + +#include "base/containers/queue.h" +#include "base/macros.h" +#include "base/numerics/checked_math.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_simple_task_runner.h" +#include "gpu/command_buffer/common/constants.h" +#include "gpu/command_buffer/common/sync_token.h" +#include "gpu/command_buffer/service/sync_point_manager.h" +#include "gpu/config/gpu_finch_features.h" +#include "gpu/ipc/common/command_buffer_id.h" +#include "gpu/ipc/common/gpu_messages.h" +#include "gpu/ipc/service/gpu_channel_manager.h" +#include "gpu/ipc/service/gpu_channel_test_common.h" +#include "gpu/ipc/service/image_decode_accelerator_worker.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "ui/gfx/color_space.h" +#include "ui/gfx/geometry/size.h" + +namespace gpu { +class GpuChannel; + +// This mock allows individual tests to decide asynchronously when to finish a +// decode by using the FinishOneDecode() method. +class MockImageDecodeAcceleratorWorker : public ImageDecodeAcceleratorWorker { + public: + MockImageDecodeAcceleratorWorker() {} + + void Decode(std::vector<uint8_t> encoded_data, + const gfx::Size& output_size, + base::OnceCallback<void(std::vector<uint8_t>)> decode_cb) { + pending_decodes_.push(PendingDecode{output_size, std::move(decode_cb)}); + DoDecode(output_size); + } + + void FinishOneDecode(bool success) { + if (pending_decodes_.empty()) + return; + PendingDecode next_decode = std::move(pending_decodes_.front()); + pending_decodes_.pop(); + if (success) { + base::CheckedNumeric<size_t> rgba_bytes = 4u; + rgba_bytes *= next_decode.output_size.width(); + rgba_bytes *= next_decode.output_size.height(); + std::vector<uint8_t> rgba_output(rgba_bytes.ValueOrDie(), 0u); + std::move(next_decode.decode_cb).Run(std::move(rgba_output)); + } else { + std::move(next_decode.decode_cb).Run(std::vector<uint8_t>()); + } + } + + MOCK_METHOD1(DoDecode, void(const gfx::Size&)); + + private: + struct PendingDecode { + gfx::Size output_size; + base::OnceCallback<void(std::vector<uint8_t>)> decode_cb; + }; + + base::queue<PendingDecode> pending_decodes_; + + DISALLOW_COPY_AND_ASSIGN(MockImageDecodeAcceleratorWorker); +}; + +const int kChannelId = 1; + +// Test fixture: the general strategy for testing is to have a GPU channel test +// infrastructure (provided by GpuChannelTestCommon), ask the channel to handle +// decode requests, and expect sync token releases and invokations to the +// ImageDecodeAcceleratorWorker functionality. +class ImageDecodeAcceleratorStubTest : public GpuChannelTestCommon { + public: + ImageDecodeAcceleratorStubTest() : GpuChannelTestCommon() {} + ~ImageDecodeAcceleratorStubTest() override = default; + + MockImageDecodeAcceleratorWorker* image_decode_accelerator_worker() const { + return image_decode_accelerator_worker_.get(); + } + + SyncPointManager* sync_point_manager() const { + return channel_manager()->sync_point_manager(); + } + + void SetUp() override { + GpuChannelTestCommon::SetUp(); + // TODO(andrescj): get rid of the |feature_list_| when the feature is + // enabled by default. + feature_list_.InitAndEnableFeature( + features::kVaapiJpegImageDecodeAcceleration); + image_decode_accelerator_worker_ = + std::make_unique<MockImageDecodeAcceleratorWorker>(); + channel_manager()->SetImageDecodeAcceleratorWorkerForTesting( + image_decode_accelerator_worker_.get()); + ASSERT_TRUE(CreateChannel(kChannelId, false /* is_gpu_host */)); + } + + void TearDown() override { + // Make sure the channel is destroyed before the + // |image_decode_accelerator_worker_| is destroyed. + channel_manager()->DestroyAllChannels(); + } + + SyncToken SendDecodeRequest(const gfx::Size& output_size) { + GpuChannel* channel = channel_manager()->LookupChannel(kChannelId); + if (!channel) { + // It's possible that the channel was destroyed as part of an earlier + // SendDecodeRequest() call. This would happen if + // ImageDecodeAcceleratorStub::OnScheduleImageDecode decides to destroy + // the channel. + return SyncToken(); + } + + SyncToken decode_sync_token( + CommandBufferNamespace::GPU_IO, + CommandBufferIdFromChannelAndRoute( + kChannelId, static_cast<int32_t>( + GpuChannelReservedRoutes::kImageDecodeAccelerator)), + release_count_++); + GpuChannelMsg_ScheduleImageDecode_Params decode_params; + decode_params.encoded_data = std::vector<uint8_t>(); + decode_params.output_size = output_size; + decode_params.raster_decoder_route_id = 1; + decode_params.transfer_cache_entry_id = 1u; + decode_params.discardable_handle_shm_id = 0; + decode_params.discardable_handle_shm_offset = 0u; + decode_params.target_color_space = gfx::ColorSpace(); + decode_params.needs_mips = false; + + HandleMessage( + channel, + new GpuChannelMsg_ScheduleImageDecode( + static_cast<int32_t>( + GpuChannelReservedRoutes::kImageDecodeAccelerator), + std::move(decode_params), decode_sync_token.release_count())); + return decode_sync_token; + } + + void RunTasksUntilIdle() { + while (task_runner()->HasPendingTask() || + io_task_runner()->HasPendingTask()) { + task_runner()->RunUntilIdle(); + io_task_runner()->RunUntilIdle(); + } + } + + private: + base::test::ScopedFeatureList feature_list_; + std::unique_ptr<MockImageDecodeAcceleratorWorker> + image_decode_accelerator_worker_; + uint64_t release_count_ = 1; + + DISALLOW_COPY_AND_ASSIGN(ImageDecodeAcceleratorStubTest); +}; + +// Tests the following flow: two decode requests are sent. One of the decodes is +// completed. This should cause one sync token to be released and the scheduler +// sequence to be disabled. Then, the second decode is completed. This should +// cause the other sync token to be released. +TEST_F(ImageDecodeAcceleratorStubTest, + MultipleDecodesCompletedAfterSequenceIsDisabled) { + { + testing::InSequence call_sequence; + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(100, 100))) + .Times(1); + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(200, 200))) + .Times(1); + } + const SyncToken decode1_sync_token = SendDecodeRequest(gfx::Size(100, 100)); + const SyncToken decode2_sync_token = SendDecodeRequest(gfx::Size(200, 200)); + + // A decode sync token should not be released before a decode is finished. + RunTasksUntilIdle(); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + + // Only the first decode sync token should be released after the first decode + // is finished. + image_decode_accelerator_worker()->FinishOneDecode(true); + RunTasksUntilIdle(); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + + // The second decode sync token should be released after the second decode is + // finished. + image_decode_accelerator_worker()->FinishOneDecode(true); + RunTasksUntilIdle(); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + + // The channel should still exist at the end. + EXPECT_TRUE(channel_manager()->LookupChannel(kChannelId)); +} + +// Tests the following flow: three decode requests are sent. The first decode +// completes which should cause the scheduler sequence to be enabled. Right +// after that (while the sequence is still enabled), the other two decodes +// complete. At the end, all the sync tokens should be released. +TEST_F(ImageDecodeAcceleratorStubTest, + MultipleDecodesCompletedWhileSequenceIsEnabled) { + { + testing::InSequence call_sequence; + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(100, 100))) + .Times(1); + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(200, 200))) + .Times(1); + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(300, 300))) + .Times(1); + } + const SyncToken decode1_sync_token = SendDecodeRequest(gfx::Size(100, 100)); + const SyncToken decode2_sync_token = SendDecodeRequest(gfx::Size(200, 200)); + const SyncToken decode3_sync_token = SendDecodeRequest(gfx::Size(300, 300)); + + // A decode sync token should not be released before a decode is finished. + RunTasksUntilIdle(); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode3_sync_token)); + + // All decode sync tokens should be released after completing all the decodes. + image_decode_accelerator_worker()->FinishOneDecode(true); + image_decode_accelerator_worker()->FinishOneDecode(true); + image_decode_accelerator_worker()->FinishOneDecode(true); + RunTasksUntilIdle(); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode3_sync_token)); + + // The channel should still exist at the end. + EXPECT_TRUE(channel_manager()->LookupChannel(kChannelId)); +} + +// Tests the following flow: three decode requests are sent. The first decode +// fails which should trigger the destruction of the channel. The second +// succeeds and the third one fails. Regardless, the channel should still be +// destroyed and all sync tokens should be released. +TEST_F(ImageDecodeAcceleratorStubTest, FailedDecodes) { + { + testing::InSequence call_sequence; + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(100, 100))) + .Times(1); + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(200, 200))) + .Times(1); + EXPECT_CALL(*image_decode_accelerator_worker(), + DoDecode(gfx::Size(300, 300))) + .Times(1); + } + const SyncToken decode1_sync_token = SendDecodeRequest(gfx::Size(100, 100)); + const SyncToken decode2_sync_token = SendDecodeRequest(gfx::Size(200, 200)); + const SyncToken decode3_sync_token = SendDecodeRequest(gfx::Size(300, 300)); + + // A decode sync token should not be released before a decode is finished. + RunTasksUntilIdle(); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + EXPECT_FALSE(sync_point_manager()->IsSyncTokenReleased(decode3_sync_token)); + image_decode_accelerator_worker()->FinishOneDecode(false); + image_decode_accelerator_worker()->FinishOneDecode(true); + image_decode_accelerator_worker()->FinishOneDecode(false); + + // We expect the destruction of the ImageDecodeAcceleratorStub, which also + // implies that all decode sync tokens should be released. + RunTasksUntilIdle(); + EXPECT_FALSE(channel_manager()->LookupChannel(kChannelId)); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode1_sync_token)); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode2_sync_token)); + EXPECT_TRUE(sync_point_manager()->IsSyncTokenReleased(decode3_sync_token)); +} + +} // namespace gpu
diff --git a/gpu/ipc/service/image_decode_accelerator_worker.h b/gpu/ipc/service/image_decode_accelerator_worker.h new file mode 100644 index 0000000..66efb30 --- /dev/null +++ b/gpu/ipc/service/image_decode_accelerator_worker.h
@@ -0,0 +1,38 @@ +// 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 GPU_IPC_SERVICE_IMAGE_DECODE_ACCELERATOR_WORKER_H_ +#define GPU_IPC_SERVICE_IMAGE_DECODE_ACCELERATOR_WORKER_H_ + +#include <vector> + +#include "base/callback.h" + +namespace gfx { +class Size; +} // namespace gfx + +namespace gpu { + +// An ImageDecodeAcceleratorWorker handles the actual hardware-accelerated +// decode of an image of a specific type (e.g., JPEG, WebP, etc.). +class ImageDecodeAcceleratorWorker { + public: + virtual ~ImageDecodeAcceleratorWorker() {} + + // Enqueue a decode of |encoded_data|. The |decode_cb| is called + // asynchronously when the decode completes passing as a parameter a vector + // containing the decoded image in RGBA format (the stride of the output is + // |output_size|.width() * 4). If the decode fails, |decode_cb| is called + // asynchronously with an empty vector. Callbacks should be called in the + // order that this method is called. + virtual void Decode( + std::vector<uint8_t> encoded_data, + const gfx::Size& output_size, + base::OnceCallback<void(std::vector<uint8_t>)> decode_cb) = 0; +}; + +} // namespace gpu + +#endif // GPU_IPC_SERVICE_IMAGE_DECODE_ACCELERATOR_WORKER_H_
diff --git a/gpu/ipc/service/shared_image_stub.cc b/gpu/ipc/service/shared_image_stub.cc index 26aebcd..c2645ce 100644 --- a/gpu/ipc/service/shared_image_stub.cc +++ b/gpu/ipc/service/shared_image_stub.cc
@@ -47,10 +47,14 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP(SharedImageStub, msg) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateSharedImage, OnCreateSharedImage) + IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateSharedImageWithData, + OnCreateSharedImageWithData) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateGMBSharedImage, OnCreateGMBSharedImage) IPC_MESSAGE_HANDLER(GpuChannelMsg_UpdateSharedImage, OnUpdateSharedImage) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroySharedImage, OnDestroySharedImage) + IPC_MESSAGE_HANDLER(GpuChannelMsg_RegisterSharedImageUploadBuffer, + OnRegisterSharedImageUploadBuffer) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; @@ -80,6 +84,57 @@ sync_point_client_state_->ReleaseFenceSync(params.release_id); } +void SharedImageStub::OnCreateSharedImageWithData( + const GpuChannelMsg_CreateSharedImageWithData_Params& params) { + TRACE_EVENT2("gpu", "SharedImageStub::OnCreateSharedImageWithData", "width", + params.size.width(), "height", params.size.height()); + if (!MakeContextCurrentAndCreateFactory()) { + OnError(); + return; + } + + base::CheckedNumeric<size_t> safe_required_span_size = + params.pixel_data_offset; + safe_required_span_size += params.pixel_data_size; + size_t required_span_size; + if (!safe_required_span_size.AssignIfValid(&required_span_size)) { + LOG(ERROR) << "SharedImageStub: upload data size and offset is invalid"; + OnError(); + return; + } + + auto memory = + upload_memory_mapping_.GetMemoryAsSpan<uint8_t>(required_span_size); + if (memory.empty()) { + LOG(ERROR) << "SharedImageStub: upload data does not have expected size"; + OnError(); + return; + } + + auto subspan = + memory.subspan(params.pixel_data_offset, params.pixel_data_size); + + if (!factory_->CreateSharedImage(params.mailbox, params.format, params.size, + params.color_space, params.usage, subspan)) { + LOG(ERROR) << "SharedImageStub: Unable to create shared image"; + OnError(); + return; + } + + // If this is the last upload using a given buffer, release it. + if (params.done_with_shm) { + upload_memory_mapping_ = base::ReadOnlySharedMemoryMapping(); + upload_memory_ = base::ReadOnlySharedMemoryRegion(); + } + + SyncToken sync_token(sync_point_client_state_->namespace_id(), + sync_point_client_state_->command_buffer_id(), + params.release_id); + auto* mailbox_manager = channel_->gpu_channel_manager()->mailbox_manager(); + mailbox_manager->PushTextureUpdates(sync_token); + sync_point_client_state_->ReleaseFenceSync(params.release_id); +} + void SharedImageStub::OnCreateGMBSharedImage( GpuChannelMsg_CreateGMBSharedImage_Params params) { TRACE_EVENT2("gpu", "SharedImageStub::OnCreateSharedImage", "width", @@ -144,6 +199,19 @@ } } +void SharedImageStub::OnRegisterSharedImageUploadBuffer( + base::ReadOnlySharedMemoryRegion shm) { + TRACE_EVENT0("gpu", "SharedImageStub::OnRegisterSharedImageUploadBuffer"); + upload_memory_ = std::move(shm); + upload_memory_mapping_ = upload_memory_.Map(); + if (!upload_memory_mapping_.IsValid()) { + LOG(ERROR) + << "SharedImageStub: Unable to map shared memory for upload data"; + OnError(); + return; + } +} + bool SharedImageStub::MakeContextCurrent() { DCHECK(context_state_); DCHECK(!context_state_->context_lost());
diff --git a/gpu/ipc/service/shared_image_stub.h b/gpu/ipc/service/shared_image_stub.h index 4b93164..fabddec 100644 --- a/gpu/ipc/service/shared_image_stub.h +++ b/gpu/ipc/service/shared_image_stub.h
@@ -47,9 +47,12 @@ private: void OnCreateSharedImage( const GpuChannelMsg_CreateSharedImage_Params& params); + void OnCreateSharedImageWithData( + const GpuChannelMsg_CreateSharedImageWithData_Params& params); void OnCreateGMBSharedImage(GpuChannelMsg_CreateGMBSharedImage_Params params); void OnUpdateSharedImage(const Mailbox& mailbox, uint32_t release_id); void OnDestroySharedImage(const Mailbox& mailbox); + void OnRegisterSharedImageUploadBuffer(base::ReadOnlySharedMemoryRegion shm); bool MakeContextCurrent(); bool MakeContextCurrentAndCreateFactory(); void OnError(); @@ -60,6 +63,9 @@ scoped_refptr<raster::RasterDecoderContextState> context_state_; std::unique_ptr<SharedImageFactory> factory_; uint64_t size_ = 0; + // Holds shared memory used in initial data uploads. + base::ReadOnlySharedMemoryRegion upload_memory_; + base::ReadOnlySharedMemoryMapping upload_memory_mapping_; }; } // namespace gpu
diff --git a/infra/config/global/cr-buildbucket.cfg b/infra/config/global/cr-buildbucket.cfg index 937fcb85..e869522 100644 --- a/infra/config/global/cr-buildbucket.cfg +++ b/infra/config/global/cr-buildbucket.cfg
@@ -2958,6 +2958,11 @@ } builders { mixins: "android-try" + name: "android_blink_rel" + dimensions: "os:Ubuntu-14.04" + } + builders { + mixins: "android-try" mixins: "goma-j300" name: "android_clang_dbg_recipe" dimensions: "os:Ubuntu-14.04"
diff --git a/infra/config/global/luci-milo.cfg b/infra/config/global/luci-milo.cfg index 19a1f77..161553e 100644 --- a/infra/config/global/luci-milo.cfg +++ b/infra/config/global/luci-milo.cfg
@@ -3021,41 +3021,45 @@ builders { name: "buildbot/chromium.goma/Chromium Linux Goma RBE Staging (clobber)" name: "buildbucket/luci.chromium.ci/Chromium Linux Goma RBE Staging (clobber)" - category: "rbe|linux|rel" + category: "rbe|staging|linux|rel" short_name: "clb" } builders { name: "buildbot/chromium.goma/Chromium Linux Goma RBE Staging" name: "buildbucket/luci.chromium.ci/Chromium Linux Goma RBE Staging" - category: "rbe|linux|rel" + category: "rbe|staging|linux|rel" } builders { name: "buildbot/chromium.goma/Chromium Linux Goma RBE Staging (dbg) (clobber)" name: "buildbucket/luci.chromium.ci/Chromium Linux Goma RBE Staging (dbg) (clobber)" - category: "rbe|linux|debug" + category: "rbe|staging|linux|debug" short_name: "clb" } builders { name: "buildbot/chromium.goma/Chromium Linux Goma RBE Staging (dbg)" name: "buildbucket/luci.chromium.ci/Chromium Linux Goma RBE Staging (dbg)" - category: "rbe|linux|debug" + category: "rbe|staging|linux|debug" } builders { name: "buildbucket/luci.chromium.ci/Chromium Mac Goma RBE Staging (clobber)" - category: "rbe|mac|rel" + category: "rbe|staging|mac|rel" short_name: "clb" } builders { name: "buildbucket/luci.chromium.ci/Chromium Mac Goma RBE Staging" - category: "rbe|mac|rel" + category: "rbe|staging|mac|rel" } builders { name: "buildbucket/luci.chromium.ci/Chromium Mac Goma RBE Staging (dbg)" - category: "rbe|mac|debug" + category: "rbe|staging|mac|debug" } builders { name: "buildbucket/luci.chromium.ci/Chromium Android ARM 32-bit Goma RBE Staging" - category: "rbe|android arm|rel" + category: "rbe|staging|android arm|rel" + } + builders { + name: "buildbucket/luci.chromium.ci/Chromium Linux Goma RBE Prod" + category: "rbe|prod|linux|rel" } } @@ -3962,7 +3966,7 @@ name: "buildbucket/luci.chromium.try/android-binary-size" } builders { - name: "buildbot/tryserver.chromium.android/android_blink_rel" + name: "buildbucket/luci.chromium.try/android_blink_rel" } builders { name: "buildbot/tryserver.chromium.android/android_cfi_rel_ng" @@ -4168,6 +4172,9 @@ name: "buildbucket/luci.chromium.try/linux_chromium_ubsan_rel_ng" } builders { + name: "buildbucket/luci.chromium.try/linux-goma-rbe-prod-rel" + } + builders { name: "buildbucket/luci.chromium.try/linux-goma-rbe-staging-rel" } builders {
diff --git a/ios/chrome/browser/BUILD.gn b/ios/chrome/browser/BUILD.gn index 5262925..2d36f2e 100644 --- a/ios/chrome/browser/BUILD.gn +++ b/ios/chrome/browser/BUILD.gn
@@ -126,6 +126,7 @@ "//ios/chrome/browser/drag_and_drop", "//ios/chrome/browser/find_in_page:feature_flags", "//ios/chrome/browser/itunes_urls", + "//ios/chrome/browser/passwords:feature_flags", "//ios/chrome/browser/payments:constants", "//ios/chrome/browser/search_engines:feature_flags", "//ios/chrome/browser/signin:feature_flags",
diff --git a/ios/chrome/browser/experimental_flags.h b/ios/chrome/browser/experimental_flags.h index 822da9e..dbe12be 100644 --- a/ios/chrome/browser/experimental_flags.h +++ b/ios/chrome/browser/experimental_flags.h
@@ -63,6 +63,9 @@ // only once. bool MustClearApplicationGroupSandbox(); +// Whether password generation is enabled. +bool IsAutomaticPasswordGenerationEnabled(); + } // namespace experimental_flags #endif // IOS_CHROME_BROWSER_EXPERIMENTAL_FLAGS_H_
diff --git a/ios/chrome/browser/experimental_flags.mm b/ios/chrome/browser/experimental_flags.mm index 39cb711..880355d6 100644 --- a/ios/chrome/browser/experimental_flags.mm +++ b/ios/chrome/browser/experimental_flags.mm
@@ -24,6 +24,7 @@ #include "components/variations/variations_associated_data.h" #include "ios/chrome/browser/browsing_data/browsing_data_features.h" #include "ios/chrome/browser/chrome_switches.h" +#include "ios/chrome/browser/passwords/password_manager_features.h" #import "ios/chrome/browser/ui/infobars/infobar_feature.h" #include "ios/chrome/browser/ui/ui_feature_flags.h" #include "ios/web/public/web_view_creation_util.h" @@ -130,4 +131,8 @@ return base::FeatureList::IsEnabled(kInfobarUIReboot); } +bool IsAutomaticPasswordGenerationEnabled() { + return base::FeatureList::IsEnabled(features::kPasswordGeneration); +} + } // namespace experimental_flags
diff --git a/ios/chrome/browser/find_in_page/resources/find_in_page.js b/ios/chrome/browser/find_in_page/resources/find_in_page.js index bdd2dc3..048e88b 100644 --- a/ios/chrome/browser/find_in_page/resources/find_in_page.js +++ b/ios/chrome/browser/find_in_page/resources/find_in_page.js
@@ -710,7 +710,7 @@ }; /** - * Finds the position of the result and scrolls to it. + * Finds the position of the result. * @return {string} JSON encoded array of the scroll coordinates "[x, y]". */ function findScrollDimensions_() { @@ -722,9 +722,6 @@ let xPos = normalized[0]; let yPos = normalized[1]; - // Perform the scroll. - // window.scrollTo(xPos, yPos); - match.addSelectHighlight(); let scaled = scaleCoordinates_(normalized); let index = match.visibleIndex; @@ -882,8 +879,6 @@ let originalElement = elem; let nextOffsetParent = originalElement.offsetParent; - let computedStyle = - elem.ownerDocument.defaultView.getComputedStyle(elem, null); // We are currently handling all scrolling through the app, which means we can // only scroll the window, not any scrollable containers in the DOM itself. So @@ -894,6 +889,9 @@ let bodyWidth = getBodyWidth_(); while (elem && elem.nodeName.toUpperCase() != 'BODY') { + let computedStyle = + elem.ownerDocument.defaultView.getComputedStyle(elem, null); + if (elem.style.display === 'none' || elem.style.visibility === 'hidden' || elem.style.opacity === 0 || computedStyle.display === 'none' || computedStyle.visibility === 'hidden' || computedStyle.opacity === 0) { @@ -928,7 +926,6 @@ } elem = elem.parentNode; - computedStyle = elem.ownerDocument.defaultView.getComputedStyle(elem, null); } return true; };
diff --git a/ios/chrome/browser/passwords/BUILD.gn b/ios/chrome/browser/passwords/BUILD.gn index 37387b2..2071304 100644 --- a/ios/chrome/browser/passwords/BUILD.gn +++ b/ios/chrome/browser/passwords/BUILD.gn
@@ -9,8 +9,6 @@ sources = [ "credential_manager.h", "credential_manager.mm", - "credential_manager_features.cc", - "credential_manager_features.h", "credential_manager_util.h", "credential_manager_util.mm", "ios_chrome_password_manager_client.h", @@ -93,12 +91,24 @@ "//url", ] public_deps = [ + ":feature_flags", ":passwords_generation_utils", ] allow_circular_includes_from = [ ":passwords_generation_utils" ] } +source_set("feature_flags") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "password_manager_features.cc", + "password_manager_features.h", + ] + deps = [ + "//base", + ] +} + source_set("passwords_generation_utils") { configs += [ "//build/config/compiler:enable_arc" ] sources = [
diff --git a/ios/chrome/browser/passwords/credential_manager_egtest.mm b/ios/chrome/browser/passwords/credential_manager_egtest.mm index 0ceee0e4..7eda39f3 100644 --- a/ios/chrome/browser/passwords/credential_manager_egtest.mm +++ b/ios/chrome/browser/passwords/credential_manager_egtest.mm
@@ -15,8 +15,8 @@ #include "base/test/scoped_feature_list.h" #include "components/keyed_service/core/service_access_type.h" #include "components/password_manager/core/common/password_manager_pref_names.h" -#include "ios/chrome/browser/passwords/credential_manager_features.h" #include "ios/chrome/browser/passwords/ios_chrome_password_store_factory.h" +#include "ios/chrome/browser/passwords/password_manager_features.h" #import "ios/chrome/test/app/chrome_test_util.h" #import "ios/chrome/test/app/tab_test_util.h" #import "ios/chrome/test/earl_grey/chrome_earl_grey.h"
diff --git a/ios/chrome/browser/passwords/credential_manager_features.cc b/ios/chrome/browser/passwords/credential_manager_features.cc deleted file mode 100644 index a5f6784..0000000 --- a/ios/chrome/browser/passwords/credential_manager_features.cc +++ /dev/null
@@ -1,12 +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 "ios/chrome/browser/passwords/credential_manager_features.h" - -namespace features { - -const base::Feature kCredentialManager{"CredentialManager", - base::FEATURE_DISABLED_BY_DEFAULT}; - -} // namespace features
diff --git a/ios/chrome/browser/passwords/credential_manager_features.h b/ios/chrome/browser/passwords/credential_manager_features.h deleted file mode 100644 index d640a6df..0000000 --- a/ios/chrome/browser/passwords/credential_manager_features.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_PASSWORDS_CREDENTIAL_MANAGER_FEATURES_H_ -#define IOS_CHROME_BROWSER_PASSWORDS_CREDENTIAL_MANAGER_FEATURES_H_ - -#include "base/feature_list.h" - -namespace features { - -// Used to control the state of the Credential Manager API feature. -extern const base::Feature kCredentialManager; - -} // namespace features - -#endif // IOS_CHROME_BROWSER_PASSWORDS_CREDENTIAL_MANAGER_FEATURES_H_
diff --git a/ios/chrome/browser/passwords/password_controller.mm b/ios/chrome/browser/passwords/password_controller.mm index 45febbae..902e885b 100644 --- a/ios/chrome/browser/passwords/password_controller.mm +++ b/ios/chrome/browser/passwords/password_controller.mm
@@ -42,11 +42,11 @@ #include "ios/chrome/browser/infobars/infobar_manager_impl.h" #import "ios/chrome/browser/metrics/ukm_url_recorder.h" #include "ios/chrome/browser/passwords/credential_manager.h" -#include "ios/chrome/browser/passwords/credential_manager_features.h" #import "ios/chrome/browser/passwords/ios_chrome_save_password_infobar_delegate.h" #import "ios/chrome/browser/passwords/ios_chrome_update_password_infobar_delegate.h" #import "ios/chrome/browser/passwords/notify_auto_signin_view_controller.h" #import "ios/chrome/browser/passwords/password_form_filler.h" +#include "ios/chrome/browser/passwords/password_manager_features.h" #import "ios/chrome/browser/ssl/insecure_input_tab_helper.h" #include "ios/chrome/browser/sync/profile_sync_service_factory.h" #import "ios/chrome/browser/ui/commands/application_commands.h"
diff --git a/ios/chrome/browser/passwords/password_manager_features.cc b/ios/chrome/browser/passwords/password_manager_features.cc new file mode 100644 index 0000000..c24b2487 --- /dev/null +++ b/ios/chrome/browser/passwords/password_manager_features.cc
@@ -0,0 +1,15 @@ +// 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 "ios/chrome/browser/passwords/password_manager_features.h" + +namespace features { + +const base::Feature kCredentialManager{"CredentialManager", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kPasswordGeneration{"PasswordGeneration", + base::FEATURE_DISABLED_BY_DEFAULT}; + +} // namespace features
diff --git a/ios/chrome/browser/passwords/password_manager_features.h b/ios/chrome/browser/passwords/password_manager_features.h new file mode 100644 index 0000000..64cab870 --- /dev/null +++ b/ios/chrome/browser/passwords/password_manager_features.h
@@ -0,0 +1,20 @@ +// 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 IOS_CHROME_BROWSER_PASSWORDS_PASSWORD_MANAGER_FEATURES_H_ +#define IOS_CHROME_BROWSER_PASSWORDS_PASSWORD_MANAGER_FEATURES_H_ + +#include "base/feature_list.h" + +namespace features { + +// Used to control the state of the Credential Manager API feature. +extern const base::Feature kCredentialManager; + +// Used to control the state of the iOS password generation feature. +extern const base::Feature kPasswordGeneration; + +} // namespace features + +#endif // IOS_CHROME_BROWSER_PASSWORDS_PASSWORD_MANAGER_FEATURES_H_
diff --git a/ios/chrome/browser/translate/before_translate_infobar_controller.mm b/ios/chrome/browser/translate/before_translate_infobar_controller.mm index 890ef89..8ace3664 100644 --- a/ios/chrome/browser/translate/before_translate_infobar_controller.mm +++ b/ios/chrome/browser/translate/before_translate_infobar_controller.mm
@@ -169,6 +169,7 @@ [LanguageSelectionContext contextWithLanguageData:self.infoBarDelegate initialIndex:selectedRow unavailableIndex:disabledRow]; + DCHECK(self.languageSelectionHandler); [self.languageSelectionHandler showLanguageSelectorWithContext:context delegate:self]; }
diff --git a/ios/chrome/browser/translate/chrome_ios_translate_client.h b/ios/chrome/browser/translate/chrome_ios_translate_client.h index 15befec2..a6ade45 100644 --- a/ios/chrome/browser/translate/chrome_ios_translate_client.h +++ b/ios/chrome/browser/translate/chrome_ios_translate_client.h
@@ -44,12 +44,8 @@ public: ~ChromeIOSTranslateClient() override; - // Creates a translation client tab helper and attaches it to |web_state|. The - // |language_selection_handler| may not be nil, and is not retained by the - // ChromeIOSTranslateClient. - static void CreateForWebState( - web::WebState* web_state, - id<LanguageSelectionHandler> language_selection_handler); + // Creates a translation client tab helper and attaches it to |web_state| + static void CreateForWebState(web::WebState* web_state); // Helper method to return a new TranslatePrefs instance. static std::unique_ptr<translate::TranslatePrefs> CreateTranslatePrefs( @@ -79,13 +75,16 @@ bool IsTranslatableURL(const GURL& url) override; void ShowReportLanguageDetectionErrorUI(const GURL& report_url) override; + void set_language_selection_handler(id<LanguageSelectionHandler> handler) { + language_selection_handler_ = handler; + } + private: - ChromeIOSTranslateClient( - web::WebState* web_state, - id<LanguageSelectionHandler> language_selection_handler); + ChromeIOSTranslateClient(web::WebState* web_state); friend class web::WebStateUserData<ChromeIOSTranslateClient>; // web::WebStateObserver implementation. + void DidStartLoading(web::WebState* web_state) override; void WebStateDestroyed(web::WebState* web_state) override; // The WebState this instance is observing. Will be null after
diff --git a/ios/chrome/browser/translate/chrome_ios_translate_client.mm b/ios/chrome/browser/translate/chrome_ios_translate_client.mm index cc9b1c1..f9b7dbf 100644 --- a/ios/chrome/browser/translate/chrome_ios_translate_client.mm +++ b/ios/chrome/browser/translate/chrome_ios_translate_client.mm
@@ -48,20 +48,16 @@ #endif // static -void ChromeIOSTranslateClient::CreateForWebState( - web::WebState* web_state, - id<LanguageSelectionHandler> language_selection_handler) { +void ChromeIOSTranslateClient::CreateForWebState(web::WebState* web_state) { DCHECK(web_state); if (!FromWebState(web_state)) { - web_state->SetUserData(UserDataKey(), - base::WrapUnique(new ChromeIOSTranslateClient( - web_state, language_selection_handler))); + web_state->SetUserData( + UserDataKey(), + base::WrapUnique(new ChromeIOSTranslateClient(web_state))); } } -ChromeIOSTranslateClient::ChromeIOSTranslateClient( - web::WebState* web_state, - id<LanguageSelectionHandler> language_selection_handler) +ChromeIOSTranslateClient::ChromeIOSTranslateClient(web::WebState* web_state) : web_state_(web_state), translate_manager_(std::make_unique<translate::TranslateManager>( this, @@ -74,9 +70,7 @@ ->GetPrimaryModel())), translate_driver_(web_state, web_state->GetNavigationManager(), - translate_manager_.get()), - language_selection_handler_(language_selection_handler) { - DCHECK(language_selection_handler); + translate_manager_.get()) { web_state_->AddObserver(this); } @@ -196,6 +190,10 @@ NOTREACHED(); } +void ChromeIOSTranslateClient::DidStartLoading(web::WebState* web_state) { + [language_selection_handler_ dismissLanguageSelector]; +} + void ChromeIOSTranslateClient::WebStateDestroyed(web::WebState* web_state) { DCHECK_EQ(web_state_, web_state); web_state_->RemoveObserver(this);
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 8c6ff5d..f7f55f71 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -2894,9 +2894,7 @@ // init of the translation helpers if needed. // TODO(crbug.com/785238): Remove the need for this check. if (tab.webState->GetJSInjectionReceiver()) { - ChromeIOSTranslateClient::CreateForWebState( - tab.webState, - self.infobarContainerCoordinator.languageSelectionHandler); + ChromeIOSTranslateClient::CreateForWebState(tab.webState); language::IOSLanguageDetectionTabHelper::CreateForWebState( tab.webState, ChromeIOSTranslateClient::FromWebState(tab.webState) @@ -3719,8 +3717,14 @@ return reading_list::IsOfflineURLValid( url, ReadingListModelFactory::GetForBrowserState(_browserState)); } - if (host == kChromeUINewTabHost) + if (host == kChromeUINewTabHost) { return !base::FeatureList::IsEnabled(kBrowserContainerContainsNTP); + } + if (host == kChromeUIExternalFileHost) { + id<CRWNativeContent> controller = + [self controllerForURL:url webState:self.tabModel.currentTab.webState]; + return controller ? YES : NO; + } return NO; }
diff --git a/ios/chrome/browser/ui/infobars/BUILD.gn b/ios/chrome/browser/ui/infobars/BUILD.gn index a95724c..4f1621e 100644 --- a/ios/chrome/browser/ui/infobars/BUILD.gn +++ b/ios/chrome/browser/ui/infobars/BUILD.gn
@@ -14,6 +14,7 @@ ":infobars_ui", ":public", "//base", + "//ios/chrome/browser/download", "//ios/chrome/browser/infobars", "//ios/chrome/browser/tabs", "//ios/chrome/browser/translate",
diff --git a/ios/chrome/browser/ui/infobars/infobar_container_coordinator.h b/ios/chrome/browser/ui/infobars/infobar_container_coordinator.h index a41878d..2aa74333 100644 --- a/ios/chrome/browser/ui/infobars/infobar_container_coordinator.h +++ b/ios/chrome/browser/ui/infobars/infobar_container_coordinator.h
@@ -14,7 +14,6 @@ @class TabModel; @protocol ApplicationCommands; @protocol InfobarPositioner; -@protocol LanguageSelectionHandler; @protocol SyncPresenter; // Coordinator that owns and manages an InfobarContainer. @@ -54,10 +53,6 @@ // The SyncPresenter delegate for this Coordinator. @property(nonatomic, weak) id<SyncPresenter> syncPresenter; -// The delegate that allows user to select a language from a list of languages. -@property(nonatomic, readonly) id<LanguageSelectionHandler> - languageSelectionHandler; - @end #endif // IOS_CHROME_BROWSER_UI_INFOBARS_INFOBAR_CONTAINER_COORDINATOR_H_
diff --git a/ios/chrome/browser/ui/infobars/infobar_container_coordinator.mm b/ios/chrome/browser/ui/infobars/infobar_container_coordinator.mm index ec422b5..cdf0bc4 100644 --- a/ios/chrome/browser/ui/infobars/infobar_container_coordinator.mm +++ b/ios/chrome/browser/ui/infobars/infobar_container_coordinator.mm
@@ -12,7 +12,6 @@ #import "ios/chrome/browser/ui/infobars/infobar_positioner.h" #include "ios/chrome/browser/ui/infobars/legacy_infobar_container_view_controller.h" #import "ios/chrome/browser/ui/signin_interaction/public/signin_presenter.h" -#import "ios/chrome/browser/ui/translate/language_selection_coordinator.h" #include "ios/chrome/browser/upgrade/upgrade_center.h" #if !defined(__has_feature) || !__has_feature(objc_arc) @@ -29,10 +28,6 @@ // The mediator for this Coordinator. @property(nonatomic, strong) InfobarContainerMediator* mediator; -// Coordinator for the language selection UI. -@property(nonatomic, strong) - LanguageSelectionCoordinator* languageSelectionCoordinator; - @end @implementation InfobarContainerCoordinator @@ -65,9 +60,6 @@ didMoveToParentViewController:self.baseViewController]; self.containerViewController.positioner = self.positioner; - self.languageSelectionCoordinator = [[LanguageSelectionCoordinator alloc] - initWithBaseViewController:self.baseViewController]; - // Create the mediator once the VC has been added to the View hierarchy. self.mediator = [[InfobarContainerMediator alloc] initWithConsumer:self.containerViewController @@ -75,7 +67,6 @@ tabModel:self.tabModel]; self.mediator.syncPresenter = self.syncPresenter; self.mediator.signinPresenter = self; - self.mediator.languageSelectionHandler = self.languageSelectionCoordinator; [[UpgradeCenter sharedInstance] registerClient:self.mediator withDispatcher:self.dispatcher]; @@ -105,10 +96,6 @@ return NO; } -- (id<LanguageSelectionHandler>)languageSelectionHandler { - return self.languageSelectionCoordinator; -} - #pragma mark - SigninPresenter - (void)showSignin:(ShowSigninCommand*)command {
diff --git a/ios/chrome/browser/ui/infobars/infobar_container_mediator.h b/ios/chrome/browser/ui/infobars/infobar_container_mediator.h index 3063d94..88ea821e 100644 --- a/ios/chrome/browser/ui/infobars/infobar_container_mediator.h +++ b/ios/chrome/browser/ui/infobars/infobar_container_mediator.h
@@ -14,7 +14,6 @@ } @protocol InfobarContainerConsumer; -@protocol LanguageSelectionHandler; @protocol SigninPresenter; @protocol SyncPresenter; @class TabModel; @@ -35,10 +34,6 @@ // The SigninPresenter delegate for this Mediator. @property(nonatomic, weak) id<SigninPresenter> signinPresenter; -// The delegate that allows user to select a language from a list of languages. -@property(nonatomic, weak) id<LanguageSelectionHandler> - languageSelectionHandler; - @end #endif // IOS_CHROME_BROWSER_UI_INFOBARS_INFOBAR_CONTAINER_MEDIATOR_H_
diff --git a/ios/chrome/browser/ui/infobars/infobar_container_mediator.mm b/ios/chrome/browser/ui/infobars/infobar_container_mediator.mm index 210946e..a884fa5 100644 --- a/ios/chrome/browser/ui/infobars/infobar_container_mediator.mm +++ b/ios/chrome/browser/ui/infobars/infobar_container_mediator.mm
@@ -9,7 +9,6 @@ #import "ios/chrome/browser/tabs/tab.h" #import "ios/chrome/browser/tabs/tab_model.h" #import "ios/chrome/browser/tabs/tab_model_observer.h" -#import "ios/chrome/browser/translate/language_selection_handler.h" #import "ios/chrome/browser/ui/authentication/re_signin_infobar_delegate.h" #import "ios/chrome/browser/ui/infobars/infobar_container_consumer.h" #import "ios/chrome/browser/ui/settings/sync_utils/sync_util.h" @@ -81,21 +80,6 @@ #pragma mark - TabModelObserver -- (void)tabModel:(TabModel*)model - didChangeActiveTab:(Tab*)newTab - previousTab:(Tab*)previousTab - atIndex:(NSUInteger)index { - // Dismiss the language selector, if any; this is a no-op when there's no - // language selector presented. - [self.languageSelectionHandler dismissLanguageSelector]; -} - -- (void)tabModel:(TabModel*)model willStartLoadingTab:(Tab*)tab { - // Dismiss the language selector, if any; this is a no-op when there's no - // language selector presented. - [self.languageSelectionHandler dismissLanguageSelector]; -} - // TODO(crbug.com/892376): Stop observing TabModel and use WebStateList instead. - (void)tabModel:(TabModel*)model newTabWillOpen:(Tab*)tab
diff --git a/ios/chrome/browser/ui/main/BUILD.gn b/ios/chrome/browser/ui/main/BUILD.gn index bfbcde7..e7045992 100644 --- a/ios/chrome/browser/ui/main/BUILD.gn +++ b/ios/chrome/browser/ui/main/BUILD.gn
@@ -43,6 +43,7 @@ "//ios/chrome/browser/ui/reading_list", "//ios/chrome/browser/ui/recent_tabs", "//ios/chrome/browser/ui/snackbar", + "//ios/chrome/browser/ui/translate", "//ios/chrome/browser/web", "//ios/chrome/browser/web:tab_helper_delegates", "//ios/chrome/browser/web_state_list",
diff --git a/ios/chrome/browser/ui/main/browser_coordinator.mm b/ios/chrome/browser/ui/main/browser_coordinator.mm index 14f9e80..95d438b 100644 --- a/ios/chrome/browser/ui/main/browser_coordinator.mm +++ b/ios/chrome/browser/ui/main/browser_coordinator.mm
@@ -32,6 +32,7 @@ #import "ios/chrome/browser/ui/reading_list/reading_list_coordinator.h" #import "ios/chrome/browser/ui/recent_tabs/recent_tabs_coordinator.h" #import "ios/chrome/browser/ui/snackbar/snackbar_coordinator.h" +#import "ios/chrome/browser/ui/translate/language_selection_coordinator.h" #import "ios/chrome/browser/web/repost_form_tab_helper.h" #import "ios/chrome/browser/web/repost_form_tab_helper_delegate.h" #include "ios/chrome/browser/web_state_list/web_state_list.h" @@ -67,6 +68,10 @@ @property(nonatomic, strong) FormInputAccessoryCoordinator* formInputAccessoryCoordinator; +// Coordinator for a language selection UI. +@property(nonatomic, strong) + LanguageSelectionCoordinator* languageSelectionCoordinator; + // Coordinator for Page Info UI. @property(nonatomic, strong) PageInfoLegacyCoordinator* pageInfoCoordinator; @@ -207,6 +212,12 @@ self.formInputAccessoryCoordinator.delegate = self; [self.formInputAccessoryCoordinator start]; + self.languageSelectionCoordinator = [[LanguageSelectionCoordinator alloc] + initWithBaseViewController:self.viewController + browserState:self.browserState + webStateList:self.tabModel.webStateList]; + [self.languageSelectionCoordinator start]; + self.pageInfoCoordinator = [[PageInfoLegacyCoordinator alloc] initWithBaseViewController:self.viewController browserState:self.browserState]; @@ -250,6 +261,9 @@ [self.formInputAccessoryCoordinator stop]; self.formInputAccessoryCoordinator = nil; + [self.languageSelectionCoordinator stop]; + self.languageSelectionCoordinator = nil; + [self.pageInfoCoordinator stop]; self.pageInfoCoordinator = nil;
diff --git a/ios/chrome/browser/ui/settings/cells/settings_switch_item.mm b/ios/chrome/browser/ui/settings/cells/settings_switch_item.mm index 48592c2..0e4a053 100644 --- a/ios/chrome/browser/ui/settings/cells/settings_switch_item.mm +++ b/ios/chrome/browser/ui/settings/cells/settings_switch_item.mm
@@ -109,6 +109,10 @@ _switchView = [[UISwitch alloc] initWithFrame:CGRectZero]; _switchView.translatesAutoresizingMaskIntoConstraints = NO; _switchView.onTintColor = UIColorFromRGB(kTableViewSwitchTintColor); + [_switchView + setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh + 1 + forAxis: + UILayoutConstraintAxisHorizontal]; _switchView.accessibilityHint = l10n_util::GetNSString( IDS_IOS_TOGGLE_SETTING_SWITCH_ACCESSIBILITY_HINT); [self.contentView addSubview:_switchView];
diff --git a/ios/chrome/browser/ui/tab_grid/grid/BUILD.gn b/ios/chrome/browser/ui/tab_grid/grid/BUILD.gn index 666ae29..07c1758 100644 --- a/ios/chrome/browser/ui/tab_grid/grid/BUILD.gn +++ b/ios/chrome/browser/ui/tab_grid/grid/BUILD.gn
@@ -12,6 +12,7 @@ "grid_constants.h", "grid_constants.mm", "grid_consumer.h", + "grid_empty_view.h", "grid_image_data_source.h", "grid_item.h", "grid_item.mm",
diff --git a/ios/chrome/browser/ui/tab_grid/grid/grid_empty_view.h b/ios/chrome/browser/ui/tab_grid/grid/grid_empty_view.h new file mode 100644 index 0000000..ce7e9c9 --- /dev/null +++ b/ios/chrome/browser/ui/tab_grid/grid/grid_empty_view.h
@@ -0,0 +1,16 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_UI_TAB_GRID_GRID_GRID_EMPTY_VIEW_H_ +#define IOS_CHROME_BROWSER_UI_TAB_GRID_GRID_GRID_EMPTY_VIEW_H_ + +// Protocol defining the interface of the view displayed when the grid is empty. +@protocol GridEmptyView + +// Insets of the inner ScrollView. +@property(nonatomic, assign) UIEdgeInsets scrollViewContentInsets; + +@end + +#endif // IOS_CHROME_BROWSER_UI_TAB_GRID_GRID_GRID_EMPTY_VIEW_H_
diff --git a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h index 42665fa5..43d0291 100644 --- a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h +++ b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.h
@@ -10,6 +10,7 @@ #import "ios/chrome/browser/ui/tab_grid/grid/grid_consumer.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_theme.h" +@protocol GridEmptyView; @protocol GridImageDataSource; @class GridTransitionLayout; @class GridViewController; @@ -40,7 +41,7 @@ // The gridView is accessible to manage the content inset behavior. @property(nonatomic, readonly) UIScrollView* gridView; // The view that is shown when there are no items. -@property(nonatomic, strong) UIView* emptyStateView; +@property(nonatomic, strong) UIView<GridEmptyView>* emptyStateView; // Returns YES if the grid has no items. @property(nonatomic, readonly, getter=isGridEmpty) BOOL gridEmpty; // The visual look of the grid.
diff --git a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.mm b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.mm index 5369c7be..44893f6 100644 --- a/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.mm +++ b/ios/chrome/browser/ui/tab_grid/grid/grid_view_controller.mm
@@ -13,6 +13,7 @@ #include "ios/chrome/browser/procedural_block_types.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_cell.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_constants.h" +#import "ios/chrome/browser/ui/tab_grid/grid/grid_empty_view.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_image_data_source.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_item.h" #import "ios/chrome/browser/ui/tab_grid/grid/grid_layout.h" @@ -170,23 +171,27 @@ return self.collectionView; } -- (void)setEmptyStateView:(UIView*)emptyStateView { +- (void)setEmptyStateView:(UIView<GridEmptyView>*)emptyStateView { if (_emptyStateView) [_emptyStateView removeFromSuperview]; _emptyStateView = emptyStateView; + emptyStateView.scrollViewContentInsets = + self.collectionView.adjustedContentInset; emptyStateView.translatesAutoresizingMaskIntoConstraints = NO; [self.collectionView.backgroundView addSubview:emptyStateView]; id<LayoutGuideProvider> safeAreaGuide = self.collectionView.backgroundView.safeAreaLayoutGuide; [NSLayoutConstraint activateConstraints:@[ - [self.collectionView.backgroundView.centerXAnchor - constraintEqualToAnchor:emptyStateView.centerXAnchor], [self.collectionView.backgroundView.centerYAnchor constraintEqualToAnchor:emptyStateView.centerYAnchor], [safeAreaGuide.leadingAnchor - constraintLessThanOrEqualToAnchor:emptyStateView.leadingAnchor], + constraintEqualToAnchor:emptyStateView.leadingAnchor], [safeAreaGuide.trailingAnchor - constraintGreaterThanOrEqualToAnchor:emptyStateView.trailingAnchor], + constraintEqualToAnchor:emptyStateView.trailingAnchor], + [emptyStateView.topAnchor + constraintGreaterThanOrEqualToAnchor:safeAreaGuide.topAnchor], + [emptyStateView.bottomAnchor + constraintLessThanOrEqualToAnchor:safeAreaGuide.bottomAnchor], ]]; } @@ -313,6 +318,12 @@ return NO; } +#pragma mark - UIScrollViewDelegate + +- (void)scrollViewDidChangeAdjustedContentInset:(UIScrollView*)scrollView { + self.emptyStateView.scrollViewContentInsets = scrollView.contentInset; +} + #pragma mark - GridCellDelegate - (void)closeButtonTappedForCell:(GridCell*)cell {
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.h b/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.h index 79c3467d..48981ee 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.h +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.h
@@ -7,17 +7,20 @@ #import <UIKit/UIKit.h> +#import "ios/chrome/browser/ui/tab_grid/grid/grid_empty_view.h" #import "ios/chrome/browser/ui/tab_grid/tab_grid_paging.h" // A view that informs the user that the grid is empty. The displayed // text is customized for incognito and regular tabs pages. No text is // displayed for the remote tabs page. -@interface TabGridEmptyStateView : UIView +@interface TabGridEmptyStateView : UIView <GridEmptyView> + // Initializes view with |page|, which changes the displayed text. - (instancetype)initWithPage:(TabGridPage)page NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; - (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; - (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE; + @end #endif // IOS_CHROME_BROWSER_UI_TAB_GRID_TAB_GRID_EMPTY_STATE_VIEW_H_
diff --git a/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.mm b/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.mm index 4ebec1c..c753c7ba 100644 --- a/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.mm +++ b/ios/chrome/browser/ui/tab_grid/tab_grid_empty_state_view.mm
@@ -6,6 +6,7 @@ #import "ios/chrome/browser/ui/tab_grid/tab_grid_constants.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" +#import "ios/chrome/common/ui_util/constraints_ui_util.h" #include "ios/chrome/grit/ios_strings.h" #include "ui/base/l10n/l10n_util.h" @@ -13,14 +14,21 @@ #error "This file requires ARC support." #endif +namespace { +const CGFloat kVerticalMargin = 16; +} // namespace + @interface TabGridEmptyStateView () +@property(nonatomic, strong) UIView* container; +@property(nonatomic, strong) UIScrollView* scrollView; +@property(nonatomic, strong) NSLayoutConstraint* scrollViewHeight; @property(nonatomic, copy, readonly) NSString* title; @property(nonatomic, copy, readonly) NSString* body; @end @implementation TabGridEmptyStateView -@synthesize title = _title; -@synthesize body = _body; + +@synthesize scrollViewContentInsets = _scrollViewContentInsets; - (instancetype)initWithPage:(TabGridPage)page { if (self = [super initWithFrame:CGRectZero]) { @@ -45,18 +53,39 @@ return self; } +#pragma mark - Accessor + +- (void)setScrollViewContentInsets:(UIEdgeInsets)scrollViewContentInsets { + _scrollViewContentInsets = scrollViewContentInsets; + self.scrollView.contentInset = scrollViewContentInsets; + self.scrollViewHeight.constant = + scrollViewContentInsets.top + scrollViewContentInsets.bottom; +} + #pragma mark - UIView - (void)willMoveToSuperview:(UIView*)newSuperview { - // The first time this moves to a superview, perform the view setup. - if (newSuperview && self.subviews.count == 0) { - [self setupViews]; + if (newSuperview) { + // The first time this moves to a superview, perform the view setup. + if (self.subviews.count == 0) + [self setupViews]; + [self.container.widthAnchor + constraintEqualToAnchor:self.safeAreaLayoutGuide.widthAnchor] + .active = YES; } } #pragma mark - Private - (void)setupViews { + UIView* container = [[UIView alloc] init]; + container.translatesAutoresizingMaskIntoConstraints = NO; + self.container = container; + + UIScrollView* scrollView = [[UIScrollView alloc] init]; + scrollView.translatesAutoresizingMaskIntoConstraints = NO; + self.scrollView = scrollView; + UILabel* topLabel = [[UILabel alloc] init]; topLabel.translatesAutoresizingMaskIntoConstraints = NO; topLabel.text = self.title; @@ -65,7 +94,7 @@ topLabel.adjustsFontForContentSizeCategory = YES; topLabel.numberOfLines = 0; topLabel.textAlignment = NSTextAlignmentCenter; - [self addSubview:topLabel]; + UILabel* bottomLabel = [[UILabel alloc] init]; bottomLabel.translatesAutoresizingMaskIntoConstraints = NO; bottomLabel.text = self.body; @@ -74,17 +103,44 @@ bottomLabel.adjustsFontForContentSizeCategory = YES; bottomLabel.numberOfLines = 0; bottomLabel.textAlignment = NSTextAlignmentCenter; - [self addSubview:bottomLabel]; + + [container addSubview:topLabel]; + [container addSubview:bottomLabel]; + [scrollView addSubview:container]; + [self addSubview:scrollView]; + + NSLayoutConstraint* scrollViewHeightConstraint = [scrollView.heightAnchor + constraintEqualToAnchor:container.heightAnchor + constant:(self.scrollViewContentInsets.top + + self.scrollViewContentInsets.bottom)]; + scrollViewHeightConstraint.priority = UILayoutPriorityDefaultLow; + scrollViewHeightConstraint.active = YES; + self.scrollViewHeight = scrollViewHeightConstraint; + [NSLayoutConstraint activateConstraints:@[ - [topLabel.topAnchor constraintEqualToAnchor:self.topAnchor], - [topLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor], - [topLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor], + [topLabel.topAnchor constraintEqualToAnchor:container.topAnchor + constant:kVerticalMargin], + [topLabel.leadingAnchor constraintEqualToAnchor:container.leadingAnchor], + [topLabel.trailingAnchor constraintEqualToAnchor:container.trailingAnchor], [topLabel.bottomAnchor constraintEqualToAnchor:bottomLabel.topAnchor constant:-kTabGridEmptyStateVerticalMargin], - [bottomLabel.leadingAnchor constraintEqualToAnchor:self.leadingAnchor], - [bottomLabel.trailingAnchor constraintEqualToAnchor:self.trailingAnchor], - [bottomLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor], + [bottomLabel.leadingAnchor constraintEqualToAnchor:container.leadingAnchor], + [bottomLabel.trailingAnchor + constraintEqualToAnchor:container.trailingAnchor], + [bottomLabel.bottomAnchor constraintEqualToAnchor:container.bottomAnchor + constant:-kVerticalMargin], + + [container.topAnchor constraintEqualToAnchor:scrollView.topAnchor], + [container.bottomAnchor constraintEqualToAnchor:scrollView.bottomAnchor], + [container.centerXAnchor constraintEqualToAnchor:scrollView.centerXAnchor], + + [scrollView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor], + [scrollView.topAnchor constraintGreaterThanOrEqualToAnchor:self.topAnchor], + [scrollView.bottomAnchor + constraintLessThanOrEqualToAnchor:self.bottomAnchor], + [scrollView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor], + [scrollView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor], ]]; }
diff --git a/ios/chrome/browser/ui/translate/BUILD.gn b/ios/chrome/browser/ui/translate/BUILD.gn index 79af1f9..4ad5c214 100644 --- a/ios/chrome/browser/ui/translate/BUILD.gn +++ b/ios/chrome/browser/ui/translate/BUILD.gn
@@ -16,7 +16,10 @@ "//components/translate/core/browser", "//ios/chrome/browser", "//ios/chrome/browser/translate", + "//ios/chrome/browser/ui/coordinators:chrome_coordinators", "//ios/chrome/browser/ui/presenters", + "//ios/chrome/browser/web_state_list", + "//ios/web/public", ] }
diff --git a/ios/chrome/browser/ui/translate/language_selection_coordinator.h b/ios/chrome/browser/ui/translate/language_selection_coordinator.h index 768a6c3..a83c76db8 100644 --- a/ios/chrome/browser/ui/translate/language_selection_coordinator.h +++ b/ios/chrome/browser/ui/translate/language_selection_coordinator.h
@@ -7,22 +7,29 @@ #import <UIKit/UIKit.h> -#import "ios/chrome/browser/translate/language_selection_handler.h" +#import "ios/chrome/browser/ui/coordinators/chrome_coordinator.h" @protocol ContainedPresenter; +class WebStateList; // A coordinator for a language selection UI. This is intended for display as // a contained, not presented, view controller. // The methods defined in the LanguageSelectionHandler protocol will be called // to start the coordinator. -@interface LanguageSelectionCoordinator : NSObject<LanguageSelectionHandler> +@interface LanguageSelectionCoordinator : ChromeCoordinator -// Creates a coordinator that will use |viewController| as the base view -// controller for presenting its UI. +// Creates a coordinator that uses a |viewController| a |browserState| and +// a |webStateList|. - (instancetype)initWithBaseViewController:(UIViewController*)viewController - NS_DESIGNATED_INITIALIZER; + browserState: + (ios::ChromeBrowserState*)browserState + webStateList:(WebStateList*)webStateList; -- (instancetype)init NS_UNAVAILABLE; +// Unavailable, use -initWithBaseViewController:browserState:webStateList:. +- (instancetype)initWithBaseViewController:(UIViewController*)viewController + browserState: + (ios::ChromeBrowserState*)browserState + NS_UNAVAILABLE; @end
diff --git a/ios/chrome/browser/ui/translate/language_selection_coordinator.mm b/ios/chrome/browser/ui/translate/language_selection_coordinator.mm index a6f91c4..64d7e88 100644 --- a/ios/chrome/browser/ui/translate/language_selection_coordinator.mm +++ b/ios/chrome/browser/ui/translate/language_selection_coordinator.mm
@@ -6,8 +6,8 @@ #import "base/logging.h" #import "ios/chrome/browser/translate/language_selection_delegate.h" +#import "ios/chrome/browser/translate/language_selection_handler.h" #import "ios/chrome/browser/ui/presenters/contained_presenter.h" -#import "ios/chrome/browser/ui/presenters/contained_presenter_delegate.h" #import "ios/chrome/browser/ui/presenters/vertical_animation_container.h" #import "ios/chrome/browser/ui/translate/language_selection_mediator.h" #import "ios/chrome/browser/ui/translate/language_selection_view_controller.h" @@ -16,71 +16,65 @@ #error "This file requires ARC support." #endif -@interface LanguageSelectionCoordinator ()< - LanguageSelectionViewControllerDelegate, - ContainedPresenterDelegate> +@interface LanguageSelectionCoordinator () < + LanguageSelectionHandler, + LanguageSelectionViewControllerDelegate> + +// The WebStateList being observed. +@property(nonatomic) WebStateList* webStateList; // Presenter to use to for presenting the view controller. @property(nonatomic) id<ContainedPresenter> presenter; -// The base view controller the instance was initialized with. -@property(nonatomic, weak) UIViewController* baseViewController; // The view controller this coordinator manages. @property(nonatomic) LanguageSelectionViewController* selectionViewController; // A mediator to interoperate with the translation model. @property(nonatomic) LanguageSelectionMediator* selectionMediator; // A delegate, provided by showLanguageSelectorWithContext:delegate:. @property(nonatomic, weak) id<LanguageSelectionDelegate> selectionDelegate; -// YES if the coordinator has started displaying its UI. -@property(nonatomic, readonly) BOOL started; - -// Starts displaying the UI for this coordinator, using self.presenter to handle -// the positioning and display of self.selectionViewController. -// It is an error to call this method when self.presenter is nil. -- (void)start; - -// Cleans up state after the UI for this coordinator has stopped being -// displayed. -- (void)stop; +// YES if the coordinator has been started. +@property(nonatomic) BOOL started; @end @implementation LanguageSelectionCoordinator -@synthesize baseViewController = _baseViewController; -@synthesize presenter = _presenter; -@synthesize selectionViewController = _selectionViewController; -@synthesize selectionMediator = _selectionMediator; -@synthesize selectionDelegate = _selectionDelegate; - -- (nullable instancetype)initWithBaseViewController: - (UIViewController*)viewController { - if ((self = [super init])) { - _baseViewController = viewController; +- (instancetype)initWithBaseViewController:(UIViewController*)viewController + browserState: + (ios::ChromeBrowserState*)browserState + webStateList:(WebStateList*)webStateList { + DCHECK(webStateList); + self = [super initWithBaseViewController:viewController + browserState:browserState]; + if (self) { + _webStateList = webStateList; } return self; } -#pragma mark - private property implementation - -- (BOOL)started { - return self.presenter.presentedViewController != nil; -} - #pragma mark - private methods - (void)start { - self.presenter = [[VerticalAnimationContainer alloc] init]; - self.presenter.baseViewController = self.baseViewController; - self.presenter.presentedViewController = self.selectionViewController; - self.presenter.delegate = self; + if (self.started) + return; - [self.presenter prepareForPresentation]; + self.selectionMediator = + [[LanguageSelectionMediator alloc] initWithLanguageSelectionHandler:self]; + self.selectionMediator.webStateList = self.webStateList; - [self.presenter presentAnimated:YES]; + self.started = YES; } - (void)stop { - self.selectionViewController = nil; + if (!self.started) + return; + + [self dismissLanguageSelector]; + [self.selectionMediator disconnect]; self.selectionMediator = nil; + self.presenter = nil; + self.selectionViewController = nil; + self.selectionDelegate = nil; + + self.started = NO; } #pragma mark - LanguageSelectionHandler @@ -88,25 +82,22 @@ - (void)showLanguageSelectorWithContext:(LanguageSelectionContext*)context delegate: (id<LanguageSelectionDelegate>)delegate { - if (self.started) - return; - self.selectionDelegate = delegate; - self.selectionMediator = - [[LanguageSelectionMediator alloc] initWithContext:context]; + self.selectionMediator.context = context; self.selectionViewController = [[LanguageSelectionViewController alloc] init]; self.selectionViewController.delegate = self; self.selectionMediator.consumer = self.selectionViewController; - [self start]; + self.presenter = [[VerticalAnimationContainer alloc] init]; + self.presenter.baseViewController = self.baseViewController; + self.presenter.presentedViewController = self.selectionViewController; + [self.presenter prepareForPresentation]; + [self.presenter presentAnimated:YES]; } - (void)dismissLanguageSelector { - if (!self.started) - return; - [self.selectionDelegate languageSelectorClosedWithoutSelection]; [self.presenter dismissAnimated:NO]; } @@ -125,15 +116,4 @@ [self.presenter dismissAnimated:YES]; } -#pragma mark - ContainedPresenterDelegate - -- (void)containedPresenterDidPresent:(id<ContainedPresenter>)presenter { - DCHECK(presenter == self.presenter); -} - -- (void)containedPresenterDidDismiss:(id<ContainedPresenter>)presenter { - DCHECK(presenter == self.presenter); - [self stop]; -} - @end
diff --git a/ios/chrome/browser/ui/translate/language_selection_mediator.h b/ios/chrome/browser/ui/translate/language_selection_mediator.h index de067951..46154619 100644 --- a/ios/chrome/browser/ui/translate/language_selection_mediator.h +++ b/ios/chrome/browser/ui/translate/language_selection_mediator.h
@@ -10,16 +10,26 @@ @protocol LanguageSelectionConsumer; @class LanguageSelectionContext; +@protocol LanguageSelectionHandler; +class WebStateList; // Mediator object to configure and provide data for language selection. @interface LanguageSelectionMediator : NSObject -// Designated initializer. |context| is the context object provided for language -// selection. -- (instancetype)initWithContext:(LanguageSelectionContext*)context - NS_DESIGNATED_INITIALIZER; +// |handler| presents and dismisses the language selection UI. +- (instancetype)initWithLanguageSelectionHandler: + (id<LanguageSelectionHandler>)handler NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; +// Disconnects the mediator. +- (void)disconnect; + +// The WebStateList being observed. +@property(nonatomic) WebStateList* webStateList; + +// The context object provided for language selection. +@property(nonatomic) LanguageSelectionContext* context; + // Consumer for this mediator. @property(nonatomic, weak) id<LanguageSelectionConsumer> consumer;
diff --git a/ios/chrome/browser/ui/translate/language_selection_mediator.mm b/ios/chrome/browser/ui/translate/language_selection_mediator.mm index 9cb7dc98..4ac89b5 100644 --- a/ios/chrome/browser/ui/translate/language_selection_mediator.mm +++ b/ios/chrome/browser/ui/translate/language_selection_mediator.mm
@@ -4,51 +4,158 @@ #import "ios/chrome/browser/ui/translate/language_selection_mediator.h" +#include <memory> + #include "base/logging.h" +#include "base/scoped_observer.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "components/translate/core/browser/translate_infobar_delegate.h" +#include "ios/chrome/browser/translate/chrome_ios_translate_client.h" #import "ios/chrome/browser/translate/language_selection_context.h" +#import "ios/chrome/browser/translate/language_selection_handler.h" #import "ios/chrome/browser/ui/translate/language_selection_consumer.h" #import "ios/chrome/browser/ui/translate/language_selection_provider.h" +#import "ios/chrome/browser/web_state_list/web_state_list.h" +#import "ios/chrome/browser/web_state_list/web_state_list_observer_bridge.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif -@interface LanguageSelectionMediator ()<LanguageSelectionProvider> -@property(nonatomic) LanguageSelectionContext* context; +@interface LanguageSelectionMediator () <WebStateListObserving, + LanguageSelectionProvider> { + // WebStateList observers. + std::unique_ptr<WebStateListObserverBridge> _webStateListObserverBridge; + std::unique_ptr<ScopedObserver<WebStateList, WebStateListObserver>> + _scopedWebStateListObserver; +} + +// The language selection handler. +@property(nonatomic, weak) id<LanguageSelectionHandler> + languageSelectionHandler; + @end @implementation LanguageSelectionMediator -@synthesize consumer = _consumer; -@synthesize context = _context; - -- (instancetype)initWithContext:(LanguageSelectionContext*)context { +- (instancetype)initWithLanguageSelectionHandler: + (id<LanguageSelectionHandler>)handler { + DCHECK(handler); if ((self = [super init])) { - _context = context; + _languageSelectionHandler = handler; } return self; } +#pragma mark - Public methods + +- (void)disconnect { + self.webStateList = nil; +} + +- (std::string)languageCodeForLanguageAtIndex:(int)index { + DCHECK(self.context); + return self.context.languageData->language_code_at(index); +} + +#pragma mark - Properties + - (void)setConsumer:(id<LanguageSelectionConsumer>)consumer { _consumer = consumer; + DCHECK(self.context); self.consumer.languageCount = self.context.languageData->num_languages(); self.consumer.initialLanguageIndex = self.context.initialLanguageIndex; self.consumer.disabledLanguageIndex = self.context.unavailableLanguageIndex; self.consumer.provider = self; } -#pragma mark - Public methods +- (void)setWebStateList:(WebStateList*)webStateList { + if (_webStateList == webStateList) + return; -- (std::string)languageCodeForLanguageAtIndex:(int)index { - return self.context.languageData->language_code_at(index); + if (_webStateList) { + [self removeWebStateListObserver]; + + // Uninstall delegates for each WebState in WebStateList. + for (int i = 0; i < self.webStateList->count(); i++) { + [self uninstallDelegatesForWebState:self.webStateList->GetWebStateAt(i)]; + } + } + + _webStateList = webStateList; + + if (_webStateList) { + // Install delegates for each WebState in WebStateList. + for (int i = 0; i < _webStateList->count(); i++) { + [self installDelegatesForWebState:_webStateList->GetWebStateAt(i)]; + } + + [self addWebStateListObserver]; + } +} + +#pragma mark - Private + +// Adds observer for WebStateList. +- (void)addWebStateListObserver { + _webStateListObserverBridge = + std::make_unique<WebStateListObserverBridge>(self); + _scopedWebStateListObserver = + std::make_unique<ScopedObserver<WebStateList, WebStateListObserver>>( + _webStateListObserverBridge.get()); + _scopedWebStateListObserver->Add(self.webStateList); +} + +// Removes observer for WebStateList. +- (void)removeWebStateListObserver { + _scopedWebStateListObserver.reset(); + _webStateListObserverBridge.reset(); +} + +// Installs delegates for |webState|. +- (void)installDelegatesForWebState:(web::WebState*)webState { + if (ChromeIOSTranslateClient::FromWebState(webState)) { + ChromeIOSTranslateClient::FromWebState(webState) + ->set_language_selection_handler(self.languageSelectionHandler); + } +} + +// Uninstalls delegates for |webState|. +- (void)uninstallDelegatesForWebState:(web::WebState*)webState { + if (ChromeIOSTranslateClient::FromWebState(webState)) { + ChromeIOSTranslateClient::FromWebState(webState) + ->set_language_selection_handler(nil); + } +} + +#pragma mark - WebStateListObserving + +- (void)webStateList:(WebStateList*)webStateList + didInsertWebState:(web::WebState*)webState + atIndex:(int)index + activating:(BOOL)activating { + [self installDelegatesForWebState:webState]; +} + +- (void)webStateList:(WebStateList*)webStateList + didReplaceWebState:(web::WebState*)oldWebState + withWebState:(web::WebState*)newWebState + atIndex:(int)index { + [self uninstallDelegatesForWebState:oldWebState]; + [self installDelegatesForWebState:newWebState]; +} + +- (void)webStateList:(WebStateList*)webStateList + didDetachWebState:(web::WebState*)webState + atIndex:(int)index { + [self uninstallDelegatesForWebState:webState]; } #pragma mark - LanguageSelectionProvider - (NSString*)languageNameAtIndex:(int)languageIndex { + DCHECK(self.context); if (languageIndex < 0 || languageIndex >= static_cast<int>(self.context.languageData->num_languages())) {
diff --git a/ios/chrome/browser/web/chrome_web_client.mm b/ios/chrome/browser/web/chrome_web_client.mm index c02e5bc..9343a37 100644 --- a/ios/chrome/browser/web/chrome_web_client.mm +++ b/ios/chrome/browser/web/chrome_web_client.mm
@@ -22,7 +22,7 @@ #include "ios/chrome/browser/chrome_url_constants.h" #include "ios/chrome/browser/experimental_flags.h" #include "ios/chrome/browser/ios_chrome_main_parts.h" -#include "ios/chrome/browser/passwords/credential_manager_features.h" +#include "ios/chrome/browser/passwords/password_manager_features.h" #include "ios/chrome/browser/ssl/ios_ssl_error_handler.h" #import "ios/chrome/browser/ui/chrome_web_view_factory.h" #import "ios/chrome/browser/web/error_page_util.h"
diff --git a/ios/chrome/browser/web/chrome_web_client_unittest.mm b/ios/chrome/browser/web/chrome_web_client_unittest.mm index 99055cc..463de89 100644 --- a/ios/chrome/browser/web/chrome_web_client_unittest.mm +++ b/ios/chrome/browser/web/chrome_web_client_unittest.mm
@@ -15,7 +15,7 @@ #include "base/test/scoped_task_environment.h" #include "ios/chrome/browser/browser_state/test_chrome_browser_state.h" #include "ios/chrome/browser/chrome_url_constants.h" -#include "ios/chrome/browser/passwords/credential_manager_features.h" +#include "ios/chrome/browser/passwords/password_manager_features.h" #import "ios/chrome/browser/web/error_page_util.h" #import "ios/web/public/test/error_test_util.h" #import "ios/web/public/test/js_test_util.h"
diff --git a/ios/web_view/internal/sync/web_view_sync_client.mm b/ios/web_view/internal/sync/web_view_sync_client.mm index f3d9f598..5998e4f0 100644 --- a/ios/web_view/internal/sync/web_view_sync_client.mm +++ b/ios/web_view/internal/sync/web_view_sync_client.mm
@@ -4,6 +4,8 @@ #import "ios/web_view/internal/sync/web_view_sync_client.h" +#include <algorithm> + #include "base/command_line.h" #include "base/logging.h" #include "base/task/post_task.h" @@ -20,6 +22,7 @@ #include "components/keyed_service/core/service_access_type.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/sync/password_model_worker.h" +#include "components/sync/driver/data_type_controller.h" #include "components/sync/driver/sync_api_component_factory.h" #include "components/sync/driver/sync_util.h" #include "components/sync/engine/passive_model_worker.h" @@ -141,9 +144,15 @@ syncer::DataTypeController::TypeVector WebViewSyncClient::CreateDataTypeControllers() { - // The iOS port does not have any platform-specific datatypes. - return component_factory_->CreateCommonDataTypeControllers( - GetDisabledTypes()); + // iOS WebView uses butter sync and so has no need to record user consents. + syncer::DataTypeController::TypeVector type_vector = + component_factory_->CreateCommonDataTypeControllers(GetDisabledTypes()); + type_vector.erase(std::remove_if(type_vector.begin(), type_vector.end(), + [](const auto& data_type_controller) { + return data_type_controller->type() == + syncer::USER_CONSENTS; + })); + return type_vector; } BookmarkUndoService* WebViewSyncClient::GetBookmarkUndoServiceIfExists() {
diff --git a/ios/web_view/internal/web_view_web_main_parts.mm b/ios/web_view/internal/web_view_web_main_parts.mm index abe70f9..2b8ae17 100644 --- a/ios/web_view/internal/web_view_web_main_parts.mm +++ b/ios/web_view/internal/web_view_web_main_parts.mm
@@ -48,6 +48,7 @@ std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList); std::string enable_features = base::JoinString( {autofill::features::kAutofillEnableAccountWalletStorage.name, + autofill::features::kAutofillAlwaysShowServerCardsInSyncTransport.name, switches::kSyncStandaloneTransport.name, switches::kSyncSupportSecondaryAccount.name, switches::kSyncUSSAutofillWalletData.name},
diff --git a/mash/catalog_viewer/BUILD.gn b/mash/catalog_viewer/BUILD.gn index be8149f..62e9f06 100644 --- a/mash/catalog_viewer/BUILD.gn +++ b/mash/catalog_viewer/BUILD.gn
@@ -4,7 +4,7 @@ import("//build/config/ui.gni") import("//mojo/public/tools/bindings/mojom.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") source_set("lib") { @@ -26,7 +26,7 @@ ] } -service("catalog_viewer") { +service_executable("catalog_viewer") { sources = [ "main.cc", ] @@ -39,8 +39,6 @@ "//services/service_manager/public/mojom", "//ui/views/mus:for_mojo_application", ] - - resources = [ "$root_out_dir/views_mus_resources.pak" ] } service_manifest("manifest") {
diff --git a/mash/catalog_viewer/main.cc b/mash/catalog_viewer/main.cc index 65a916e..2fc7048 100644 --- a/mash/catalog_viewer/main.cc +++ b/mash/catalog_viewer/main.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "mash/catalog_viewer/catalog_viewer.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/mash/example/views_examples/BUILD.gn b/mash/example/views_examples/BUILD.gn index 28b491fe..5b2dc8c 100644 --- a/mash/example/views_examples/BUILD.gn +++ b/mash/example/views_examples/BUILD.gn
@@ -4,11 +4,11 @@ import("//build/config/ui.gni") import("//mojo/public/tools/bindings/mojom.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//tools/grit/repack.gni") -service("views_examples") { +service_executable("views_examples") { testonly = true sources = [ "views_examples.cc", @@ -28,8 +28,6 @@ "//ui/views/examples:views_examples_lib", "//ui/views/mus:for_mojo_application", ] - - resources = [ "$root_out_dir/views_mus_resources.pak" ] } service_manifest("manifest") {
diff --git a/mash/example/views_examples/views_examples.cc b/mash/example/views_examples/views_examples.cc index 0ce813d..8454923d 100644 --- a/mash/example/views_examples/views_examples.cc +++ b/mash/example/views_examples/views_examples.cc
@@ -14,7 +14,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "ui/views/examples/example_base.h" #include "ui/views/examples/examples_window.h"
diff --git a/mash/example/window_type_launcher/BUILD.gn b/mash/example/window_type_launcher/BUILD.gn index f9be856..fcb18900 100644 --- a/mash/example/window_type_launcher/BUILD.gn +++ b/mash/example/window_type_launcher/BUILD.gn
@@ -4,11 +4,11 @@ import("//build/config/ui.gni") import("//mojo/public/tools/bindings/mojom.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//tools/grit/repack.gni") -service("window_type_launcher") { +service_executable("window_type_launcher") { testonly = true sources = [ "window_type_launcher.cc", @@ -31,8 +31,6 @@ "//ui/views", "//ui/views/mus:for_mojo_application", ] - - resources = [ "$root_out_dir/views_mus_resources.pak" ] } service_manifest("manifest") {
diff --git a/mash/example/window_type_launcher/window_type_launcher.cc b/mash/example/window_type_launcher/window_type_launcher.cc index 44bdf39..6fce65e2 100644 --- a/mash/example/window_type_launcher/window_type_launcher.cc +++ b/mash/example/window_type_launcher/window_type_launcher.cc
@@ -15,7 +15,7 @@ #include "base/threading/platform_thread.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/ws/public/cpp/property_type_converters.h" #include "services/ws/public/mojom/window_manager.mojom.h" #include "ui/aura/window.h"
diff --git a/mash/session/BUILD.gn b/mash/session/BUILD.gn index 5afad9f0..2ca9519 100644 --- a/mash/session/BUILD.gn +++ b/mash/session/BUILD.gn
@@ -4,7 +4,7 @@ import("//build/config/ui.gni") import("//mojo/public/tools/bindings/mojom.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//tools/grit/repack.gni") @@ -31,7 +31,7 @@ } } -service("session") { +service_executable("session") { output_name = "mash_session" sources = [ "main.cc",
diff --git a/mash/session/main.cc b/mash/session/main.cc index 92aaeb7..1f668330 100644 --- a/mash/session/main.cc +++ b/mash/session/main.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "mash/session/session.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/mash/task_viewer/BUILD.gn b/mash/task_viewer/BUILD.gn index 3a6f6f5..fb339d5 100644 --- a/mash/task_viewer/BUILD.gn +++ b/mash/task_viewer/BUILD.gn
@@ -4,7 +4,7 @@ import("//build/config/ui.gni") import("//mojo/public/tools/bindings/mojom.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") source_set("lib") { @@ -26,7 +26,7 @@ ] } -service("task_viewer") { +service_executable("task_viewer") { sources = [ "main.cc", ] @@ -39,8 +39,6 @@ "//services/service_manager/public/mojom", "//ui/views/mus:for_mojo_application", ] - - resources = [ "$root_out_dir/views_mus_resources.pak" ] } service_manifest("manifest") {
diff --git a/mash/task_viewer/main.cc b/mash/task_viewer/main.cc index aea0c08..efadca20 100644 --- a/mash/task_viewer/main.cc +++ b/mash/task_viewer/main.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "mash/task_viewer/task_viewer.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/media/audio/audio_thread_hang_monitor.cc b/media/audio/audio_thread_hang_monitor.cc index fdff50c..7e94838 100644 --- a/media/audio/audio_thread_hang_monitor.cc +++ b/media/audio/audio_thread_hang_monitor.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/bind.h" -#include "base/debug/alias.h" #include "base/debug/dump_without_crashing.h" #include "base/location.h" #include "base/metrics/histogram_macros.h" @@ -80,12 +79,6 @@ void AudioThreadHangMonitor::StartTimer() { DCHECK_CALLED_ON_VALID_SEQUENCE(monitor_sequence_); - auto* pm = base::PowerMonitor::Get(); - if (pm) { - // May be null in unit tests. - pm->AddObserver(this); - } - // Set the flag to true so that the first run doesn't detect a hang. alive_flag_->flag_ = true; @@ -110,12 +103,6 @@ return audio_thread_status_ == ThreadStatus::kHung; } -void AudioThreadHangMonitor::OnResume() { - DCHECK_CALLED_ON_VALID_SEQUENCE(monitor_sequence_); - last_resume_time_ = clock_->NowTicks(); - recent_ping_state_ = 0; -} - void AudioThreadHangMonitor::CheckIfAudioThreadIsAlive() { DCHECK_CALLED_ON_VALID_SEQUENCE(monitor_sequence_); @@ -152,9 +139,6 @@ LogHistogramThreadStatus(); if (dump_on_hang_) { - int64_t time_since_resume = - (clock_->NowTicks() - last_resume_time_).InMilliseconds(); - base::debug::Alias(&time_since_resume); base::debug::DumpWithoutCrashing(); } }
diff --git a/media/audio/audio_thread_hang_monitor.h b/media/audio/audio_thread_hang_monitor.h index e4ab0a66..bcd9d51 100644 --- a/media/audio/audio_thread_hang_monitor.h +++ b/media/audio/audio_thread_hang_monitor.h
@@ -13,7 +13,6 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" -#include "base/power_monitor/power_observer.h" #include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" #include "base/time/time.h" @@ -34,7 +33,7 @@ // posting a task to the audio thread every minute and checking that it was // executed. If three consecutive such pings are missed, the thread is // considered hung. -class MEDIA_EXPORT AudioThreadHangMonitor final : public base::PowerObserver { +class MEDIA_EXPORT AudioThreadHangMonitor final { public: using Ptr = std::unique_ptr<AudioThreadHangMonitor, base::OnTaskRunnerDeleter>; @@ -57,7 +56,7 @@ scoped_refptr<base::SingleThreadTaskRunner> audio_thread_task_runner, scoped_refptr<base::SequencedTaskRunner> monitor_task_runner = nullptr); - ~AudioThreadHangMonitor() final; + ~AudioThreadHangMonitor(); // Thread-safe. bool IsAudioThreadHung() const; @@ -85,10 +84,6 @@ bool NeverLoggedThreadHung() const; bool NeverLoggedThreadRecoveredAfterHung() const; - // base::PowerObserver overrides. - // Reset hang detection state when the system comes out of the suspend state. - void OnResume() final; - // This function is run by the |timer_|. It checks if the audio thread has // shown signs of life since the last time it was called (by checking the // |alive_flag_|) and updates the value of |successful_pings_| and @@ -126,9 +121,6 @@ // detecting the audio thread as hung. base::TimeTicks last_check_time_ = base::TimeTicks(); - // Used to investigate hangs. - base::TimeTicks last_resume_time_ = base::TimeTicks(); - // |recent_ping_state_| tracks the recent life signs from the audio thread. If // the most recent ping was successful, the number indicates the number of // successive successful pings. If the most recent ping was failed, the number
diff --git a/media/gpu/windows/d3d11_video_decoder.cc b/media/gpu/windows/d3d11_video_decoder.cc index 4f87781..f9b2c9c9 100644 --- a/media/gpu/windows/d3d11_video_decoder.cc +++ b/media/gpu/windows/d3d11_video_decoder.cc
@@ -225,7 +225,7 @@ init_cb_ = init_cb; output_cb_ = output_cb; - is_encrypted_ = config.is_encrypted(); + config_ = config; D3D11VideoDecoderImpl::InitCB cb = base::BindOnce( &D3D11VideoDecoder::OnGpuInitComplete, weak_factory_.GetWeakPtr()); @@ -306,7 +306,7 @@ return; } - if (is_encrypted_) + if (config_.is_encrypted()) dec_config.guidConfigBitstreamEncryption = D3D11_DECODER_ENCRYPTION_HW_CENC; memcpy(&decoder_guid_, &decoder_guid, sizeof decoder_guid_); @@ -326,7 +326,7 @@ #endif // Ensure that if we are encrypted, that we have a CDM. - if (is_encrypted_ && !proxy_context) { + if (config_.is_encrypted() && !proxy_context) { NotifyError("Video stream is encrypted, but no cdm was found"); return; } @@ -551,7 +551,7 @@ // thread and D3D device. See https://crbug.com/911847 texture_desc.MiscFlags = 0; } - if (is_encrypted_) + if (config_.is_encrypted()) texture_desc.MiscFlags |= D3D11_RESOURCE_MISC_HW_PROTECTED; Microsoft::WRL::ComPtr<ID3D11Texture2D> out_texture; @@ -600,11 +600,14 @@ picture_buffer->set_in_client_use(true); // Note: The pixel format doesn't matter. - gfx::Rect visible_rect(picture->visible_rect()); - // TODO(liberato): Pixel aspect ratio should come from the VideoDecoderConfig - // (except when it should come from the SPS). - // https://crbug.com/837337 - double pixel_aspect_ratio = 1.0; + gfx::Rect visible_rect = picture->visible_rect(); + if (visible_rect.IsEmpty()) + visible_rect = config_.visible_rect(); + + // TODO(https://crbug.com/843150): Use aspect ratio from decoder (SPS) if + // stream metadata doesn't overrride it. + double pixel_aspect_ratio = config_.GetPixelAspectRatio(); + base::TimeDelta timestamp = picture_buffer->timestamp_; scoped_refptr<VideoFrame> frame = VideoFrame::WrapNativeTextures( PIXEL_FORMAT_NV12, picture_buffer->mailbox_holders(), @@ -621,7 +624,7 @@ // that ALLOW_OVERLAY is required for encrypted video path. frame->metadata()->SetBoolean(VideoFrameMetadata::ALLOW_OVERLAY, true); - if (is_encrypted_) { + if (config_.is_encrypted()) { frame->metadata()->SetBoolean(VideoFrameMetadata::PROTECTED_VIDEO, true); frame->metadata()->SetBoolean(VideoFrameMetadata::HW_PROTECTED, true); }
diff --git a/media/gpu/windows/d3d11_video_decoder.h b/media/gpu/windows/d3d11_video_decoder.h index a80f2a49..158e815 100644 --- a/media/gpu/windows/d3d11_video_decoder.h +++ b/media/gpu/windows/d3d11_video_decoder.h
@@ -193,7 +193,7 @@ // During init, these will be set. InitCB init_cb_; OutputCB output_cb_; - bool is_encrypted_ = false; + VideoDecoderConfig config_; D3D11CreateDeviceCB create_device_func_;
diff --git a/media/mojo/services/BUILD.gn b/media/mojo/services/BUILD.gn index fb4d010..4e6b4a3 100644 --- a/media/mojo/services/BUILD.gn +++ b/media/mojo/services/BUILD.gn
@@ -5,7 +5,7 @@ import("//build/config/jumbo.gni") import("//media/media_options.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -205,7 +205,7 @@ # service out-of-process. While CdmService is tested as a packaged service, # which runs the service in-process. -service("media") { +service_executable("media") { testonly = true sources = [
diff --git a/media/mojo/services/main.cc b/media/mojo/services/main.cc index 0ee648b..b8d4318 100644 --- a/media/mojo/services/main.cc +++ b/media/mojo/services/main.cc
@@ -5,7 +5,7 @@ #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "media/mojo/services/media_service_factory.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" void ServiceMain(service_manager::mojom::ServiceRequest request) {
diff --git a/media/test/mock_media_source.cc b/media/test/mock_media_source.cc index d68cd0a..373ebdfea 100644 --- a/media/test/mock_media_source.cc +++ b/media/test/mock_media_source.cc
@@ -146,7 +146,7 @@ append_window_start_, append_window_end_, &last_timestamp_offset_); current_position_ += size; - ASSERT_EQ(expect_append_success_, success); + VerifyExpectedAppendResult(success); if (do_eos_after_next_append_) { do_eos_after_next_append_ = false; @@ -173,8 +173,7 @@ const uint8_t* pData, int size) { CHECK(!chunk_demuxer_->IsParsingMediaSegment(kSourceId)); - ASSERT_EQ( - expect_append_success_, + VerifyExpectedAppendResult( chunk_demuxer_->AppendData(kSourceId, pData, size, append_window_start, append_window_end, ×tamp_offset)); last_timestamp_offset_ = timestamp_offset; @@ -275,4 +274,12 @@ InitSegmentReceivedMock(tracks); } +void MockMediaSource::VerifyExpectedAppendResult(bool append_result) { + if (expected_append_result_ == ExpectedAppendResult::kSuccessOrFailure) + return; // |append_result| is ignored in this case. + + ASSERT_EQ(expected_append_result_ == ExpectedAppendResult::kSuccess, + append_result); +} + } // namespace media
diff --git a/media/test/mock_media_source.h b/media/test/mock_media_source.h index 1474cf19..7155144 100644 --- a/media/test/mock_media_source.h +++ b/media/test/mock_media_source.h
@@ -22,6 +22,12 @@ // Media Source API. class MockMediaSource { public: + enum class ExpectedAppendResult { + kSuccess, + kFailure, + kSuccessOrFailure, // e.g., for fuzzing when parse may pass or fail + }; + MockMediaSource(const std::string& filename, const std::string& mimetype, size_t initial_append_size, @@ -87,8 +93,8 @@ return last_timestamp_offset_; } - void set_expect_append_success(bool expectation) { - expect_append_success_ = expectation; + void set_expected_append_result(ExpectedAppendResult expectation) { + expected_append_result_ = expectation; } void InitSegmentReceived(std::unique_ptr<MediaTracks> tracks); @@ -97,6 +103,8 @@ MOCK_METHOD1(OnParseWarningMock, void(const SourceBufferParseWarning)); private: + void VerifyExpectedAppendResult(bool append_result); + MediaLog media_log_; scoped_refptr<DecoderBuffer> file_data_; size_t current_position_; @@ -111,7 +119,7 @@ base::TimeDelta append_window_start_; base::TimeDelta append_window_end_ = kInfiniteDuration; bool do_eos_after_next_append_ = false; - bool expect_append_success_ = true; + ExpectedAppendResult expected_append_result_ = ExpectedAppendResult::kSuccess; DISALLOW_COPY_AND_ASSIGN(MockMediaSource); };
diff --git a/media/test/pipeline_integration_fuzzertest.cc b/media/test/pipeline_integration_fuzzertest.cc index 9ea4e897ae..80ebfaa 100644 --- a/media/test/pipeline_integration_fuzzertest.cc +++ b/media/test/pipeline_integration_fuzzertest.cc
@@ -201,11 +201,19 @@ source.set_encrypted_media_init_data_cb( base::Bind(&OnEncryptedMediaInitData, this)); + // Allow parsing to either pass or fail without emitting a gtest failure + // from MockMediaSource. + source.set_expected_append_result( + MockMediaSource::ExpectedAppendResult::kSuccessOrFailure); + // TODO(wolenetz): Vary the behavior (abort/remove/seek/endOfStream/Append // in pieces/append near play-head/vary append mode/etc), perhaps using // CustomMutator and Seed to insert/update the variation information into/in // the |data| we process here. See https://crbug.com/750818. - if (PIPELINE_OK != StartPipelineWithMediaSource(&source)) + // Use |kDemuxerMayPassOrFail| test type to allow pipeline start to either + // pass or fail without emitting a gtest failure. + if (PIPELINE_OK != + StartPipelineWithMediaSource(&source, kDemuxerMayPassOrFail, nullptr)) return; Play();
diff --git a/media/test/pipeline_integration_test.cc b/media/test/pipeline_integration_test.cc index a58f4bc..baec0cb 100644 --- a/media/test/pipeline_integration_test.cc +++ b/media/test/pipeline_integration_test.cc
@@ -1457,7 +1457,8 @@ // pipeline is still completing renderer setup. MockMediaSource source("bear-320x240_corrupted_after_init_segment.webm", 4380); - source.set_expect_append_success(false); + source.set_expected_append_result( + MockMediaSource::ExpectedAppendResult::kFailure); EXPECT_EQ(CHUNK_DEMUXER_ERROR_APPEND_FAILED, StartPipelineWithMediaSource(&source)); } @@ -2277,7 +2278,8 @@ EXPECT_CALL(*this, OnVideoNaturalSizeChange(gfx::Size(1280, 720))).Times(1); scoped_refptr<DecoderBuffer> second_file = ReadTestDataFile("bear-1280x720-v_frag-cenc.mp4"); - source.set_expect_append_success(false); + source.set_expected_append_result( + MockMediaSource::ExpectedAppendResult::kFailure); source.AppendAtTime(base::TimeDelta::FromSeconds(kAppendTimeSec), second_file->data(), second_file->data_size()); @@ -2309,7 +2311,8 @@ scoped_refptr<DecoderBuffer> second_file = ReadTestDataFile("bear-1280x720-av_frag.mp4"); - source.set_expect_append_success(false); + source.set_expected_append_result( + MockMediaSource::ExpectedAppendResult::kFailure); source.AppendAtTime(base::TimeDelta::FromSeconds(kAppendTimeSec), second_file->data(), second_file->data_size());
diff --git a/media/test/pipeline_integration_test_base.cc b/media/test/pipeline_integration_test_base.cc index 89c19b7..1993e16 100644 --- a/media/test/pipeline_integration_test_base.cc +++ b/media/test/pipeline_integration_test_base.cc
@@ -585,7 +585,9 @@ FakeEncryptedMedia* encrypted_media) { ParseTestTypeFlags(test_type); - if (!(test_type & kExpectDemuxerFailure)) + if (test_type & kDemuxerMayPassOrFail) + EXPECT_CALL(*source, InitSegmentReceivedMock(_)).Times(AnyNumber()); + else if (!(test_type & kExpectDemuxerFailure)) EXPECT_CALL(*source, InitSegmentReceivedMock(_)).Times(AtLeast(1)); EXPECT_CALL(*this, OnMetadata(_))
diff --git a/media/test/pipeline_integration_test_base.h b/media/test/pipeline_integration_test_base.h index eb35397..70e37641 100644 --- a/media/test/pipeline_integration_test_base.h +++ b/media/test/pipeline_integration_test_base.h
@@ -89,6 +89,7 @@ kUnreliableDuration = 8, kWebAudio = 16, kMonoOutput = 32, + kDemuxerMayPassOrFail = 64, // e.g., for demuxer fuzzing }; // Setup method to intialize various state according to flags.
diff --git a/mojo/public/tools/bindings/generators/mojom_js_generator.py b/mojo/public/tools/bindings/generators/mojom_js_generator.py index 9191abc..fe53ec5 100644 --- a/mojo/public/tools/bindings/generators/mojom_js_generator.py +++ b/mojo/public/tools/bindings/generators/mojom_js_generator.py
@@ -77,16 +77,16 @@ mojom.DOUBLE: "number", mojom.STRING: "string", mojom.NULLABLE_STRING: "string", - mojom.HANDLE: "mojo.MojoHandle", - mojom.DCPIPE: "mojo.MojoHandle", - mojom.DPPIPE: "mojo.MojoHandle", - mojom.MSGPIPE: "mojo.MojoHandle", - mojom.SHAREDBUFFER: "mojo.MojoHandle", - mojom.NULLABLE_HANDLE: "mojo.MojoHandle", - mojom.NULLABLE_DCPIPE: "mojo.MojoHandle", - mojom.NULLABLE_DPPIPE: "mojo.MojoHandle", - mojom.NULLABLE_MSGPIPE: "mojo.MojoHandle", - mojom.NULLABLE_SHAREDBUFFER: "mojo.MojoHandle", + mojom.HANDLE: "MojoHandle", + mojom.DCPIPE: "MojoHandle", + mojom.DPPIPE: "MojoHandle", + mojom.MSGPIPE: "MojoHandle", + mojom.SHAREDBUFFER: "MojoHandle", + mojom.NULLABLE_HANDLE: "MojoHandle", + mojom.NULLABLE_DCPIPE: "MojoHandle", + mojom.NULLABLE_DPPIPE: "MojoHandle", + mojom.NULLABLE_MSGPIPE: "MojoHandle", + mojom.NULLABLE_SHAREDBUFFER: "MojoHandle", } _kind_to_lite_js_type = {
diff --git a/mojo/public/tools/bindings/mojom.gni b/mojo/public/tools/bindings/mojom.gni index 57d12ad..2b2d65c 100644 --- a/mojo/public/tools/bindings/mojom.gni +++ b/mojo/public/tools/bindings/mojom.gni
@@ -1286,6 +1286,28 @@ } } } + + js_externs_target_suffix = "_js_externs" + js_externs_target_name = "${target_name}${js_externs_target_suffix}" + if (defined(invoker.sources)) { + js_library(js_externs_target_name) { + sources = [] + extra_public_deps = [ ":$generator_js_target_name" ] + externs_list = [ "${externs_path}/mojo.js" ] + externs_list += process_file_template( + invoker.sources, + [ "{{source_gen_dir}}/{{source_name_part}}.mojom-lite.externs.js" ]) + + deps = [] + foreach(d, all_deps) { + full_name = get_label_info(d, "label_no_toolchain") + deps += [ "${full_name}${js_externs_target_suffix}" ] + } + } + } else { + group(js_externs_target_name) { + } + } } }
diff --git a/net/spdy/header_coalescer.cc b/net/spdy/header_coalescer.cc index d53f152..be4c9c53 100644 --- a/net/spdy/header_coalescer.cc +++ b/net/spdy/header_coalescer.cc
@@ -17,6 +17,7 @@ #include "net/base/escape.h" #include "net/http/http_log_util.h" #include "net/http/http_util.h" +#include "net/log/net_log.h" namespace net { namespace { @@ -27,11 +28,10 @@ base::StringPiece error_message, NetLogCaptureMode capture_mode) { auto dict = std::make_unique<base::DictionaryValue>(); - dict->SetString("header_name", EscapeExternalHandlerValue(header_name)); - dict->SetString( - "header_value", - EscapeExternalHandlerValue(ElideHeaderValueForNetLog( - capture_mode, header_name.as_string(), header_value.as_string()))); + dict->SetKey("header_name", NetLogStringValue(header_name)); + dict->SetKey("header_value", NetLogStringValue(ElideHeaderValueForNetLog( + capture_mode, header_name.as_string(), + header_value.as_string()))); dict->SetString("error", error_message); return std::move(dict); }
diff --git a/net/spdy/header_coalescer_test.cc b/net/spdy/header_coalescer_test.cc index c6e4187..72693b87 100644 --- a/net/spdy/header_coalescer_test.cc +++ b/net/spdy/header_coalescer_test.cc
@@ -101,7 +101,8 @@ base::StringPiece header_name("\x1\x7F\x80\xFF"); header_coalescer_.OnHeader(header_name, "foo"); EXPECT_TRUE(header_coalescer_.error_seen()); - ExpectEntry("%01%7F%80%FF", "foo", "Invalid character in header name."); + ExpectEntry("%ESCAPED:\xE2\x80\x8B \x1\x7F%80%FF", "foo", + "Invalid character in header name."); } // RFC 7540 Section 8.1.2.6. Uppercase in header name is invalid. @@ -139,19 +140,19 @@ TEST_F(HeaderCoalescerTest, HeaderValueContainsLF) { header_coalescer_.OnHeader("foo", "bar\nbaz"); EXPECT_TRUE(header_coalescer_.error_seen()); - ExpectEntry("foo", "bar%0Abaz", "Invalid character 0x0A in header value."); + ExpectEntry("foo", "bar\nbaz", "Invalid character 0x0A in header value."); } TEST_F(HeaderCoalescerTest, HeaderValueContainsCR) { header_coalescer_.OnHeader("foo", "bar\rbaz"); EXPECT_TRUE(header_coalescer_.error_seen()); - ExpectEntry("foo", "bar%0Dbaz", "Invalid character 0x0D in header value."); + ExpectEntry("foo", "bar\rbaz", "Invalid character 0x0D in header value."); } TEST_F(HeaderCoalescerTest, HeaderValueContains0x7f) { header_coalescer_.OnHeader("foo", "bar\x7f baz"); EXPECT_TRUE(header_coalescer_.error_seen()); - ExpectEntry("foo", "bar%7F%20baz", "Invalid character 0x7F in header value."); + ExpectEntry("foo", "bar\x7F baz", "Invalid character 0x7F in header value."); } } // namespace test
diff --git a/ppapi/proxy/ppapi_command_buffer_proxy.cc b/ppapi/proxy/ppapi_command_buffer_proxy.cc index 5c1ba70..85440525 100644 --- a/ppapi/proxy/ppapi_command_buffer_proxy.cc +++ b/ppapi/proxy/ppapi_command_buffer_proxy.cc
@@ -171,7 +171,7 @@ } void PpapiCommandBufferProxy::SetLock(base::Lock*) { - NOTIMPLEMENTED(); + NOTREACHED(); } void PpapiCommandBufferProxy::EnsureWorkVisible() { @@ -206,22 +206,23 @@ } bool PpapiCommandBufferProxy::IsFenceSyncReleased(uint64_t release) { - NOTIMPLEMENTED(); + NOTREACHED(); return false; } void PpapiCommandBufferProxy::SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } -void PpapiCommandBufferProxy::WaitSyncTokenHint( - const gpu::SyncToken& sync_token) { - // TODO(sunnyps): Forward sync token dependency hints to the renderer. +// Pepper plugin does not expose or call WaitSyncTokenCHROMIUM. +void PpapiCommandBufferProxy::WaitSyncToken(const gpu::SyncToken& sync_token) { + NOTREACHED(); } bool PpapiCommandBufferProxy::CanWaitUnverifiedSyncToken( const gpu::SyncToken& sync_token) { + NOTREACHED(); return false; } @@ -232,13 +233,13 @@ void PpapiCommandBufferProxy::CreateGpuFence(uint32_t gpu_fence_id, ClientGpuFence source) { - NOTIMPLEMENTED(); + NOTREACHED(); } void PpapiCommandBufferProxy::GetGpuFence( uint32_t gpu_fence_id, base::OnceCallback<void(std::unique_ptr<gfx::GpuFence>)> callback) { - NOTIMPLEMENTED(); + NOTREACHED(); } void PpapiCommandBufferProxy::SetGpuControlClient(gpu::GpuControlClient*) {
diff --git a/ppapi/proxy/ppapi_command_buffer_proxy.h b/ppapi/proxy/ppapi_command_buffer_proxy.h index e2f137ca..44db7cae 100644 --- a/ppapi/proxy/ppapi_command_buffer_proxy.h +++ b/ppapi/proxy/ppapi_command_buffer_proxy.h
@@ -75,7 +75,7 @@ bool IsFenceSyncReleased(uint64_t release) override; void SignalSyncToken(const gpu::SyncToken& sync_token, base::OnceClosure callback) override; - void WaitSyncTokenHint(const gpu::SyncToken& sync_token) override; + void WaitSyncToken(const gpu::SyncToken& sync_token) override; bool CanWaitUnverifiedSyncToken(const gpu::SyncToken& sync_token) override; private:
diff --git a/services/audio/BUILD.gn b/services/audio/BUILD.gn index 2f45b30..575bcab 100644 --- a/services/audio/BUILD.gn +++ b/services/audio/BUILD.gn
@@ -5,14 +5,14 @@ import("//build/config/chromecast_build.gni") import("//media/webrtc/audio_processing.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") # Currently standalone service binaries are not supported on Android or iOS. standalone_supported = !(is_android || is_ios) -service("audio") { +service_executable("audio") { sources = [ "service_main.cc", ]
diff --git a/services/audio/service_main.cc b/services/audio/service_main.cc index ca3535b6..19d658f 100644 --- a/services/audio/service_main.cc +++ b/services/audio/service_main.cc
@@ -8,7 +8,7 @@ #include "services/audio/service.h" #include "services/audio/service_factory.h" #include "services/service_manager/public/cpp/binder_registry.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) { base::MessageLoop message_loop;
diff --git a/services/catalog/public/tools/catalog.gni b/services/catalog/public/tools/catalog.gni index 8700db35..cdcac1d1 100644 --- a/services/catalog/public/tools/catalog.gni +++ b/services/catalog/public/tools/catalog.gni
@@ -32,8 +32,9 @@ # Typically a standalone service binary is expected to live next to # the Service Manager embedder's binary, with the name # "${service_name}.service", with an additional ".exe" suffix on Windows. -# Binaries following this naming scheme are typically output by "service" -# targets (see //services/service_manager/public/cpp/service.gni). +# Binaries following this naming scheme are typically output by +# service_executable targets. See +# //services/service_manager/public/cpp/service_executable.gni. # # executable_overrides (optional) # A list of overrides to apply in catalog metadata for individual
diff --git a/services/device/BUILD.gn b/services/device/BUILD.gn index 83eecb14..cb1ba0c 100644 --- a/services/device/BUILD.gn +++ b/services/device/BUILD.gn
@@ -197,8 +197,8 @@ if (is_serial_enabled_platform) { sources += [ - "serial/serial_device_enumerator_impl_unittest.cc", - "serial/serial_io_handler_impl_unittest.cc", + "serial/serial_port_impl_unittest.cc", + "serial/serial_port_manager_impl_unittest.cc", ] deps += [ "//services/device/serial" ] }
diff --git a/services/device/device_service.cc b/services/device/device_service.cc index 1f69ae0..08d5487 100644 --- a/services/device/device_service.cc +++ b/services/device/device_service.cc
@@ -22,8 +22,8 @@ #include "services/device/geolocation/public_ip_address_location_notifier.h" #include "services/device/power_monitor/power_monitor_message_broadcaster.h" #include "services/device/public/mojom/battery_monitor.mojom.h" -#include "services/device/serial/serial_device_enumerator_impl.h" -#include "services/device/serial/serial_io_handler_impl.h" +#include "services/device/serial/serial_port_impl.h" +#include "services/device/serial/serial_port_manager_impl.h" #include "services/device/time_zone_monitor/time_zone_monitor.h" #include "services/device/wake_lock/wake_lock_provider.h" #include "services/network/public/cpp/shared_url_loader_factory.h" @@ -143,11 +143,10 @@ &DeviceService::BindTimeZoneMonitorRequest, base::Unretained(this))); registry_.AddInterface<mojom::WakeLockProvider>(base::Bind( &DeviceService::BindWakeLockProviderRequest, base::Unretained(this))); - registry_.AddInterface<mojom::SerialDeviceEnumerator>( - base::Bind(&DeviceService::BindSerialDeviceEnumeratorRequest, - base::Unretained(this))); - registry_.AddInterface<mojom::SerialIoHandler>(base::Bind( - &DeviceService::BindSerialIoHandlerRequest, base::Unretained(this))); + registry_.AddInterface<mojom::SerialPortManager>(base::Bind( + &DeviceService::BindSerialPortManagerRequest, base::Unretained(this))); + registry_.AddInterface<mojom::SerialPort>(base::Bind( + &DeviceService::BindSerialPortRequest, base::Unretained(this))); registry_.AddInterface<mojom::UsbDeviceManager>(base::Bind( &DeviceService::BindUsbDeviceManagerRequest, base::Unretained(this))); @@ -308,23 +307,21 @@ wake_lock_context_callback_); } -void DeviceService::BindSerialDeviceEnumeratorRequest( - mojom::SerialDeviceEnumeratorRequest request) { +void DeviceService::BindSerialPortManagerRequest( + mojom::SerialPortManagerRequest request) { #if (defined(OS_LINUX) && defined(USE_UDEV)) || defined(OS_WIN) || \ defined(OS_MACOSX) - SerialDeviceEnumeratorImpl::Create(std::move(request)); + SerialPortManagerImpl::Create(std::move(request)); #endif } -void DeviceService::BindSerialIoHandlerRequest( - mojom::SerialIoHandlerRequest request) { +void DeviceService::BindSerialPortRequest(mojom::SerialPortRequest request) { #if (defined(OS_LINUX) && defined(USE_UDEV)) || defined(OS_WIN) || \ defined(OS_MACOSX) if (io_task_runner_) { io_task_runner_->PostTask( - FROM_HERE, - base::Bind(&SerialIoHandlerImpl::Create, base::Passed(&request), - base::ThreadTaskRunnerHandle::Get())); + FROM_HERE, base::Bind(&SerialPortImpl::Create, base::Passed(&request), + base::ThreadTaskRunnerHandle::Get())); } #endif }
diff --git a/services/device/device_service.h b/services/device/device_service.h index 1aea599..997ecca6 100644 --- a/services/device/device_service.h +++ b/services/device/device_service.h
@@ -159,10 +159,9 @@ void BindWakeLockProviderRequest(mojom::WakeLockProviderRequest request); - void BindSerialDeviceEnumeratorRequest( - mojom::SerialDeviceEnumeratorRequest request); + void BindSerialPortManagerRequest(mojom::SerialPortManagerRequest request); - void BindSerialIoHandlerRequest(mojom::SerialIoHandlerRequest request); + void BindSerialPortRequest(mojom::SerialPortRequest request); void BindUsbDeviceManagerRequest(mojom::UsbDeviceManagerRequest request);
diff --git a/services/device/manifest.json b/services/device/manifest.json index beac967..f24fd909 100644 --- a/services/device/manifest.json +++ b/services/device/manifest.json
@@ -22,8 +22,8 @@ "device:power_monitor": [ "device.mojom.PowerMonitor" ], "device:screen_orientation": [ "device.mojom.ScreenOrientationListener" ], "device:serial": [ - "device.mojom.SerialDeviceEnumerator", - "device.mojom.SerialIoHandler" + "device.mojom.SerialPortManager", + "device.mojom.SerialPort" ], "device:time_zone_monitor": [ "device.mojom.TimeZoneMonitor" ], "device:usb": [ "device.mojom.UsbDeviceManager" ],
diff --git a/services/device/public/mojom/serial.mojom b/services/device/public/mojom/serial.mojom index 31a1709..145c552 100644 --- a/services/device/public/mojom/serial.mojom +++ b/services/device/public/mojom/serial.mojom
@@ -4,7 +4,7 @@ module device.mojom; -struct SerialDeviceInfo { +struct SerialPortInfo { string path; uint16 vendor_id; bool has_vendor_id = false; @@ -77,7 +77,7 @@ bool has_rts = false; }; -struct SerialDeviceControlSignals { +struct SerialPortControlSignals { bool dcd; bool cts; bool ri; @@ -85,12 +85,12 @@ }; // Discovers and enumerates serial devices available to the host. -interface SerialDeviceEnumerator { - GetDevices() => (array<SerialDeviceInfo> devices); +interface SerialPortManager { + GetDevices() => (array<SerialPortInfo> devices); }; // Performs asynchronous I/O on serial devices. -interface SerialIoHandler { +interface SerialPort { // Initiates an Open of the device then returns result. Open(string port, SerialConnectionOptions options) => (bool success); @@ -118,7 +118,7 @@ Flush() => (bool success); // Reads current control signals (DCD, CTS, etc.). - GetControlSignals() => (SerialDeviceControlSignals signals); + GetControlSignals() => (SerialPortControlSignals signals); // Sets one or more control signals (DTR and/or RTS) and returns result. SetControlSignals(SerialHostControlSignals signals) => (bool success);
diff --git a/services/device/serial/BUILD.gn b/services/device/serial/BUILD.gn index 84985df9..724a0a90 100644 --- a/services/device/serial/BUILD.gn +++ b/services/device/serial/BUILD.gn
@@ -12,10 +12,10 @@ ] sources = [ - "serial_device_enumerator_impl.cc", - "serial_device_enumerator_impl.h", - "serial_io_handler_impl.cc", - "serial_io_handler_impl.h", + "serial_port_impl.cc", + "serial_port_impl.h", + "serial_port_manager_impl.cc", + "serial_port_manager_impl.h", ] public_deps = [
diff --git a/services/device/serial/serial_device_enumerator_impl.h b/services/device/serial/serial_device_enumerator_impl.h deleted file mode 100644 index bb9f694f..0000000 --- a/services/device/serial/serial_device_enumerator_impl.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_DEVICE_SERIAL_SERIAL_DEVICE_ENUMERATOR_IMPL_H_ -#define SERVICES_DEVICE_SERIAL_SERIAL_DEVICE_ENUMERATOR_IMPL_H_ - -#include <memory> - -#include "base/macros.h" -#include "device/serial/serial_device_enumerator.h" -#include "services/device/public/mojom/serial.mojom.h" - -namespace device { - -// TODO(leonhsl): Merge this class with SerialDeviceEnumerator if/once -// SerialDeviceEnumerator is exposed only via the Device Service. -// crbug.com/748505 -class SerialDeviceEnumeratorImpl : public mojom::SerialDeviceEnumerator { - public: - static void Create(mojom::SerialDeviceEnumeratorRequest request); - - SerialDeviceEnumeratorImpl(); - ~SerialDeviceEnumeratorImpl() override; - - private: - // mojom::SerialDeviceEnumerator methods: - void GetDevices(GetDevicesCallback callback) override; - - std::unique_ptr<device::SerialDeviceEnumerator> enumerator_; - - DISALLOW_COPY_AND_ASSIGN(SerialDeviceEnumeratorImpl); -}; - -} // namespace device - -#endif // SERVICES_DEVICE_SERIAL_SERIAL_DEVICE_ENUMERATOR_IMPL_H_
diff --git a/services/device/serial/serial_io_handler_impl.cc b/services/device/serial/serial_port_impl.cc similarity index 61% rename from services/device/serial/serial_io_handler_impl.cc rename to services/device/serial/serial_port_impl.cc index e02a920e..87017f5 100644 --- a/services/device/serial/serial_io_handler_impl.cc +++ b/services/device/serial/serial_port_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/device/serial/serial_io_handler_impl.h" +#include "services/device/serial/serial_port_impl.h" #include "base/single_thread_task_runner.h" #include "base/task/post_task.h" @@ -12,26 +12,26 @@ namespace device { // static -void SerialIoHandlerImpl::Create( - mojom::SerialIoHandlerRequest request, +void SerialPortImpl::Create( + mojom::SerialPortRequest request, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) { - mojo::MakeStrongBinding(std::make_unique<SerialIoHandlerImpl>(ui_task_runner), + mojo::MakeStrongBinding(std::make_unique<SerialPortImpl>(ui_task_runner), std::move(request)); } -SerialIoHandlerImpl::SerialIoHandlerImpl( +SerialPortImpl::SerialPortImpl( scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) : io_handler_(device::SerialIoHandler::Create(ui_task_runner)) {} -SerialIoHandlerImpl::~SerialIoHandlerImpl() = default; +SerialPortImpl::~SerialPortImpl() = default; -void SerialIoHandlerImpl::Open(const std::string& port, - mojom::SerialConnectionOptionsPtr options, - OpenCallback callback) { +void SerialPortImpl::Open(const std::string& port, + mojom::SerialConnectionOptionsPtr options, + OpenCallback callback) { io_handler_->Open(port, *options, std::move(callback)); } -void SerialIoHandlerImpl::Read(uint32_t bytes, ReadCallback callback) { +void SerialPortImpl::Read(uint32_t bytes, ReadCallback callback) { auto buffer = base::MakeRefCounted<net::IOBuffer>(static_cast<size_t>(bytes)); io_handler_->Read(std::make_unique<ReceiveBuffer>( buffer, bytes, @@ -46,8 +46,8 @@ std::move(callback), buffer))); } -void SerialIoHandlerImpl::Write(const std::vector<uint8_t>& data, - WriteCallback callback) { +void SerialPortImpl::Write(const std::vector<uint8_t>& data, + WriteCallback callback) { io_handler_->Write(std::make_unique<SendBuffer>( data, base::BindOnce( [](WriteCallback callback, int bytes_sent, @@ -57,44 +57,42 @@ std::move(callback)))); } -void SerialIoHandlerImpl::CancelRead(mojom::SerialReceiveError reason) { +void SerialPortImpl::CancelRead(mojom::SerialReceiveError reason) { io_handler_->CancelRead(reason); } -void SerialIoHandlerImpl::CancelWrite(mojom::SerialSendError reason) { +void SerialPortImpl::CancelWrite(mojom::SerialSendError reason) { io_handler_->CancelWrite(reason); } -void SerialIoHandlerImpl::Flush(FlushCallback callback) { +void SerialPortImpl::Flush(FlushCallback callback) { std::move(callback).Run(io_handler_->Flush()); } -void SerialIoHandlerImpl::GetControlSignals( - GetControlSignalsCallback callback) { +void SerialPortImpl::GetControlSignals(GetControlSignalsCallback callback) { std::move(callback).Run(io_handler_->GetControlSignals()); } -void SerialIoHandlerImpl::SetControlSignals( +void SerialPortImpl::SetControlSignals( mojom::SerialHostControlSignalsPtr signals, SetControlSignalsCallback callback) { std::move(callback).Run(io_handler_->SetControlSignals(*signals)); } -void SerialIoHandlerImpl::ConfigurePort( - mojom::SerialConnectionOptionsPtr options, - ConfigurePortCallback callback) { +void SerialPortImpl::ConfigurePort(mojom::SerialConnectionOptionsPtr options, + ConfigurePortCallback callback) { std::move(callback).Run(io_handler_->ConfigurePort(*options)); } -void SerialIoHandlerImpl::GetPortInfo(GetPortInfoCallback callback) { +void SerialPortImpl::GetPortInfo(GetPortInfoCallback callback) { std::move(callback).Run(io_handler_->GetPortInfo()); } -void SerialIoHandlerImpl::SetBreak(SetBreakCallback callback) { +void SerialPortImpl::SetBreak(SetBreakCallback callback) { std::move(callback).Run(io_handler_->SetBreak()); } -void SerialIoHandlerImpl::ClearBreak(ClearBreakCallback callback) { +void SerialPortImpl::ClearBreak(ClearBreakCallback callback) { std::move(callback).Run(io_handler_->ClearBreak()); }
diff --git a/services/device/serial/serial_io_handler_impl.h b/services/device/serial/serial_port_impl.h similarity index 80% rename from services/device/serial/serial_io_handler_impl.h rename to services/device/serial/serial_port_impl.h index c8b7aca..c73d036 100644 --- a/services/device/serial/serial_io_handler_impl.h +++ b/services/device/serial/serial_port_impl.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SERVICES_DEVICE_SERIAL_SERIAL_IO_HANDLER_IMPL_H_ -#define SERVICES_DEVICE_SERIAL_SERIAL_IO_HANDLER_IMPL_H_ +#ifndef SERVICES_DEVICE_SERIAL_SERIAL_PORT_IMPL_H_ +#define SERVICES_DEVICE_SERIAL_SERIAL_PORT_IMPL_H_ #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -20,18 +20,18 @@ // SerialIoHandler is exposed only via the Device Service. // crbug.com/748505 // This class must be constructed and run on IO thread. -class SerialIoHandlerImpl : public mojom::SerialIoHandler { +class SerialPortImpl : public mojom::SerialPort { public: static void Create( - mojom::SerialIoHandlerRequest request, + mojom::SerialPortRequest request, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner); - explicit SerialIoHandlerImpl( + explicit SerialPortImpl( scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner); - ~SerialIoHandlerImpl() override; + ~SerialPortImpl() override; private: - // mojom::SerialIoHandler methods: + // mojom::SerialPort methods: void Open(const std::string& port, mojom::SerialConnectionOptionsPtr options, OpenCallback callback) override; @@ -51,9 +51,9 @@ scoped_refptr<device::SerialIoHandler> io_handler_; - DISALLOW_COPY_AND_ASSIGN(SerialIoHandlerImpl); + DISALLOW_COPY_AND_ASSIGN(SerialPortImpl); }; } // namespace device -#endif // SERVICES_DEVICE_SERIAL_SERIAL_IO_HANDLER_IMPL_H_ +#endif // SERVICES_DEVICE_SERIAL_SERIAL_PORT_IMPL_H_
diff --git a/services/device/serial/serial_io_handler_impl_unittest.cc b/services/device/serial/serial_port_impl_unittest.cc similarity index 63% rename from services/device/serial/serial_io_handler_impl_unittest.cc rename to services/device/serial/serial_port_impl_unittest.cc index d492526..40a7c418 100644 --- a/services/device/serial/serial_io_handler_impl_unittest.cc +++ b/services/device/serial/serial_port_impl_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 "services/device/serial/serial_io_handler_impl.h" +#include "services/device/serial/serial_port_impl.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/interface_ptr.h" @@ -14,21 +14,20 @@ namespace { -class SerialIoHandlerImplTest : public DeviceServiceTestBase { +class SerialPortImplTest : public DeviceServiceTestBase { public: - SerialIoHandlerImplTest() = default; - ~SerialIoHandlerImplTest() override = default; + SerialPortImplTest() = default; + ~SerialPortImplTest() override = default; private: - DISALLOW_COPY_AND_ASSIGN(SerialIoHandlerImplTest); + DISALLOW_COPY_AND_ASSIGN(SerialPortImplTest); }; // This is to simply test that on Linux/Mac/Windows a client can connect to -// Device Service and bind the serial SerialIoHandler interface -// correctly. +// Device Service and bind the serial SerialPort interface correctly. // TODO(leonhsl): figure out how to add more robust tests. -TEST_F(SerialIoHandlerImplTest, SimpleConnectTest) { - mojom::SerialIoHandlerPtr io_handler; +TEST_F(SerialPortImplTest, SimpleConnectTest) { + mojom::SerialPortPtr io_handler; connector()->BindInterface(mojom::kServiceName, &io_handler); io_handler.FlushForTesting(); }
diff --git a/services/device/serial/serial_device_enumerator_impl.cc b/services/device/serial/serial_port_manager_impl.cc similarity index 60% rename from services/device/serial/serial_device_enumerator_impl.cc rename to services/device/serial/serial_port_manager_impl.cc index 5a4b37b..55a5338af 100644 --- a/services/device/serial/serial_device_enumerator_impl.cc +++ b/services/device/serial/serial_port_manager_impl.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/device/serial/serial_device_enumerator_impl.h" +#include "services/device/serial/serial_port_manager_impl.h" #include "base/sequenced_task_runner.h" #include "base/task/post_task.h" @@ -12,18 +12,16 @@ namespace { -void CreateAndBindOnBlockableRunner( - mojom::SerialDeviceEnumeratorRequest request) { - mojo::MakeStrongBinding(std::make_unique<SerialDeviceEnumeratorImpl>(), +void CreateAndBindOnBlockableRunner(mojom::SerialPortManagerRequest request) { + mojo::MakeStrongBinding(std::make_unique<SerialPortManagerImpl>(), std::move(request)); } } // namespace // static -void SerialDeviceEnumeratorImpl::Create( - mojom::SerialDeviceEnumeratorRequest request) { - // SerialDeviceEnumeratorImpl must live on a thread that is allowed to do +void SerialPortManagerImpl::Create(mojom::SerialPortManagerRequest request) { + // SerialPortManagerImpl must live on a thread that is allowed to do // blocking IO. scoped_refptr<base::SequencedTaskRunner> blockable_sequence_runner = base::CreateSequencedTaskRunnerWithTraits( @@ -33,12 +31,12 @@ base::BindOnce(&CreateAndBindOnBlockableRunner, std::move(request))); } -SerialDeviceEnumeratorImpl::SerialDeviceEnumeratorImpl() +SerialPortManagerImpl::SerialPortManagerImpl() : enumerator_(device::SerialDeviceEnumerator::Create()) {} -SerialDeviceEnumeratorImpl::~SerialDeviceEnumeratorImpl() = default; +SerialPortManagerImpl::~SerialPortManagerImpl() = default; -void SerialDeviceEnumeratorImpl::GetDevices(GetDevicesCallback callback) { +void SerialPortManagerImpl::GetDevices(GetDevicesCallback callback) { DCHECK(enumerator_); std::move(callback).Run(enumerator_->GetDevices()); }
diff --git a/services/device/serial/serial_port_manager_impl.h b/services/device/serial/serial_port_manager_impl.h new file mode 100644 index 0000000..f99b8d4 --- /dev/null +++ b/services/device/serial/serial_port_manager_impl.h
@@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_DEVICE_SERIAL_SERIAL_PORT_MANAGER_IMPL_H_ +#define SERVICES_DEVICE_SERIAL_SERIAL_PORT_MANAGER_IMPL_H_ + +#include <memory> + +#include "base/macros.h" +#include "device/serial/serial_device_enumerator.h" +#include "services/device/public/mojom/serial.mojom.h" + +namespace device { + +// TODO(leonhsl): Merge this class with SerialDeviceEnumerator if/once +// SerialDeviceEnumerator is exposed only via the Device Service. +// crbug.com/748505 +class SerialPortManagerImpl : public mojom::SerialPortManager { + public: + static void Create(mojom::SerialPortManagerRequest request); + + SerialPortManagerImpl(); + ~SerialPortManagerImpl() override; + + private: + // mojom::SerialPortManager methods: + void GetDevices(GetDevicesCallback callback) override; + + std::unique_ptr<device::SerialDeviceEnumerator> enumerator_; + + DISALLOW_COPY_AND_ASSIGN(SerialPortManagerImpl); +}; + +} // namespace device + +#endif // SERVICES_DEVICE_SERIAL_SERIAL_PORT_MANAGER_IMPL_H_
diff --git a/services/device/serial/serial_device_enumerator_impl_unittest.cc b/services/device/serial/serial_port_manager_impl_unittest.cc similarity index 70% rename from services/device/serial/serial_device_enumerator_impl_unittest.cc rename to services/device/serial/serial_port_manager_impl_unittest.cc index b4bbacf..68459cef 100644 --- a/services/device/serial/serial_device_enumerator_impl_unittest.cc +++ b/services/device/serial/serial_port_manager_impl_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 "services/device/serial/serial_device_enumerator_impl.h" +#include "services/device/serial/serial_port_manager_impl.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/interface_ptr.h" @@ -14,10 +14,10 @@ namespace { -class SerialDeviceEnumeratorImplTest : public DeviceServiceTestBase { +class SerialPortManagerImplTest : public DeviceServiceTestBase { public: - SerialDeviceEnumeratorImplTest() = default; - ~SerialDeviceEnumeratorImplTest() override = default; + SerialPortManagerImplTest() = default; + ~SerialPortManagerImplTest() override = default; protected: void SetUp() override { @@ -27,16 +27,16 @@ void TearDown() override { enumerator_.reset(); } - mojom::SerialDeviceEnumeratorPtr enumerator_; + mojom::SerialPortManagerPtr enumerator_; - DISALLOW_COPY_AND_ASSIGN(SerialDeviceEnumeratorImplTest); + DISALLOW_COPY_AND_ASSIGN(SerialPortManagerImplTest); }; // This is to simply test that on Linux/Mac/Windows a client can connect to // Device Service and bind the serial SerialDeviceEnumerator interface // correctly. // TODO(leonhsl): figure out how to add more robust tests. -TEST_F(SerialDeviceEnumeratorImplTest, SimpleConnectTest) { +TEST_F(SerialPortManagerImplTest, SimpleConnectTest) { enumerator_.FlushForTesting(); }
diff --git a/services/identity/public/cpp/identity_manager.cc b/services/identity/public/cpp/identity_manager.cc index b7dfa452..5783eaf 100644 --- a/services/identity/public/cpp/identity_manager.cc +++ b/services/identity/public/cpp/identity_manager.cc
@@ -124,6 +124,51 @@ return HasAccountWithRefreshToken(GetPrimaryAccountId()); } +base::Optional<AccountInfo> +IdentityManager::FindAccountInfoForAccountWithRefreshTokenByAccountId( + const std::string& account_id) const { + AccountInfo account_info = + account_tracker_service_->GetAccountInfo(account_id); + + // AccountTrackerService always returns an AccountInfo, even on failure. In + // case of failure, the AccountInfo will be unpopulated, thus we should not + // be able to find a valid refresh token. + if (!HasAccountWithRefreshToken(account_info.account_id)) + return base::nullopt; + + return GetAccountInfoForAccountWithRefreshToken(account_info.account_id); +} + +base::Optional<AccountInfo> +IdentityManager::FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + const std::string& email_address) const { + AccountInfo account_info = + account_tracker_service_->FindAccountInfoByEmail(email_address); + + // AccountTrackerService always returns an AccountInfo, even on failure. In + // case of failure, the AccountInfo will be unpopulated, thus we should not + // be able to find a valid refresh token. + if (!HasAccountWithRefreshToken(account_info.account_id)) + return base::nullopt; + + return GetAccountInfoForAccountWithRefreshToken(account_info.account_id); +} + +base::Optional<AccountInfo> +IdentityManager::FindAccountInfoForAccountWithRefreshTokenByGaiaId( + const std::string& gaia_id) const { + AccountInfo account_info = + account_tracker_service_->FindAccountInfoByGaiaId(gaia_id); + + // AccountTrackerService always returns an AccountInfo, even on failure. In + // case of failure, the AccountInfo will be unpopulated, thus we should not + // be able to find a valid refresh token. + if (!HasAccountWithRefreshToken(account_info.account_id)) + return base::nullopt; + + return GetAccountInfoForAccountWithRefreshToken(account_info.account_id); +} + std::unique_ptr<AccessTokenFetcher> IdentityManager::CreateAccessTokenFetcherForAccount( const std::string& account_id,
diff --git a/services/identity/public/cpp/identity_manager.h b/services/identity/public/cpp/identity_manager.h index 421819d..b36603aa 100644 --- a/services/identity/public/cpp/identity_manager.h +++ b/services/identity/public/cpp/identity_manager.h
@@ -219,6 +219,29 @@ // exists for the primary account. bool HasPrimaryAccountWithRefreshToken() const; + // Looks up and returns information for account with given |account_id|. If + // the account cannot be found, return an empty optional. This is equivalent + // to searching on the vector returned by GetAccountsWithRefreshTokens() but + // without allocating memory for the vector. + base::Optional<AccountInfo> + FindAccountInfoForAccountWithRefreshTokenByAccountId( + const std::string& account_id) const; + + // Looks up and returns information for account with given |email_address|. If + // the account cannot be found, return an empty optional. This is equivalent + // to searching on the vector returned by GetAccountsWithRefreshTokens() but + // without allocating memory for the vector. + base::Optional<AccountInfo> + FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + const std::string& email_address) const; + + // Looks up and returns information for account with given |gaia_id|. If the + // account cannot be found, return an empty optional. This is equivalent to + // searching on the vector returned by GetAccountsWithRefreshTokens() but + // without allocating memory for the vector. + base::Optional<AccountInfo> FindAccountInfoForAccountWithRefreshTokenByGaiaId( + const std::string& gaia_id) const; + // Creates an AccessTokenFetcher given the passed-in information. std::unique_ptr<AccessTokenFetcher> CreateAccessTokenFetcherForAccount( const std::string& account_id,
diff --git a/services/identity/public/cpp/identity_manager_unittest.cc b/services/identity/public/cpp/identity_manager_unittest.cc index e929bfb..ddd45e8a 100644 --- a/services/identity/public/cpp/identity_manager_unittest.cc +++ b/services/identity/public/cpp/identity_manager_unittest.cc
@@ -1774,4 +1774,80 @@ EXPECT_TRUE(mutator); } +// Checks that FindAccountInfoForAccountWithRefreshTokenByAccountId() returns +// information about the account if the account is found or nullopt if there +// are no accounts with requested |account_id|. +TEST_F(IdentityManagerTest, + FindAccountInfoForAccountWithRefreshTokenByAccountId) { + // Add an account (note: cannot use kTestEmail as it is already inserted + // by the fixture common code, so use a different address). + const AccountInfo foo_account_info = + MakeAccountAvailable(identity_manager(), "foo@bar.com"); + + base::Optional<AccountInfo> maybe_account_info; + maybe_account_info = + identity_manager()->FindAccountInfoForAccountWithRefreshTokenByAccountId( + "dummy_value"); + EXPECT_FALSE(maybe_account_info.has_value()); + + maybe_account_info = + identity_manager()->FindAccountInfoForAccountWithRefreshTokenByAccountId( + foo_account_info.account_id); + EXPECT_TRUE(maybe_account_info.has_value()); + EXPECT_EQ(foo_account_info.account_id, maybe_account_info.value().account_id); + EXPECT_EQ(foo_account_info.email, maybe_account_info.value().email); + EXPECT_EQ(foo_account_info.gaia, maybe_account_info.value().gaia); +} + +// Checks that FindAccountInfoForAccountWithRefreshTokenByEmailAddress() returns +// information about the account if the account is found or nullopt if there +// are no accounts with requested |email_address|. +TEST_F(IdentityManagerTest, + FindAccountInfoForAccountWithRefreshTokenByEmailAddress) { + // Add an account (note: cannot use kTestEmail as it is already inserted + // by the fixture common code, so use a different address). + const AccountInfo foo_account_info = + MakeAccountAvailable(identity_manager(), "foo@bar.com"); + + base::Optional<AccountInfo> maybe_account_info; + maybe_account_info = + identity_manager() + ->FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + "dummy_value"); + EXPECT_FALSE(maybe_account_info.has_value()); + + maybe_account_info = + identity_manager() + ->FindAccountInfoForAccountWithRefreshTokenByEmailAddress( + foo_account_info.email); + EXPECT_TRUE(maybe_account_info.has_value()); + EXPECT_EQ(foo_account_info.account_id, maybe_account_info.value().account_id); + EXPECT_EQ(foo_account_info.email, maybe_account_info.value().email); + EXPECT_EQ(foo_account_info.gaia, maybe_account_info.value().gaia); +} + +// Checks that FindAccountInfoForAccountWithRefreshTokenByGaiaId() returns +// information about the account if the account is found or nullopt if there +// are no accounts with requested |gaia_id|. +TEST_F(IdentityManagerTest, FindAccountInfoForAccountWithRefreshTokenByGaiaId) { + // Add an account (note: cannot use kTestEmail as it is already inserted + // by the fixture common code, so use a different address). + const AccountInfo foo_account_info = + MakeAccountAvailable(identity_manager(), "foo@bar.com"); + + base::Optional<AccountInfo> maybe_account_info; + maybe_account_info = + identity_manager()->FindAccountInfoForAccountWithRefreshTokenByGaiaId( + "dummy_value"); + EXPECT_FALSE(maybe_account_info.has_value()); + + maybe_account_info = + identity_manager()->FindAccountInfoForAccountWithRefreshTokenByGaiaId( + foo_account_info.gaia); + EXPECT_TRUE(maybe_account_info.has_value()); + EXPECT_EQ(foo_account_info.account_id, maybe_account_info.value().account_id); + EXPECT_EQ(foo_account_info.email, maybe_account_info.value().email); + EXPECT_EQ(foo_account_info.gaia, maybe_account_info.value().gaia); +} + } // namespace identity
diff --git a/services/identity/public/cpp/primary_account_mutator_unittest.cc b/services/identity/public/cpp/primary_account_mutator_unittest.cc index 715901a..58cedb0 100644 --- a/services/identity/public/cpp/primary_account_mutator_unittest.cc +++ b/services/identity/public/cpp/primary_account_mutator_unittest.cc
@@ -6,6 +6,7 @@ #include "base/containers/flat_set.h" #include "base/run_loop.h" +#include "base/scoped_observer.h" #include "base/test/scoped_task_environment.h" #include "components/signin/core/browser/signin_metrics.h" #include "services/identity/public/cpp/identity_test_environment.h" @@ -13,305 +14,339 @@ #include "testing/platform_test.h" namespace { + +// Constants used by the different tests. const char kUnknownAccountId[] = "{unknown account id}"; const char kPrimaryAccountEmail[] = "primary.account@example.com"; const char kAnotherAccountEmail[] = "another.account@example.com"; const char kRefreshToken[] = "refresh_token"; const char kPassword[] = "password"; -} // namespace -class TestIdentityManagerObserver : public identity::IdentityManager::Observer { +// All account consistency methods that are tested by those unit tests when +// testing ClearPrimaryAccount method. +const signin::AccountConsistencyMethod kTestedAccountConsistencyMethods[] = { + signin::AccountConsistencyMethod::kDisabled, + signin::AccountConsistencyMethod::kMirror, + signin::AccountConsistencyMethod::kDiceMigration, + signin::AccountConsistencyMethod::kDice, +}; + +// See RunClearPrimaryAccountTest(). +enum class AuthExpectation { kAuthNormal, kAuthError }; +enum class RemoveAccountExpectation { kKeepAll, kRemovePrimary, kRemoveAll }; + +// This callback will be invoked every time the IdentityManager::Observer +// method OnPrimaryAccountCleared is invoked. The parameter will be a +// reference to the still valid primary account that was cleared. +using PrimaryAccountClearedCallback = + base::RepeatingCallback<void(const AccountInfo&)>; + +// This callback will be invoked every time the IdentityManager::Observer +// method OnPrimaryAccountSigninFailed is invoked. The parameter will be +// a reference to the authentication error. +using PrimaryAccountSigninFailedCallback = + base::RepeatingCallback<void(const GoogleServiceAuthError&)>; + +// This callback will be invoked every time the IdentityManager::Observer +// method OnRefreshTokenRemoved is invoked. The parameter will be a reference +// to the account_id whose token was removed. +using RefreshTokenRemovedCallback = + base::RepeatingCallback<void(const std::string&)>; + +// Helper IdentityManager::Observer that forwards some events to the +// callback passed to the constructor. +class ClearPrimaryAccountTestObserver + : public identity::IdentityManager::Observer { public: - explicit TestIdentityManagerObserver( - identity::IdentityManager* identity_manager) - : identity_manager_(identity_manager) { - identity_manager_->AddObserver(this); - } - ~TestIdentityManagerObserver() override { - identity_manager_->RemoveObserver(this); + ClearPrimaryAccountTestObserver( + identity::IdentityManager* identity_manager, + PrimaryAccountClearedCallback on_primary_account_cleared, + PrimaryAccountSigninFailedCallback on_primary_account_signin_failed, + RefreshTokenRemovedCallback on_refresh_token_removed) + : on_primary_account_cleared_(std::move(on_primary_account_cleared)), + on_primary_account_signin_failed_( + std::move(on_primary_account_signin_failed)), + on_refresh_token_removed_(std::move(on_refresh_token_removed)), + scoped_observer_(this) { + DCHECK(on_primary_account_cleared_); + DCHECK(on_primary_account_signin_failed_); + DCHECK(on_refresh_token_removed_); + scoped_observer_.Add(identity_manager); } - void set_on_primary_account_cleared_callback(base::OnceClosure callback) { - on_primary_account_cleared_callback_ = std::move(callback); - } - - void set_on_primary_account_signin_failed_callback( - base::OnceClosure callback) { - on_primary_account_signin_failed_callback_ = std::move(callback); - } - - // This method uses a RepeatingCallback to simplify verification of multiple - // removed tokens. - void set_on_refresh_token_removed_callback( - base::RepeatingCallback<void(const std::string&)> callback) { - on_refresh_token_removed_callback_ = std::move(callback); - } - - const GoogleServiceAuthError& error_from_signin_failed_callback() const { - return google_signin_failed_error_; - } - - private: // identity::IdentityManager::Observer implementation. - void OnPrimaryAccountCleared( - const AccountInfo& previous_primary_account_info) override { - primary_account_from_cleared_callback_ = previous_primary_account_info; - if (on_primary_account_cleared_callback_) - std::move(on_primary_account_cleared_callback_).Run(); + void OnPrimaryAccountCleared(const AccountInfo& account_info) override { + on_primary_account_cleared_.Run(account_info); } void OnPrimaryAccountSigninFailed( const GoogleServiceAuthError& error) override { - google_signin_failed_error_ = error; - if (on_primary_account_signin_failed_callback_) - std::move(on_primary_account_signin_failed_callback_).Run(); + on_primary_account_signin_failed_.Run(error); } void OnRefreshTokenRemovedForAccount(const std::string& account_id) override { - account_from_refresh_token_removed_callback_ = account_id; - if (on_refresh_token_removed_callback_) - on_refresh_token_removed_callback_.Run(account_id); - } - - identity::IdentityManager* identity_manager_; - base::OnceClosure on_primary_account_cleared_callback_; - base::OnceClosure on_primary_account_signin_failed_callback_; - base::RepeatingCallback<void(const std::string&)> - on_refresh_token_removed_callback_; - AccountInfo primary_account_from_cleared_callback_; - std::string account_from_refresh_token_removed_callback_; - GoogleServiceAuthError google_signin_failed_error_; -}; - -class PrimaryAccountMutatorTest : public PlatformTest { - public: - PrimaryAccountMutatorTest() { - RecreateIdentityTestEnvironment( - signin::AccountConsistencyMethod::kDisabled); - } - - identity::IdentityTestEnvironment* environment() { - return environment_.get(); - } - - identity::IdentityManager* identity_manager() { - return environment()->identity_manager(); - } - - TestIdentityManagerObserver* identity_manager_observer() { - return identity_manager_observer_.get(); - } - - identity::PrimaryAccountMutator* primary_account_mutator() { - return identity_manager()->GetPrimaryAccountMutator(); - } - - // Recreates the IdentityTestEnvironment with given |account_consistency| and - // optionally seeds with an authenticated account depending on - // |singin_manager_setup|. This process destroys any existing - // IdentityTestEnvironment and its dependencies, then remakes them. - void RecreateIdentityTestEnvironment( - signin::AccountConsistencyMethod account_consistency) { - identity_manager_observer_.reset(); - - environment_ = std::make_unique<identity::IdentityTestEnvironment>( - false, nullptr, account_consistency); - identity_manager_observer_ = - std::make_unique<TestIdentityManagerObserver>(identity_manager()); - } - - // See RunClearPrimaryAccountTest(). - enum class AuthExpectation { kAuthNormal, kAuthError }; - enum class RemoveAccountExpectation { kKeepAll, kRemovePrimary, kRemoveAll }; - - // Helper for testing of ClearPrimaryAccount(). This method requires lots - // of tests due to having different behaviors based on its arguments. But the - // setup and execution of these test is all the boiler plate you see here: - // 1) Ensure you have 2 accounts, both with refresh tokens - // 2) Clear the primary account - // 3) Assert clearing succeeds and refresh tokens are optionally removed based - // on arguments. - // - // Optionally, it's possible to specify whether a normal auth process will - // take place, or whether an auth error should happen, useful for some tests. - void RunClearPrimaryAccountTest( - identity::PrimaryAccountMutator::ClearAccountsAction account_action, - RemoveAccountExpectation account_expectation, - AuthExpectation auth_expection = AuthExpectation::kAuthNormal) { - // With the exception of ClearPrimaryAccount_AuthInProgress, every other - // ClearPrimaryAccount_* test requires a primary account to be signed in. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); - EXPECT_TRUE( - primary_account_mutator()->SetPrimaryAccount(account_info.account_id)); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); - EXPECT_TRUE(identity_manager()->HasPrimaryAccountWithRefreshToken()); - - EXPECT_EQ(identity_manager()->GetPrimaryAccountId(), - account_info.account_id); - EXPECT_EQ(identity_manager()->GetPrimaryAccountInfo().email, - kPrimaryAccountEmail); - - if (auth_expection == AuthExpectation::kAuthError) { - // Set primary account to have authentication error. - SetRefreshTokenForPrimaryAccount(identity_manager()); - identity::UpdatePersistentErrorOfRefreshTokenForAccount( - identity_manager(), account_info.account_id, - GoogleServiceAuthError( - GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS)); - } - - // Additionally, ClearPrimaryAccount_* tests also need a secondary account. - AccountInfo secondary_account_info = - MakeAccountAvailable(identity_manager(), kAnotherAccountEmail); - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( - secondary_account_info.account_id)); - - // Track Observer token removal notifications. - base::flat_set<std::string> observed_removals; - identity_manager_observer()->set_on_refresh_token_removed_callback( - base::BindRepeating( - [](base::flat_set<std::string>* observed_removals, - const std::string& removed_account) { - observed_removals->insert(removed_account); - }, - &observed_removals)); - - // Grab this before clearing for token checks below. - auto former_primary_account = identity_manager()->GetPrimaryAccountInfo(); - - base::RunLoop run_loop; - identity_manager_observer()->set_on_primary_account_cleared_callback( - run_loop.QuitClosure()); - primary_account_mutator()->ClearPrimaryAccount( - account_action, signin_metrics::SIGNOUT_TEST, - signin_metrics::SignoutDelete::IGNORE_METRIC); - run_loop.Run(); - - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - // NOTE: IdentityManager _may_ still possess this token (see switch below), - // but it is no longer considered part of the primary account. - EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken()); - - switch (account_expectation) { - case RemoveAccountExpectation::kKeepAll: - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( - former_primary_account.account_id)); - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( - secondary_account_info.account_id)); - EXPECT_TRUE(observed_removals.empty()); - break; - case RemoveAccountExpectation::kRemovePrimary: - EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken( - former_primary_account.account_id)); - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( - secondary_account_info.account_id)); - EXPECT_TRUE(base::ContainsKey(observed_removals, - former_primary_account.account_id)); - EXPECT_FALSE(base::ContainsKey(observed_removals, - secondary_account_info.account_id)); - break; - case RemoveAccountExpectation::kRemoveAll: - EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken( - former_primary_account.account_id)); - EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken( - secondary_account_info.account_id)); - EXPECT_TRUE(base::ContainsKey(observed_removals, - former_primary_account.account_id)); - EXPECT_TRUE(base::ContainsKey(observed_removals, - secondary_account_info.account_id)); - break; - } + on_refresh_token_removed_.Run(account_id); } private: - base::test::ScopedTaskEnvironment task_environment_; - std::unique_ptr<identity::IdentityTestEnvironment> environment_; - std::unique_ptr<TestIdentityManagerObserver> identity_manager_observer_; + PrimaryAccountClearedCallback on_primary_account_cleared_; + PrimaryAccountSigninFailedCallback on_primary_account_signin_failed_; + RefreshTokenRemovedCallback on_refresh_token_removed_; + ScopedObserver<identity::IdentityManager, identity::IdentityManager::Observer> + scoped_observer_; + + DISALLOW_COPY_AND_ASSIGN(ClearPrimaryAccountTestObserver); }; +// Helper for testing of ClearPrimaryAccount(). This function requires lots +// of tests due to having different behaviors based on its arguments. But the +// setup and execution of these test is all the boiler plate you see here: +// 1) Ensure you have 2 accounts, both with refresh tokens +// 2) Clear the primary account +// 3) Assert clearing succeeds and refresh tokens are optionally removed based +// on arguments. +// +// Optionally, it's possible to specify whether a normal auth process will +// take place, or whether an auth error should happen, useful for some tests. +void RunClearPrimaryAccountTest( + signin::AccountConsistencyMethod account_consistency_method, + identity::PrimaryAccountMutator::ClearAccountsAction account_action, + RemoveAccountExpectation account_expectation, + AuthExpectation auth_expection = AuthExpectation::kAuthNormal) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment( + /*use_fake_url_loader_for_gaia_cookie_manager=*/false, + /*pref_service=*/nullptr, account_consistency_method); + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + + // Abort the test if the current platform does not support mutation of the + // primary account (the returned PrimaryAccountMutator* will be null). + if (!primary_account_mutator) + return; + + // With the exception of ClearPrimaryAccount_AuthInProgress, every other + // ClearPrimaryAccount_* test requires a primary account to be signed in. + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + AccountInfo account_info = + environment.MakeAccountAvailable(kPrimaryAccountEmail); + EXPECT_TRUE( + primary_account_mutator->SetPrimaryAccount(account_info.account_id)); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); + EXPECT_TRUE(identity_manager->HasPrimaryAccountWithRefreshToken()); + + EXPECT_EQ(identity_manager->GetPrimaryAccountId(), account_info.account_id); + EXPECT_EQ(identity_manager->GetPrimaryAccountInfo().email, + kPrimaryAccountEmail); + + if (auth_expection == AuthExpectation::kAuthError) { + // Set primary account to have authentication error. + SetRefreshTokenForPrimaryAccount(identity_manager); + identity::UpdatePersistentErrorOfRefreshTokenForAccount( + identity_manager, account_info.account_id, + GoogleServiceAuthError( + GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS)); + } + + // Additionally, ClearPrimaryAccount_* tests also need a secondary account. + AccountInfo secondary_account_info = + environment.MakeAccountAvailable(kAnotherAccountEmail); + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( + secondary_account_info.account_id)); + + // Grab this before clearing for token checks below. + auto former_primary_account = identity_manager->GetPrimaryAccountInfo(); + + // Make sure we exit the run loop. + base::RunLoop run_loop; + PrimaryAccountClearedCallback primary_account_cleared_callback = + base::BindRepeating([](base::RepeatingClosure quit_closure, + const AccountInfo&) { quit_closure.Run(); }, + run_loop.QuitClosure()); + + // Authentication error should not occur. + PrimaryAccountSigninFailedCallback primary_account_signin_failed_callback = + base::BindRepeating([](const GoogleServiceAuthError&) { + FAIL() << "auth should not fail"; + }); + + // Track Observer token removal notification. + base::flat_set<std::string> observed_removals; + RefreshTokenRemovedCallback refresh_token_removed_callback = + base::BindRepeating( + [](base::flat_set<std::string>* observed_removals, + const std::string& removed_account) { + observed_removals->insert(removed_account); + }, + &observed_removals); + + ClearPrimaryAccountTestObserver scoped_observer( + identity_manager, primary_account_cleared_callback, + primary_account_signin_failed_callback, refresh_token_removed_callback); + + primary_account_mutator->ClearPrimaryAccount( + account_action, signin_metrics::SIGNOUT_TEST, + signin_metrics::SignoutDelete::IGNORE_METRIC); + run_loop.Run(); + + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + // NOTE: IdentityManager _may_ still possess this token (see switch below), + // but it is no longer considered part of the primary account. + EXPECT_FALSE(identity_manager->HasPrimaryAccountWithRefreshToken()); + + switch (account_expectation) { + case RemoveAccountExpectation::kKeepAll: + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( + former_primary_account.account_id)); + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( + secondary_account_info.account_id)); + EXPECT_TRUE(observed_removals.empty()); + break; + case RemoveAccountExpectation::kRemovePrimary: + EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken( + former_primary_account.account_id)); + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( + secondary_account_info.account_id)); + EXPECT_TRUE(base::ContainsKey(observed_removals, + former_primary_account.account_id)); + EXPECT_FALSE(base::ContainsKey(observed_removals, + secondary_account_info.account_id)); + break; + case RemoveAccountExpectation::kRemoveAll: + EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken( + former_primary_account.account_id)); + EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken( + secondary_account_info.account_id)); + EXPECT_TRUE(base::ContainsKey(observed_removals, + former_primary_account.account_id)); + EXPECT_TRUE(base::ContainsKey(observed_removals, + secondary_account_info.account_id)); + break; + } +} + +} // namespace + +using PrimaryAccountMutatorTest = PlatformTest; + // Checks that the method to control whether setting the primary account is // working correctly and that the setting is respected by SetPrimaryAccount(). TEST_F(PrimaryAccountMutatorTest, SetSettingPrimaryAccountAllowed) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; - primary_account_mutator()->SetSettingPrimaryAccountAllowed(false); - EXPECT_FALSE(primary_account_mutator()->IsSettingPrimaryAccountAllowed()); + primary_account_mutator->SetSettingPrimaryAccountAllowed(false); + EXPECT_FALSE(primary_account_mutator->IsSettingPrimaryAccountAllowed()); - primary_account_mutator()->SetSettingPrimaryAccountAllowed(true); - EXPECT_TRUE(primary_account_mutator()->IsSettingPrimaryAccountAllowed()); + primary_account_mutator->SetSettingPrimaryAccountAllowed(true); + EXPECT_TRUE(primary_account_mutator->IsSettingPrimaryAccountAllowed()); } // Checks that setting the primary account works. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); + EXPECT_FALSE(environment.identity_manager()->HasPrimaryAccount()); EXPECT_TRUE( - primary_account_mutator()->SetPrimaryAccount(account_info.account_id)); + primary_account_mutator->SetPrimaryAccount(account_info.account_id)); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); - EXPECT_EQ(identity_manager()->GetPrimaryAccountId(), account_info.account_id); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); + EXPECT_EQ(identity_manager->GetPrimaryAccountId(), account_info.account_id); } // Checks that setting the primary account fails if the account is not known by // the identity service. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_NoAccount) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(primary_account_mutator()->SetPrimaryAccount(kUnknownAccountId)); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->SetPrimaryAccount(kUnknownAccountId)); } // Checks that setting the primary account fails if the account is unknown. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_UnknownAccount) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(primary_account_mutator()->SetPrimaryAccount(kUnknownAccountId)); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->SetPrimaryAccount(kUnknownAccountId)); } // Checks that trying to set the primary account fails when there is already a // primary account. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_AlreadyHasPrimaryAccount) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; AccountInfo primary_account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); AccountInfo another_account_info = - environment()->MakeAccountAvailable(kAnotherAccountEmail); + environment.MakeAccountAvailable(kAnotherAccountEmail); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_TRUE(primary_account_mutator()->SetPrimaryAccount( + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_TRUE(primary_account_mutator->SetPrimaryAccount( primary_account_info.account_id)); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(primary_account_mutator()->SetPrimaryAccount( + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->SetPrimaryAccount( another_account_info.account_id)); - EXPECT_EQ(identity_manager()->GetPrimaryAccountId(), + EXPECT_EQ(identity_manager->GetPrimaryAccountId(), primary_account_info.account_id); } @@ -319,69 +354,92 @@ // account is not allowed. TEST_F(PrimaryAccountMutatorTest, SetPrimaryAccount_SettingPrimaryAccountForbidden) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; AccountInfo primary_account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); - primary_account_mutator()->SetSettingPrimaryAccountAllowed(false); - EXPECT_FALSE(primary_account_mutator()->IsSettingPrimaryAccountAllowed()); + primary_account_mutator->SetSettingPrimaryAccountAllowed(false); + EXPECT_FALSE(primary_account_mutator->IsSettingPrimaryAccountAllowed()); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(primary_account_mutator()->SetPrimaryAccount( + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->SetPrimaryAccount( primary_account_info.account_id)); } TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_NotSignedIn) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; // Trying to signout an account that hasn't signed in first should fail. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(primary_account_mutator()->ClearPrimaryAccount( + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->ClearPrimaryAccount( identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); // Adding an account without signing in should yield similar a result. AccountInfo primary_account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(primary_account_mutator()->ClearPrimaryAccount( + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->ClearPrimaryAccount( identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); } TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default) { - if (!primary_account_mutator()) + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + + // Abort the test if the current platform does not support mutation of the + // primary account (the returned PrimaryAccountMutator* will be null). + if (!primary_account_mutator) return; // This test requires two accounts to be made available. AccountInfo primary_account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); AccountInfo other_account_info = - environment()->MakeAccountAvailable(kAnotherAccountEmail); + environment.MakeAccountAvailable(kAnotherAccountEmail); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( primary_account_info.account_id)); - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( other_account_info.account_id)); // Sign in the primary account to check ClearPrimaryAccount() later on. - primary_account_mutator()->SetPrimaryAccount(primary_account_info.account_id); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); - EXPECT_EQ(identity_manager()->GetPrimaryAccountId(), + primary_account_mutator->SetPrimaryAccount(primary_account_info.account_id); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); + EXPECT_EQ(identity_manager->GetPrimaryAccountId(), primary_account_info.account_id); - EXPECT_TRUE(primary_account_mutator()->ClearPrimaryAccount( + EXPECT_TRUE(primary_account_mutator->ClearPrimaryAccount( identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); @@ -389,29 +447,35 @@ // The underlying SigninManager in IdentityTestEnvironment (FakeSigninManager) // will be created with signin::AccountConsistencyMethod::kDisabled, which // should result in ClearPrimaryAccount() removing all the tokens. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken( + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken( primary_account_info.account_id)); - EXPECT_FALSE(identity_manager()->HasAccountWithRefreshToken( + EXPECT_FALSE(identity_manager->HasAccountWithRefreshToken( other_account_info.account_id)); } +// Test that ClearPrimaryAccount(...) with ClearAccountTokensAction::kKeepAll +// keep all tokens, independently of the account consistency method. TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_KeepAll) { - if (!primary_account_mutator()) - return; - - RunClearPrimaryAccountTest( - identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, - RemoveAccountExpectation::kKeepAll); + for (signin::AccountConsistencyMethod account_consistency_method : + kTestedAccountConsistencyMethods) { + RunClearPrimaryAccountTest( + account_consistency_method, + identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, + RemoveAccountExpectation::kKeepAll); + } } +// Test that ClearPrimaryAccount(...) with ClearAccountTokensAction::kRemoveAll +// remove all tokens, independently of the account consistency method. TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_RemoveAll) { - if (!primary_account_mutator()) - return; - - RunClearPrimaryAccountTest( - identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, - RemoveAccountExpectation::kRemoveAll); + for (signin::AccountConsistencyMethod account_consistency_method : + kTestedAccountConsistencyMethods) { + RunClearPrimaryAccountTest( + account_consistency_method, + identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, + RemoveAccountExpectation::kRemoveAll); + } } // Test that ClearPrimaryAccount(...) with ClearAccountTokensAction::kDefault @@ -419,13 +483,8 @@ // tokens. TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default_DisabledConsistency) { - if (!primary_account_mutator()) - return; - - // Tests default to kDisabled, so this is just being explicit. - RecreateIdentityTestEnvironment(signin::AccountConsistencyMethod::kDisabled); - RunClearPrimaryAccountTest( + signin::AccountConsistencyMethod::kDisabled, identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kRemoveAll); } @@ -435,12 +494,8 @@ // tokens. TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default_MirrorConsistency) { - if (!primary_account_mutator()) - return; - - RecreateIdentityTestEnvironment(signin::AccountConsistencyMethod::kMirror); - RunClearPrimaryAccountTest( + signin::AccountConsistencyMethod::kMirror, identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kRemoveAll); } @@ -449,12 +504,8 @@ // and AccountConsistencyMethod::kDice keeps all accounts when the the primary // account does not have an authentication error (see *_AuthError test). TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default_DiceConsistency) { - if (!primary_account_mutator()) - return; - - RecreateIdentityTestEnvironment(signin::AccountConsistencyMethod::kDice); - RunClearPrimaryAccountTest( + signin::AccountConsistencyMethod::kDice, identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kKeepAll); } @@ -464,12 +515,8 @@ // due to it authentication error. TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_Default_DiceConsistency_AuthError) { - if (!primary_account_mutator()) - return; - - RecreateIdentityTestEnvironment(signin::AccountConsistencyMethod::kDice); - RunClearPrimaryAccountTest( + signin::AccountConsistencyMethod::kDice, identity::PrimaryAccountMutator::ClearAccountsAction::kDefault, RemoveAccountExpectation::kRemovePrimary, AuthExpectation::kAuthError); } @@ -477,32 +524,40 @@ // Test that ClearPrimaryAccount(...) with authentication in progress notifies // Observers that sign-in is canceled and does not remove any tokens. TEST_F(PrimaryAccountMutatorTest, ClearPrimaryAccount_AuthInProgress) { - if (!primary_account_mutator()) + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + + // Abort the test if the current platform does not support mutation of the + // primary account (the returned PrimaryAccountMutator* will be null). + if (!primary_account_mutator) return; AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); EXPECT_TRUE( - identity_manager()->HasAccountWithRefreshToken(account_info.account_id)); + identity_manager->HasAccountWithRefreshToken(account_info.account_id)); // Account available in the tracker service but still not authenticated means // there's neither a primary account nor an authentication process ongoing. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); // Add a secondary account to verify that its refresh token survives the // call to ClearPrimaryAccount(...) below. AccountInfo secondary_account_info = - MakeAccountAvailable(identity_manager(), kAnotherAccountEmail); - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( + MakeAccountAvailable(identity_manager, kAnotherAccountEmail); + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( secondary_account_info.account_id)); // Start a signin process for the account we just made available and check // that it's reported to be in progress before the process is completed. base::RunLoop run_loop; std::string signed_account_refresh_token; - primary_account_mutator()->LegacyStartSigninWithRefreshTokenForPrimaryAccount( + primary_account_mutator->LegacyStartSigninWithRefreshTokenForPrimaryAccount( kRefreshToken, account_info.gaia, account_info.email, kPassword, base::BindOnce( [](std::string* out_refresh_token, const std::string& refresh_token) { @@ -510,91 +565,111 @@ }, base::Unretained(&signed_account_refresh_token))); - EXPECT_TRUE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_TRUE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); AccountInfo auth_in_progress_account_info = - primary_account_mutator()->LegacyPrimaryAccountForAuthInProgress(); - - // Make sure we exit the nested RunLoop. - identity_manager_observer()->set_on_primary_account_signin_failed_callback( - run_loop.QuitClosure()); - - // Observer should not be notified of any token removals. - identity_manager_observer()->set_on_refresh_token_removed_callback( - base::BindRepeating([](const std::string&) { EXPECT_TRUE(false); })); + primary_account_mutator->LegacyPrimaryAccountForAuthInProgress(); // No primary account to "clear", so no callback. - identity_manager_observer()->set_on_primary_account_cleared_callback( - base::BindOnce([] { EXPECT_TRUE(false); })); + PrimaryAccountClearedCallback primary_account_cleared_callback = + base::BindRepeating([](const AccountInfo&) { + FAIL() << "no primary account is set, so nothing should be cleared"; + }); - EXPECT_TRUE(primary_account_mutator()->ClearPrimaryAccount( + // Capture the authentication error and make sure we exit the run loop. + GoogleServiceAuthError captured_auth_error; + PrimaryAccountSigninFailedCallback primary_account_signin_failed_callback = + base::BindRepeating( + [](base::RepeatingClosure quit_closure, + GoogleServiceAuthError* out_auth_error, + const GoogleServiceAuthError& auth_error) { + *out_auth_error = auth_error; + quit_closure.Run(); + }, + run_loop.QuitClosure(), &captured_auth_error); + + // Observer should not be notified of any token removals. + RefreshTokenRemovedCallback refresh_token_removed_callback = + base::BindRepeating([](const std::string& removed_account) { + FAIL() << "no token removal should happen"; + }); + + ClearPrimaryAccountTestObserver scoped_observer( + identity_manager, primary_account_cleared_callback, + primary_account_signin_failed_callback, refresh_token_removed_callback); + + EXPECT_TRUE(primary_account_mutator->ClearPrimaryAccount( identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); run_loop.Run(); // Verify in-progress authentication was canceled. - EXPECT_EQ( - identity_manager_observer()->error_from_signin_failed_callback().state(), - GoogleServiceAuthError::State::REQUEST_CANCELED); - EXPECT_FALSE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_EQ(captured_auth_error.state(), + GoogleServiceAuthError::State::REQUEST_CANCELED); + EXPECT_FALSE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); // We didn't have a primary account to start with, we shouldn't have one now // either. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(identity_manager->HasPrimaryAccountWithRefreshToken()); // Secondary account token still exists. - EXPECT_TRUE(identity_manager()->HasAccountWithRefreshToken( + EXPECT_TRUE(identity_manager->HasAccountWithRefreshToken( secondary_account_info.account_id)); } // Checks that checking whether an authentication process is in progress reports // true before starting and after successfully completing the signin process. TEST_F(PrimaryAccountMutatorTest, SigninWithRefreshToken) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; // We'll sign in the same account twice, using SetPrimaryAccount() and // LegacyStartSigninWithRefreshTokenForPrimaryAccount(), and check that // in both cases the end result is the same. AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); EXPECT_TRUE( - primary_account_mutator()->SetPrimaryAccount(account_info.account_id)); + primary_account_mutator->SetPrimaryAccount(account_info.account_id)); const std::string primary_account_id_1 = - identity_manager()->GetPrimaryAccountId(); + identity_manager->GetPrimaryAccountId(); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); EXPECT_FALSE(primary_account_id_1.empty()); EXPECT_EQ(primary_account_id_1, account_info.account_id); EXPECT_TRUE( - identity_manager()->HasAccountWithRefreshToken(primary_account_id_1)); - EXPECT_FALSE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + identity_manager->HasAccountWithRefreshToken(primary_account_id_1)); + EXPECT_FALSE(identity_manager->GetPrimaryAccountInfo().email.empty()); // Sign out the account to try to sign in again with the other mechanism, but // using kKeepAll so we can use the same account we made available before. - EXPECT_TRUE(primary_account_mutator()->ClearPrimaryAccount( + EXPECT_TRUE(primary_account_mutator->ClearPrimaryAccount( identity::PrimaryAccountMutator::ClearAccountsAction::kKeepAll, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_TRUE(identity_manager()->GetPrimaryAccountId().empty()); - EXPECT_TRUE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_TRUE(identity_manager->GetPrimaryAccountId().empty()); + EXPECT_TRUE(identity_manager->GetPrimaryAccountInfo().email.empty()); // Start a signin process for the account and complete it right away to check // whether we end up with a similar result than with SetPrimaryAccount(). std::string signed_account_refresh_token; - primary_account_mutator()->LegacyStartSigninWithRefreshTokenForPrimaryAccount( + primary_account_mutator->LegacyStartSigninWithRefreshTokenForPrimaryAccount( kRefreshToken, account_info.gaia, account_info.email, kPassword, base::BindOnce( [](std::string* out_refresh_token, const std::string& refresh_token) { @@ -602,29 +677,29 @@ }, base::Unretained(&signed_account_refresh_token))); - primary_account_mutator()->LegacyCompletePendingPrimaryAccountSignin(); + primary_account_mutator->LegacyCompletePendingPrimaryAccountSignin(); // The refresh token assigned to the account should match the one passed. EXPECT_EQ(signed_account_refresh_token, kRefreshToken); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); EXPECT_FALSE(primary_account_id_1.empty()); EXPECT_EQ(primary_account_id_1, account_info.account_id); EXPECT_TRUE( - identity_manager()->HasAccountWithRefreshToken(primary_account_id_1)); - EXPECT_FALSE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + identity_manager->HasAccountWithRefreshToken(primary_account_id_1)); + EXPECT_FALSE(identity_manager->GetPrimaryAccountInfo().email.empty()); const std::string primary_account_id_2 = - identity_manager()->GetPrimaryAccountId(); + identity_manager->GetPrimaryAccountId(); - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); EXPECT_FALSE(primary_account_id_2.empty()); EXPECT_EQ(primary_account_id_2, account_info.account_id); EXPECT_TRUE( - identity_manager()->HasAccountWithRefreshToken(primary_account_id_2)); - EXPECT_FALSE(identity_manager()->GetPrimaryAccountInfo().email.empty()); + identity_manager->HasAccountWithRefreshToken(primary_account_id_2)); + EXPECT_FALSE(identity_manager->GetPrimaryAccountInfo().email.empty()); // Information retrieved via the IdentityManager now for the current primary // account should match the data of the account we signed in before. @@ -634,25 +709,31 @@ // Checks that checking whether an authentication process is in progress reports // true before starting and after successfully completing the signin process. TEST_F(PrimaryAccountMutatorTest, AuthInProgress_SigninCompleted) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); // Account available in the tracker service but still not authenticated means // there's neither a primary account nor an authentication process ongoing. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); // Start a signin process for the account we just made available and check // that it's reported to be in progress before the process is completed. base::RunLoop run_loop; std::string signed_account_refresh_token; - primary_account_mutator()->LegacyStartSigninWithRefreshTokenForPrimaryAccount( + primary_account_mutator->LegacyStartSigninWithRefreshTokenForPrimaryAccount( kRefreshToken, account_info.gaia, account_info.email, kPassword, base::BindOnce( [](std::string* out_refresh_token, const std::string& refresh_token) { @@ -660,11 +741,10 @@ }, base::Unretained(&signed_account_refresh_token))); - EXPECT_TRUE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_TRUE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); AccountInfo auth_in_progress_account_info = - primary_account_mutator()->LegacyPrimaryAccountForAuthInProgress(); + primary_account_mutator->LegacyPrimaryAccountForAuthInProgress(); // The data from the AccountInfo related to the authentication process still // in progress should match the data of the account being signed in. @@ -673,7 +753,7 @@ EXPECT_EQ(auth_in_progress_account_info.email, account_info.email); // Finally, complete the signin process so that we can do further checks. - primary_account_mutator()->LegacyCompletePendingPrimaryAccountSignin(); + primary_account_mutator->LegacyCompletePendingPrimaryAccountSignin(); run_loop.RunUntilIdle(); // The refresh token assigned to the account should match the one passed. @@ -681,15 +761,14 @@ // An account has been authenticated now, so there should be a primary account // authenticated and no authentication process reported as in progress now. - EXPECT_TRUE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_TRUE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); // Information retrieved via the IdentityManager now for the current primary // account should match the data of the account being signed in. - EXPECT_EQ(identity_manager()->GetPrimaryAccountId(), account_info.account_id); + EXPECT_EQ(identity_manager->GetPrimaryAccountId(), account_info.account_id); AccountInfo identity_manager_account_info = - identity_manager()->GetPrimaryAccountInfo(); + identity_manager->GetPrimaryAccountInfo(); EXPECT_EQ(identity_manager_account_info.account_id, account_info.account_id); EXPECT_EQ(identity_manager_account_info.gaia, account_info.gaia); EXPECT_EQ(identity_manager_account_info.email, account_info.email); @@ -698,25 +777,31 @@ // Checks that checking whether an authentication process is in progress reports // true before starting and after cancelling and ongoing signin process. TEST_F(PrimaryAccountMutatorTest, AuthInProgress_SigninCancelled) { + base::test::ScopedTaskEnvironment task_environment; + identity::IdentityTestEnvironment environment; + + identity::IdentityManager* identity_manager = environment.identity_manager(); + identity::PrimaryAccountMutator* primary_account_mutator = + identity_manager->GetPrimaryAccountMutator(); + // Abort the test if the current platform does not support mutation of the // primary account (the returned PrimaryAccountMutator* will be null). - if (!primary_account_mutator()) + if (!primary_account_mutator) return; AccountInfo account_info = - environment()->MakeAccountAvailable(kPrimaryAccountEmail); + environment.MakeAccountAvailable(kPrimaryAccountEmail); // Account available in the tracker service but still not authenticated means // there's neither a primary account nor an authentication process ongoing. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); // Start a signin process for the account we just made available and check // that it's reported to be in progress before the process is completed. base::RunLoop run_loop; std::string signed_account_refresh_token; - primary_account_mutator()->LegacyStartSigninWithRefreshTokenForPrimaryAccount( + primary_account_mutator->LegacyStartSigninWithRefreshTokenForPrimaryAccount( kRefreshToken, account_info.gaia, account_info.email, kPassword, base::BindOnce( [](std::string* out_refresh_token, const std::string& refresh_token) { @@ -724,11 +809,10 @@ }, base::Unretained(&signed_account_refresh_token))); - EXPECT_TRUE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + EXPECT_TRUE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); AccountInfo auth_in_progress_account_info = - primary_account_mutator()->LegacyPrimaryAccountForAuthInProgress(); + primary_account_mutator->LegacyPrimaryAccountForAuthInProgress(); // The data from the AccountInfo related to the authentication process still // in progress should match the data of the account being signed in. @@ -738,7 +822,7 @@ // Now cancel the signin process (by attempting to clear the primary account // we were trying to sign in so far), so that we can do further checks. - EXPECT_TRUE(primary_account_mutator()->ClearPrimaryAccount( + EXPECT_TRUE(primary_account_mutator->ClearPrimaryAccount( identity::PrimaryAccountMutator::ClearAccountsAction::kRemoveAll, signin_metrics::SIGNOUT_TEST, signin_metrics::SignoutDelete::IGNORE_METRIC)); @@ -751,14 +835,13 @@ // signed in, the refresh we just received should not be valid for the primary // account (even if it's been fetched and stored for the account already) and // no authentication process reported as in progress now. - EXPECT_FALSE(identity_manager()->HasPrimaryAccount()); - EXPECT_FALSE(identity_manager()->HasPrimaryAccountWithRefreshToken()); + EXPECT_FALSE(identity_manager->HasPrimaryAccount()); + EXPECT_FALSE(identity_manager->HasPrimaryAccountWithRefreshToken()); EXPECT_TRUE( - identity_manager()->HasAccountWithRefreshToken(account_info.account_id)); - EXPECT_FALSE( - primary_account_mutator()->LegacyIsPrimaryAccountAuthInProgress()); + identity_manager->HasAccountWithRefreshToken(account_info.account_id)); + EXPECT_FALSE(primary_account_mutator->LegacyIsPrimaryAccountAuthInProgress()); // Information retrieved via the IdentityManager confirms the cancelation. - EXPECT_EQ(identity_manager()->GetPrimaryAccountId(), std::string()); - EXPECT_TRUE(identity_manager()->GetPrimaryAccountInfo().IsEmpty()); + EXPECT_EQ(identity_manager->GetPrimaryAccountId(), std::string()); + EXPECT_TRUE(identity_manager->GetPrimaryAccountInfo().IsEmpty()); }
diff --git a/services/resource_coordinator/BUILD.gn b/services/resource_coordinator/BUILD.gn index 089fa8d..340362a 100644 --- a/services/resource_coordinator/BUILD.gn +++ b/services/resource_coordinator/BUILD.gn
@@ -67,7 +67,6 @@ "//services/metrics/public/cpp:ukm_builders", "//services/metrics/public/mojom", "//services/resource_coordinator/public/cpp:resource_coordinator_cpp", - "//services/service_manager/public/cpp/standalone_service:standalone_service", ] }
diff --git a/services/service_manager/README.md b/services/service_manager/README.md index 7273f86..fd43b59 100644 --- a/services/service_manager/README.md +++ b/services/service_manager/README.md
@@ -180,7 +180,7 @@ **`//services/my_service/BUILD.gn`** ``` python -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") source_set("lib") {
diff --git a/services/service_manager/background/tests/BUILD.gn b/services/service_manager/background/tests/BUILD.gn index 77486c2..971b93c 100644 --- a/services/service_manager/background/tests/BUILD.gn +++ b/services/service_manager/background/tests/BUILD.gn
@@ -4,7 +4,7 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -36,7 +36,7 @@ ] } -service("background_service_manager_test_service") { +service_executable("background_service_manager_test_service") { sources = [ "test_service.cc", ]
diff --git a/services/service_manager/embedder/BUILD.gn b/services/service_manager/embedder/BUILD.gn index 2a41a0e4..ae53ee51 100644 --- a/services/service_manager/embedder/BUILD.gn +++ b/services/service_manager/embedder/BUILD.gn
@@ -70,7 +70,7 @@ ":embedder_switches", "//mojo/core/embedder", "//services/service_manager/background:lib", - "//services/service_manager/public/cpp/standalone_service", + "//services/service_manager/public/cpp/service_executable:support", "//services/service_manager/runner:init", "//services/service_manager/runner/common", ]
diff --git a/services/service_manager/embedder/main.cc b/services/service_manager/embedder/main.cc index ef513e0..53eeddcb 100644 --- a/services/service_manager/embedder/main.cc +++ b/services/service_manager/embedder/main.cc
@@ -35,7 +35,7 @@ #include "services/service_manager/embedder/shared_file_util.h" #include "services/service_manager/embedder/switches.h" #include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/cpp/standalone_service/standalone_service.h" +#include "services/service_manager/public/cpp/service_executable/service_executable_environment.h" #include "services/service_manager/runner/common/client_util.h" #include "services/service_manager/runner/common/switches.h" #include "services/service_manager/runner/init.h" @@ -263,39 +263,29 @@ InitializeResources(); - int exit_code = 0; - RunStandaloneService(base::Bind( - [](MainDelegate* delegate, int* exit_code, - mojom::ServiceRequest request) { - // TODO(rockot): Make the default MessageLoop type overridable for - // services. This is TYPE_UI because at least one service (the "ui" - // service) needs it to be. - base::MessageLoop message_loop(base::MessageLoop::TYPE_UI); - base::RunLoop run_loop; + service_manager::ServiceExecutableEnvironment environment; - std::string service_name = - base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kServiceName); - if (service_name.empty()) { - LOG(ERROR) << "Service process requires --service-name"; - *exit_code = 1; - return; - } + base::MessageLoop message_loop(base::MessageLoop::TYPE_UI); + base::RunLoop run_loop; - std::unique_ptr<Service> service = - delegate->CreateEmbeddedService(service_name); - if (!service) { - LOG(ERROR) << "Failed to start embedded service: " << service_name; - *exit_code = 1; - return; - } + std::string service_name = + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kServiceName); + if (service_name.empty()) { + LOG(ERROR) << "Service process requires --service-name"; + return 1; + } - service->set_termination_closure(run_loop.QuitClosure()); - run_loop.Run(); - }, - delegate, &exit_code)); + std::unique_ptr<Service> service = + delegate->CreateEmbeddedService(service_name); + if (!service) { + LOG(ERROR) << "Failed to start embedded service: " << service_name; + return 1; + } - return exit_code; + service->set_termination_closure(run_loop.QuitClosure()); + run_loop.Run(); + return 0; } } // namespace
diff --git a/services/service_manager/public/cpp/service.gni b/services/service_manager/public/cpp/service.gni deleted file mode 100644 index 0ed9dcd..0000000 --- a/services/service_manager/public/cpp/service.gni +++ /dev/null
@@ -1,45 +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. - -# Generates a Service binary. The parameters of this template are those of an -# executable. -# -# TODO: We should consider removing this. At this point all it does is bring a -# single dep for an entry point, and change the executable extension. Both are -# of marginal value, and having another special target type may be unnecessarily -# confusing for developers when these are really just executables. -template("service") { - if (defined(invoker.resources)) { - # TODO(rockot): Remove this once all existing service targets have stopped - # setting |resources|. This target serves no purpose other than to ensure - # that |resources| is actually used, avoiding GN complaints. - source_set("${target_name}__unused_resources_target") { - testonly = true - sources = invoker.resources - deps = invoker.deps - } - } - - executable(target_name) { - forward_variables_from(invoker, "*", [ "configs" ]) - - # Executable targets already have a default set of configs which we should - # not overwrite. Hence we do not forward but manually append. - if (defined(invoker.configs)) { - configs += invoker.configs - } - - if (is_win) { - output_extension = "service.exe" - } else { - output_extension = "service" - } - - if (!defined(deps)) { - deps = [] - } - - deps += [ "//services/service_manager/public/cpp/standalone_service:main" ] - } -}
diff --git a/services/service_manager/public/cpp/service_executable.gni b/services/service_manager/public/cpp/service_executable.gni new file mode 100644 index 0000000..f149344f --- /dev/null +++ b/services/service_manager/public/cpp/service_executable.gni
@@ -0,0 +1,31 @@ +# 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. + +# Generates an executable binary to run a service. This is essentially just an +# executable with a special file extension (".service" on most platforms, +# ".service.exe" on Windows) and a custom |ServiceMain()| entry point, declared +# in service_main.h. +template("service_executable") { + executable(target_name) { + forward_variables_from(invoker, "*", [ "configs" ]) + + # Executable targets already have a default set of configs which we should + # not overwrite. Hence we do not forward but manually append. + if (defined(invoker.configs)) { + configs += invoker.configs + } + + if (is_win) { + output_extension = "service.exe" + } else { + output_extension = "service" + } + + if (!defined(deps)) { + deps = [] + } + + deps += [ "//services/service_manager/public/cpp/service_executable:main" ] + } +}
diff --git a/services/service_manager/public/cpp/standalone_service/BUILD.gn b/services/service_manager/public/cpp/service_executable/BUILD.gn similarity index 79% rename from services/service_manager/public/cpp/standalone_service/BUILD.gn rename to services/service_manager/public/cpp/service_executable/BUILD.gn index eb04b8d..dc723ac 100644 --- a/services/service_manager/public/cpp/standalone_service/BUILD.gn +++ b/services/service_manager/public/cpp/service_executable/BUILD.gn
@@ -2,12 +2,10 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -source_set("standalone_service") { +source_set("support") { sources = [ - "standalone_service.cc", - "standalone_service.h", - "switches.cc", - "switches.h", + "service_executable_environment.cc", + "service_executable_environment.h", ] deps = [ @@ -38,7 +36,10 @@ # point which accepts canonical command-line arguments to establish a connection # to the Service Manager. In order to link properly, dependents must ensure that # they define a ServiceMain() symbol which matches the signature in -# //services/service_manager/public/cpp/standalone_service/service_main.h. +# //services/service_manager/public/cpp/service_executable/service_main.h. +# +# Note that GN targets based on the service_executable() template defined in +# service_executable.gni implicitly link against this. source_set("main") { public = [ "service_main.h", @@ -49,7 +50,7 @@ ] deps = [ - ":standalone_service", + ":support", "//base", "//base:i18n", "//services/service_manager/runner:init",
diff --git a/services/service_manager/public/cpp/standalone_service/DEPS b/services/service_manager/public/cpp/service_executable/DEPS similarity index 100% rename from services/service_manager/public/cpp/standalone_service/DEPS rename to services/service_manager/public/cpp/service_executable/DEPS
diff --git a/services/service_manager/public/cpp/standalone_service/main.cc b/services/service_manager/public/cpp/service_executable/main.cc similarity index 83% rename from services/service_manager/public/cpp/standalone_service/main.cc rename to services/service_manager/public/cpp/service_executable/main.cc index b04e361..3e56810 100644 --- a/services/service_manager/public/cpp/standalone_service/main.cc +++ b/services/service_manager/public/cpp/service_executable/main.cc
@@ -13,9 +13,8 @@ #include "base/process/launch.h" #include "base/task/task_scheduler/task_scheduler.h" #include "build/build_config.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" -#include "services/service_manager/public/cpp/standalone_service/standalone_service.h" -#include "services/service_manager/public/cpp/standalone_service/switches.h" +#include "services/service_manager/public/cpp/service_executable/service_executable_environment.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/runner/init.h" @@ -47,8 +46,8 @@ command_line->GetSwitchValueASCII(switches::kDisableFeatures)); service_manager::WaitForDebuggerIfNecessary(); - service_manager::RunStandaloneService(base::BindOnce(&ServiceMain)); - + service_manager::ServiceExecutableEnvironment environment; + ServiceMain(environment.TakeServiceRequestFromCommandLine()); base::TaskScheduler::GetInstance()->Shutdown(); return 0;
diff --git a/services/service_manager/public/cpp/standalone_service/standalone_service.cc b/services/service_manager/public/cpp/service_executable/service_executable_environment.cc similarity index 78% rename from services/service_manager/public/cpp/standalone_service/standalone_service.cc rename to services/service_manager/public/cpp/service_executable/service_executable_environment.cc index ccc02b39..d120f2a 100644 --- a/services/service_manager/public/cpp/standalone_service/standalone_service.cc +++ b/services/service_manager/public/cpp/service_executable/service_executable_environment.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 "services/service_manager/public/cpp/standalone_service/standalone_service.h" +#include "services/service_manager/public/cpp/service_executable/service_executable_environment.h" #include "base/command_line.h" #include "base/debug/stack_trace.h" @@ -11,10 +11,8 @@ #include "base/message_loop/message_loop_current.h" #include "base/synchronization/waitable_event.h" #include "base/task/task_scheduler/task_scheduler.h" -#include "base/threading/thread.h" #include "build/build_config.h" #include "mojo/core/embedder/embedder.h" -#include "mojo/core/embedder/scoped_ipc_support.h" #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/invitation.h" #include "mojo/public/cpp/system/message_pipe.h" @@ -35,7 +33,8 @@ namespace service_manager { -void RunStandaloneService(StandaloneServiceCallback callback) { +ServiceExecutableEnvironment::ServiceExecutableEnvironment() + : ipc_thread_("IPC Thread") { DCHECK(!base::MessageLoopCurrent::Get()); #if defined(OS_MACOSX) @@ -43,9 +42,9 @@ mojo::core::DefaultMachBroker::SendTaskPortToParent(); #endif +#if defined(OS_LINUX) const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); -#if defined(OS_LINUX) if (command_line.HasSwitch(switches::kServiceSandboxType)) { // Warm parts of base in the copy of base in the mojo runner. base::RandUint64(); @@ -66,18 +65,21 @@ mojo::core::Init(); base::TaskScheduler::CreateAndStartWithDefaultParams("StandaloneService"); - base::Thread io_thread("io_thread"); - io_thread.StartWithOptions( + ipc_thread_.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); - mojo::core::ScopedIPCSupport ipc_support( - io_thread.task_runner(), - mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); + ipc_support_.emplace(ipc_thread_.task_runner(), + mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN); +} +ServiceExecutableEnvironment::~ServiceExecutableEnvironment() = default; + +mojom::ServiceRequest +ServiceExecutableEnvironment::TakeServiceRequestFromCommandLine() { auto invitation = mojo::IncomingInvitation::Accept( mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine( - command_line)); - std::move(callback).Run(GetServiceRequestFromCommandLine(&invitation)); + *base::CommandLine::ForCurrentProcess())); + return GetServiceRequestFromCommandLine(&invitation); } } // namespace service_manager
diff --git a/services/service_manager/public/cpp/service_executable/service_executable_environment.h b/services/service_manager/public/cpp/service_executable/service_executable_environment.h new file mode 100644 index 0000000..f526570 --- /dev/null +++ b/services/service_manager/public/cpp/service_executable/service_executable_environment.h
@@ -0,0 +1,46 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SERVICE_EXECUTABLE_ENVIRONMENT_H_ +#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SERVICE_EXECUTABLE_ENVIRONMENT_H_ + +#include "base/macros.h" +#include "base/optional.h" +#include "base/threading/thread.h" +#include "mojo/core/embedder/scoped_ipc_support.h" +#include "services/service_manager/public/mojom/service.mojom.h" + +namespace service_manager { + +// Sets up boilerplate process environment suitable for most service processes, +// including initialization of //base objects, Mojo IPC, and the scheduler; and +// acceptance of a connection from the Service Manager via canonical +// command-line arguments the Service Manager passes when launching service +// executables. This also starts the sandbox on Linux. +// +// This must outlive any Service implementation that is run within the process. +// +// Note that service executables typically won't use this directly, but will +// instead build a service_executable() target which provides a |ServiceMain()| +// entry point that already runs within the extent of a +// ServiceExecutableEnvironment. +class ServiceExecutableEnvironment { + public: + ServiceExecutableEnvironment(); + ~ServiceExecutableEnvironment(); + + // Returns a ServiceRequest which should be passed to the Service + // implementation which will run within the extent of this environment. + mojom::ServiceRequest TakeServiceRequestFromCommandLine(); + + private: + base::Thread ipc_thread_; + base::Optional<mojo::core::ScopedIPCSupport> ipc_support_; + + DISALLOW_COPY_AND_ASSIGN(ServiceExecutableEnvironment); +}; + +} // namespace service_manager + +#endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SERVICE_EXECUTABLE_ENVIRONMENT_H_
diff --git a/services/service_manager/public/cpp/standalone_service/service_main.h b/services/service_manager/public/cpp/service_executable/service_main.h similarity index 72% rename from services/service_manager/public/cpp/standalone_service/service_main.h rename to services/service_manager/public/cpp/service_executable/service_main.h index d1d959b..cdf2dc0e 100644 --- a/services/service_manager/public/cpp/standalone_service/service_main.h +++ b/services/service_manager/public/cpp/service_executable/service_main.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 SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_SERVICE_MAIN_H_ -#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_SERVICE_MAIN_H_ +#ifndef SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SERVICE_MAIN_H_ +#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_SERVICE_EXECUTABLE_SERVICE_MAIN_H_ #include "services/service_manager/public/mojom/service.mojom.h" // Service executables linking against the -// "//services/service_manager/public/cpp/standalone_service:main" target must +// "//services/service_manager/public/cpp/service_executable:main" target must // implement this function as their entry point. void ServiceMain(service_manager::mojom::ServiceRequest request);
diff --git a/services/service_manager/public/cpp/standalone_service/standalone_service.h b/services/service_manager/public/cpp/standalone_service/standalone_service.h deleted file mode 100644 index 7d3b5457..0000000 --- a/services/service_manager/public/cpp/standalone_service/standalone_service.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_STANDALONE_SERVICE_H_ -#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_STANDALONE_SERVICE_H_ - -#include "base/callback.h" -#include "services/service_manager/public/mojom/service.mojom.h" - -namespace service_manager { - -using StandaloneServiceCallback = - base::OnceCallback<void(mojom::ServiceRequest)>; - -// Runs a standalone service in the current process. This takes care of setting -// up a boilerplate environment, including initializing //base objects, Mojo -// IPC, running a MessageLoop, and establishing a connection to the Service -// Manager via canonical command-line arguments. Starts the sandbox on Linux. -// -// Once a Service request is obtained, |callback| is invoked with it. This call -// blocks until |callback| returns. -// -// NOTE: A typical service should also link against the main() defined in -// main.cc (next to this header) and thus have no need to call this function -// directly. -void RunStandaloneService(StandaloneServiceCallback callback); - -} // namespace service_manager - -#endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_STANDALONE_SERVICE_H_
diff --git a/services/service_manager/public/cpp/standalone_service/switches.cc b/services/service_manager/public/cpp/standalone_service/switches.cc deleted file mode 100644 index 58e07a0..0000000 --- a/services/service_manager/public/cpp/standalone_service/switches.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "services/service_manager/public/cpp/standalone_service/switches.h" - -namespace service_manager { -namespace switches { - -// The path where ICU initialization data can be found. If not provided, the -// service binary's directory is assumed. -const char kIcuDataDir[] = "icu-data-dir"; - -} // namespace switches -} // namespace service_manager
diff --git a/services/service_manager/public/cpp/standalone_service/switches.h b/services/service_manager/public/cpp/standalone_service/switches.h deleted file mode 100644 index 67d573fc..0000000 --- a/services/service_manager/public/cpp/standalone_service/switches.h +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_SWITCHES_H_ -#define SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_SWITCHES_H_ - -namespace service_manager { -namespace switches { - -extern const char kIcuDataDir[]; - -} // namespace switches -} // namespace service_manager - -#endif // SERVICES_SERVICE_MANAGER_PUBLIC_CPP_STANDALONE_SERVICE_SWITCHES_H_
diff --git a/services/service_manager/runner/host/BUILD.gn b/services/service_manager/runner/host/BUILD.gn index 6ab647f..6a9ebb0 100644 --- a/services/service_manager/runner/host/BUILD.gn +++ b/services/service_manager/runner/host/BUILD.gn
@@ -2,9 +2,9 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//services/service_manager/public/cpp/service.gni") -import("//services/service_manager/public/service_manifest.gni") import("//mojo/public/tools/bindings/mojom.gni") +import("//services/service_manager/public/cpp/service_executable.gni") +import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") source_set("lib") { @@ -42,10 +42,7 @@ "service_process_launcher.h", ] - deps += [ - "//mojo/core/embedder", - "//services/service_manager/public/cpp/standalone_service", - ] + deps += [ "//mojo/core/embedder" ] } } @@ -73,15 +70,10 @@ ] } - service("host_test_service") { + service_executable("host_test_service") { sources = [ "host_test_service_main.cc", ] - - deps = [ - "//mojo/public/cpp/system", - "//services/service_manager/public/cpp/standalone_service:main", - ] } service_manifest("host_test_service_manifest") {
diff --git a/services/service_manager/runner/host/host_test_service_main.cc b/services/service_manager/runner/host/host_test_service_main.cc index d5104d0..d8aeac8 100644 --- a/services/service_manager/runner/host/host_test_service_main.cc +++ b/services/service_manager/runner/host/host_test_service_main.cc
@@ -2,6 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" void ServiceMain(service_manager::mojom::ServiceRequest request) {}
diff --git a/services/service_manager/runner/host/service_process_launcher.cc b/services/service_manager/runner/host/service_process_launcher.cc index 92fef03..be7b170 100644 --- a/services/service_manager/runner/host/service_process_launcher.cc +++ b/services/service_manager/runner/host/service_process_launcher.cc
@@ -26,7 +26,6 @@ #include "mojo/public/cpp/platform/platform_channel.h" #include "mojo/public/cpp/system/core.h" #include "mojo/public/cpp/system/invitation.h" -#include "services/service_manager/public/cpp/standalone_service/switches.h" #include "services/service_manager/runner/common/client_util.h" #include "services/service_manager/runner/common/switches.h" #include "services/service_manager/sandbox/switches.h"
diff --git a/services/service_manager/standalone/BUILD.gn b/services/service_manager/standalone/BUILD.gn index 589c05a..164a77a 100644 --- a/services/service_manager/standalone/BUILD.gn +++ b/services/service_manager/standalone/BUILD.gn
@@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//services/service_manager/public/cpp/service.gni") import("//mojo/public/tools/bindings/mojom.gni") import("//testing/test.gni") @@ -23,8 +22,4 @@ "//services/service_manager/runner/host:lib", "//url", ] - - if (!is_ios) { - deps += [ "//services/service_manager/public/cpp/standalone_service" ] - } }
diff --git a/services/service_manager/tests/BUILD.gn b/services/service_manager/tests/BUILD.gn index 4451bd6a..a80015e5 100644 --- a/services/service_manager/tests/BUILD.gn +++ b/services/service_manager/tests/BUILD.gn
@@ -4,7 +4,7 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//testing/test.gni") group("tests") {
diff --git a/services/service_manager/tests/connect/BUILD.gn b/services/service_manager/tests/connect/BUILD.gn index 903b42c..12d36d2 100644 --- a/services/service_manager/tests/connect/BUILD.gn +++ b/services/service_manager/tests/connect/BUILD.gn
@@ -4,7 +4,7 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -64,7 +64,7 @@ source = "connect_test_sandboxed_app_manifest.json" } -service("connect_test_package") { +service_executable("connect_test_package") { testonly = true sources = [ "connect_test_package.cc", @@ -88,7 +88,7 @@ ] } -service("connect_test_app") { +service_executable("connect_test_app") { testonly = true sources = [ "connect_test_app.cc", @@ -107,7 +107,7 @@ source = "connect_test_app_manifest.json" } -service("connect_test_class_app") { +service_executable("connect_test_class_app") { testonly = true sources = [ "connect_test_class_app.cc", @@ -126,7 +126,7 @@ source = "connect_test_class_app_manifest.json" } -service("connect_test_singleton_app") { +service_executable("connect_test_singleton_app") { testonly = true sources = [ "connect_test_singleton_app.cc", @@ -155,7 +155,7 @@ "//base", "//build/win:default_exe_manifest", "//services/service_manager/public/cpp", - "//services/service_manager/public/cpp/standalone_service:main", + "//services/service_manager/public/cpp/service_executable:main", ] }
diff --git a/services/service_manager/tests/connect/connect_test_class_app.cc b/services/service_manager/tests/connect/connect_test_class_app.cc index 1cbfe8c..7c4a4fe 100644 --- a/services/service_manager/tests/connect/connect_test_class_app.cc +++ b/services/service_manager/tests/connect/connect_test_class_app.cc
@@ -11,8 +11,8 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/cpp/service_keepalive.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" #include "services/service_manager/public/mojom/connector.mojom.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/tests/connect/connect_test.mojom.h"
diff --git a/services/service_manager/tests/connect/connect_test_exe.cc b/services/service_manager/tests/connect/connect_test_exe.cc index b07e2649..8d9e567a 100644 --- a/services/service_manager/tests/connect/connect_test_exe.cc +++ b/services/service_manager/tests/connect/connect_test_exe.cc
@@ -10,7 +10,7 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/tests/connect/connect_test.mojom.h"
diff --git a/services/service_manager/tests/connect/connect_test_package.cc b/services/service_manager/tests/connect/connect_test_package.cc index e9960e9..2150f2b 100644 --- a/services/service_manager/tests/connect/connect_test_package.cc +++ b/services/service_manager/tests/connect/connect_test_package.cc
@@ -19,7 +19,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service_factory.mojom.h" #include "services/service_manager/tests/connect/connect_test.mojom.h"
diff --git a/services/service_manager/tests/connect/connect_test_singleton_app.cc b/services/service_manager/tests/connect/connect_test_singleton_app.cc index 5f839ca..0e876d1 100644 --- a/services/service_manager/tests/connect/connect_test_singleton_app.cc +++ b/services/service_manager/tests/connect/connect_test_singleton_app.cc
@@ -6,7 +6,7 @@ #include "base/message_loop/message_loop.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" void ServiceMain(service_manager::mojom::ServiceRequest request) {
diff --git a/services/service_manager/tests/lifecycle/BUILD.gn b/services/service_manager/tests/lifecycle/BUILD.gn index 56b10f01..2876e0c7 100644 --- a/services/service_manager/tests/lifecycle/BUILD.gn +++ b/services/service_manager/tests/lifecycle/BUILD.gn
@@ -4,7 +4,7 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -68,7 +68,7 @@ ] } -service("lifecycle_unittest_package") { +service_executable("lifecycle_unittest_package") { testonly = true sources = [ "package.cc", @@ -91,7 +91,7 @@ ] } -service("lifecycle_unittest_app") { +service_executable("lifecycle_unittest_app") { testonly = true sources = [ "app.cc", @@ -109,7 +109,7 @@ source = "app_manifest.json" } -service("lifecycle_unittest_parent") { +service_executable("lifecycle_unittest_parent") { testonly = true sources = [ "parent.cc", @@ -136,7 +136,7 @@ "//base", "//build/win:default_exe_manifest", "//services/service_manager/public/cpp", - "//services/service_manager/public/cpp/standalone_service:main", + "//services/service_manager/public/cpp/service_executable:main", ] }
diff --git a/services/service_manager/tests/lifecycle/app.cc b/services/service_manager/tests/lifecycle/app.cc index e3a7c8c..c5ea7740 100644 --- a/services/service_manager/tests/lifecycle/app.cc +++ b/services/service_manager/tests/lifecycle/app.cc
@@ -3,7 +3,7 @@ // found in the LICENSE file. #include "base/message_loop/message_loop.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/tests/lifecycle/app_client.h" void ServiceMain(service_manager::mojom::ServiceRequest request) {
diff --git a/services/service_manager/tests/lifecycle/package.cc b/services/service_manager/tests/lifecycle/package.cc index 3c91a295..b481f2c 100644 --- a/services/service_manager/tests/lifecycle/package.cc +++ b/services/service_manager/tests/lifecycle/package.cc
@@ -11,7 +11,7 @@ #include "mojo/public/cpp/bindings/binding_set.h" #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service_factory.mojom.h" #include "services/service_manager/tests/lifecycle/app_client.h" #include "services/service_manager/tests/lifecycle/lifecycle_unittest.mojom.h"
diff --git a/services/service_manager/tests/lifecycle/parent.cc b/services/service_manager/tests/lifecycle/parent.cc index 45c277b5..e7a5722 100644 --- a/services/service_manager/tests/lifecycle/parent.cc +++ b/services/service_manager/tests/lifecycle/parent.cc
@@ -12,7 +12,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/tests/lifecycle/lifecycle_unittest.mojom.h"
diff --git a/services/service_manager/tests/service_manager/BUILD.gn b/services/service_manager/tests/service_manager/BUILD.gn index d6bc218..ba34c4e 100644 --- a/services/service_manager/tests/service_manager/BUILD.gn +++ b/services/service_manager/tests/service_manager/BUILD.gn
@@ -4,7 +4,7 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -64,7 +64,7 @@ "//base", "//build/win:default_exe_manifest", "//services/service_manager/public/cpp", - "//services/service_manager/public/cpp/standalone_service:main", + "//services/service_manager/public/cpp/service_executable:main", ] } @@ -98,7 +98,7 @@ source = "regular_manifest.json" } -service("service_manager_unittest_embedder") { +service_executable("service_manager_unittest_embedder") { testonly = true sources = [ "embedder.cc",
diff --git a/services/service_manager/tests/service_manager/embedder.cc b/services/service_manager/tests/service_manager/embedder.cc index 2583b171..7fc5a6d 100644 --- a/services/service_manager/tests/service_manager/embedder.cc +++ b/services/service_manager/tests/service_manager/embedder.cc
@@ -10,7 +10,7 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/public/mojom/service_factory.mojom.h"
diff --git a/services/service_manager/tests/service_manager/target.cc b/services/service_manager/tests/service_manager/target.cc index 8b30851..e1e8eb03 100644 --- a/services/service_manager/tests/service_manager/target.cc +++ b/services/service_manager/tests/service_manager/target.cc
@@ -7,7 +7,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/tests/service_manager/service_manager_unittest.mojom.h"
diff --git a/services/service_manager/tests/shutdown/BUILD.gn b/services/service_manager/tests/shutdown/BUILD.gn index b901d58..007691d 100644 --- a/services/service_manager/tests/shutdown/BUILD.gn +++ b/services/service_manager/tests/shutdown/BUILD.gn
@@ -4,7 +4,7 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -50,7 +50,7 @@ source = "shutdown_service_manifest.json" } -service("shutdown_service") { +service_executable("shutdown_service") { testonly = true sources = [ "shutdown_service_app.cc", @@ -68,7 +68,7 @@ source = "shutdown_client_manifest.json" } -service("shutdown_client") { +service_executable("shutdown_client") { testonly = true sources = [ "shutdown_client_app.cc",
diff --git a/services/service_manager/tests/shutdown/shutdown_client_app.cc b/services/service_manager/tests/shutdown/shutdown_client_app.cc index 98d4121..e28c6990 100644 --- a/services/service_manager/tests/shutdown/shutdown_client_app.cc +++ b/services/service_manager/tests/shutdown/shutdown_client_app.cc
@@ -9,7 +9,7 @@ #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/tests/shutdown/shutdown_unittest.mojom.h" namespace service_manager {
diff --git a/services/service_manager/tests/shutdown/shutdown_service_app.cc b/services/service_manager/tests/shutdown/shutdown_service_app.cc index fb1aa18c..84990cc 100644 --- a/services/service_manager/tests/shutdown/shutdown_service_app.cc +++ b/services/service_manager/tests/shutdown/shutdown_service_app.cc
@@ -8,7 +8,7 @@ #include "services/service_manager/public/cpp/binder_registry.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "services/service_manager/tests/shutdown/shutdown_unittest.mojom.h"
diff --git a/services/tracing/BUILD.gn b/services/tracing/BUILD.gn index 5844e5b4..2b9848f 100644 --- a/services/tracing/BUILD.gn +++ b/services/tracing/BUILD.gn
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/chromecast_build.gni") import("//services/service_manager/public/service_manifest.gni") # There should be only one tracing service. It is currently @@ -45,6 +46,10 @@ public_deps += [ "//third_party/perfetto:libperfetto" ] } + + if (is_chromecast) { + defines = [ "IS_CHROMECAST" ] + } } service_manifest("manifest") { @@ -103,4 +108,8 @@ "//third_party/perfetto/protos/perfetto/trace/chrome:lite", ] } + + if (is_chromecast) { + defines = [ "IS_CHROMECAST" ] + } }
diff --git a/services/tracing/perfetto/json_trace_exporter.cc b/services/tracing/perfetto/json_trace_exporter.cc index 37acbab..c6e7d5b 100644 --- a/services/tracing/perfetto/json_trace_exporter.cc +++ b/services/tracing/perfetto/json_trace_exporter.cc
@@ -14,6 +14,7 @@ #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" +#include "build/build_config.h" #include "services/tracing/public/mojom/perfetto_service.mojom.h" #include "third_party/perfetto/include/perfetto/tracing/core/trace_config.h" #include "third_party/perfetto/include/perfetto/tracing/core/trace_packet.h" @@ -296,11 +297,22 @@ auto* chrome_config = trace_event_config->mutable_chrome_config(); chrome_config->set_trace_config(config_); +// Only CrOS and Cast support system tracing. +#if defined(OS_CHROMEOS) || (defined(IS_CHROMECAST) && defined(OS_LINUX)) auto* system_trace_config = trace_config.add_data_sources()->mutable_config(); system_trace_config->set_name(mojom::kSystemTraceDataSourceName); system_trace_config->set_target_buffer(0); auto* system_chrome_config = system_trace_config->mutable_chrome_config(); system_chrome_config->set_trace_config(config_); +#endif + +#if defined(OS_CHROMEOS) + auto* arc_trace_config = trace_config.add_data_sources()->mutable_config(); + arc_trace_config->set_name(mojom::kArcTraceDataSourceName); + arc_trace_config->set_target_buffer(0); + auto* arc_chrome_config = arc_trace_config->mutable_chrome_config(); + arc_chrome_config->set_trace_config(config_); +#endif auto* trace_metadata_config = trace_config.add_data_sources()->mutable_config();
diff --git a/services/tracing/public/mojom/perfetto_service.mojom b/services/tracing/public/mojom/perfetto_service.mojom index 1855df9..ccbf470 100644 --- a/services/tracing/public/mojom/perfetto_service.mojom +++ b/services/tracing/public/mojom/perfetto_service.mojom
@@ -7,6 +7,7 @@ const string kTraceEventDataSourceName = "org.chromium.trace_event"; const string kMetaDataSourceName = "org.chromium.trace_metadata"; const string kSystemTraceDataSourceName = "org.chromium.trace_system"; +const string kArcTraceDataSourceName = "org.chromium.trace_arc"; // Brief description of the flow: There's a per-process ProducerClient which // connects to the central PerfettoService and establishes a two-way connection
diff --git a/services/video_capture/BUILD.gn b/services/video_capture/BUILD.gn index 1651485..32890d1 100644 --- a/services/video_capture/BUILD.gn +++ b/services/video_capture/BUILD.gn
@@ -3,11 +3,11 @@ # found in the LICENSE file. import("//services/catalog/public/tools/catalog.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") -service("video_capture") { +service_executable("video_capture") { sources = [ "service_main.cc", ]
diff --git a/services/video_capture/service_main.cc b/services/video_capture/service_main.cc index b0695e8..b5ab2ce 100644 --- a/services/video_capture/service_main.cc +++ b/services/video_capture/service_main.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "base/message_loop/message_loop.h" #include "services/video_capture/service_impl.h"
diff --git a/services/viz/BUILD.gn b/services/viz/BUILD.gn index 045a310..51cfdc4 100644 --- a/services/viz/BUILD.gn +++ b/services/viz/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. -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") -service("viz") { +service_executable("viz") { sources = [ "main.cc", ]
diff --git a/services/viz/main.cc b/services/viz/main.cc index 5818269..2a9a5f4 100644 --- a/services/viz/main.cc +++ b/services/viz/main.cc
@@ -3,7 +3,7 @@ // found in the LICENSE file. #include "base/message_loop/message_loop.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/viz/service.h" void ServiceMain(service_manager::mojom::ServiceRequest request) {
diff --git a/services/ws/ime/test_ime_driver/BUILD.gn b/services/ws/ime/test_ime_driver/BUILD.gn index d0723dad..86070f16 100644 --- a/services/ws/ime/test_ime_driver/BUILD.gn +++ b/services/ws/ime/test_ime_driver/BUILD.gn
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") import("//testing/test.gni") @@ -21,7 +21,7 @@ ] } -service("test_ime_driver") { +service_executable("test_ime_driver") { sources = [ "main.cc", ]
diff --git a/services/ws/ime/test_ime_driver/main.cc b/services/ws/ime/test_ime_driver/main.cc index 4a4c2d6..49a6a99 100644 --- a/services/ws/ime/test_ime_driver/main.cc +++ b/services/ws/ime/test_ime_driver/main.cc
@@ -3,7 +3,7 @@ // found in the LICENSE file. #include "base/message_loop/message_loop.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/ws/ime/test_ime_driver/test_ime_application.h" void ServiceMain(service_manager::mojom::ServiceRequest request) {
diff --git a/services/ws/test_ws/BUILD.gn b/services/ws/test_ws/BUILD.gn index 458407e..ac94174 100644 --- a/services/ws/test_ws/BUILD.gn +++ b/services/ws/test_ws/BUILD.gn
@@ -3,10 +3,10 @@ # found in the LICENSE file. import("//mojo/public/tools/bindings/mojom.gni") -import("//services/service_manager/public/cpp/service.gni") +import("//services/service_manager/public/cpp/service_executable.gni") import("//services/service_manager/public/service_manifest.gni") -service("test_ws") { +service_executable("test_ws") { testonly = true sources = [ "test_ws.cc",
diff --git a/services/ws/test_ws/test_ws.cc b/services/ws/test_ws/test_ws.cc index 5bd7ae3..e43c021 100644 --- a/services/ws/test_ws/test_ws.cc +++ b/services/ws/test_ws/test_ws.cc
@@ -4,7 +4,7 @@ #include "base/message_loop/message_loop.h" #include "services/service_manager/public/cpp/service.h" -#include "services/service_manager/public/cpp/standalone_service/service_main.h" +#include "services/service_manager/public/cpp/service_executable/service_main.h" #include "services/ws/test_ws/test_window_service_factory.h" #include "ui/base/ui_base_paths.h"
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 25b221c66..2dee9af 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -7125,6 +7125,14 @@ ], "isolated_scripts": [ { + "isolate_coverage_data": true, + "isolate_name": "blink_json_parser_fuzzer", + "name": "blink_json_parser_fuzzer", + "swarming": { + "can_use_on_swarming_builders": false + } + }, + { "args": [ "--additional-driver-flag=--no-sandbox", "--num-retries=3"
diff --git a/testing/buildbot/chromium.perf.fyi.json b/testing/buildbot/chromium.perf.fyi.json index ceceb0f3..beac3db 100644 --- a/testing/buildbot/chromium.perf.fyi.json +++ b/testing/buildbot/chromium.perf.fyi.json
@@ -288,7 +288,8 @@ "can_use_on_swarming_builders": true, "dimension_sets": [ { - "id": "build186-b7" + "id": "build186-b7", + "pool": "chrome.tests.perf-fyi" } ], "expiration": 36000,
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index fe6c59e..84d2ea6 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -68,6 +68,7 @@ "//testing/buildbot/filters/cast-linux.content_browsertests.filter", "//testing/buildbot/filters/chromeos.single_process_mash.content_browsertests.filter", "//testing/buildbot/filters/mojo.fyi.network_content_browsertests.filter", + "//testing/buildbot/filters/site_isolation_android.content_browsertests.filter", ] }
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index 3c422106..5994a24 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -197,6 +197,19 @@ "label": "//third_party/blink/renderer/platform/heap:blink_heap_unittests", "type": "console_test_launcher", }, + "blink_json_parser_fuzzer": { + "label": "//third_party/blink/renderer/platform:blink_json_parser_fuzzer", + "type": "script", + "script": "//tools/code_coverage/run_fuzz_target.py", + "args": [ + "--fuzzer", + "./blink_json_parser_fuzzer", + "--output-dir", + "${ISOLATED_OUTDIR}", + "--timeout", + "3600", + ], + }, "blink_platform_unittests": { "label": "//third_party/blink/renderer/platform:blink_platform_unittests", "type": "console_test_launcher",
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 6cc6d4c..ca4afc73 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -569,6 +569,15 @@ }, 'chromium_code_coverage_isolated_scripts': { + 'blink_json_parser_fuzzer': { + 'swarming': { + # Fuzzer targets are temporarily to be run locally on the builder + # rather than on swarming avoid placing the corpus on the public + # isolate or making a swarming job depend on external data. + # see crbug.com/910235 + 'can_use_on_swarming_builders': False, + }, + }, 'webkit_layout_tests': { 'args': [ '--additional-driver-flag=--no-sandbox', @@ -582,7 +591,6 @@ }, }, - 'chromium_gtests': { 'angle_unittests': {}, 'base_unittests': {},
diff --git a/testing/buildbot/tryserver.chromium.linux.json b/testing/buildbot/tryserver.chromium.linux.json index b021a3f4e..3793ebf 100644 --- a/testing/buildbot/tryserver.chromium.linux.json +++ b/testing/buildbot/tryserver.chromium.linux.json
@@ -682,6 +682,14 @@ ], "isolated_scripts": [ { + "isolate_coverage_data": true, + "isolate_name": "blink_json_parser_fuzzer", + "name": "blink_json_parser_fuzzer", + "swarming": { + "can_use_on_swarming_builders": false + } + }, + { "args": [ "--additional-driver-flag=--no-sandbox", "--num-retries=3"
diff --git a/testing/libfuzzer/BUILD.gn b/testing/libfuzzer/BUILD.gn index 4f6690f..c7d1ed6b 100644 --- a/testing/libfuzzer/BUILD.gn +++ b/testing/libfuzzer/BUILD.gn
@@ -23,6 +23,16 @@ } else { sources += [ "unittest_main.cc" ] } + if (use_clang_coverage) { + # For purposes of code coverage calculation, fuzzer targets are run through + # a wrapper script in this directory, which handles corpus retrieval and + # appropriate parameter passing to run the target in an isolate. This + # directive makes this script and its dependencies to be included in the + # target's isolate. + data = [ + "//tools/code_coverage/", + ] + } } # A config used by all fuzzer_tests.
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 972703c..21536e6 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -4061,29 +4061,6 @@ ] } ], - "ResourceLoadScheduler": [ - { - "platforms": [ - "android", - "chromeos", - "linux", - "mac", - "windows" - ], - "experiments": [ - { - "name": "Enabled_v3_bg_limit_3_2", - "params": { - "bg_limit": "3", - "bg_sub_limit": "2" - }, - "enable_features": [ - "ResourceLoadScheduler" - ] - } - ] - } - ], "ResourceLoadingHints": [ { "platforms": [
diff --git a/third_party/blink/perf_tests/layout/contain-content-style-change.html b/third_party/blink/perf_tests/layout/contain-content-style-change.html new file mode 100644 index 0000000..8233ad5b --- /dev/null +++ b/third_party/blink/perf_tests/layout/contain-content-style-change.html
@@ -0,0 +1,58 @@ +<!DOCTYPE html> +<script src="../resources/runner.js"></script> +<title>Contain layout performance</title> +<style> +#listContainer { + margin: 0 auto; + width: 600px; + border: 1px solid blue; + contain: content; +} +.listItem { + outline: 2px solid green; + padding: .4em; + overflow: hidden; + contain: content; +} +</style> +</head> +<body> +<div id="listContainer"></div> +<script> +const LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; + +let listContainer = null; + +function createListItem() { + let item = document.createElement("div"); + item.classList.add("listItem"); + item.textContent = LOREM_IPSUM.substr( + Math.floor(Math.random()*100), Math.floor(Math.random()*200)+150); + listContainer.appendChild(item); +} + +var height = 0; +function runTest() { + height++; + listContainer.firstChild.style.height = height + "px"; + if (height > 50) + height = 0; +} + +function setupTest() { + listContainer = document.getElementById("listContainer"); + for (let i = 0; i < 5000; ++i) { + createListItem(); + } + PerfTestRunner.forceLayout(); +} + +setupTest(); + +PerfTestRunner.measureFrameTime({ + description: "Measures performance of changing the height of a child of a contain:contents object.", + iterationCount: 50, + run: runTest +}); + +</script>
diff --git a/third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom b/third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom index 90a4054..2818f9eb 100644 --- a/third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom +++ b/third_party/blink/public/platform/modules/background_fetch/background_fetch.mojom
@@ -84,8 +84,9 @@ uint64 uploaded; uint64 download_total; uint64 downloaded; - BackgroundFetchResult result; - BackgroundFetchFailureReason failure_reason; + BackgroundFetchResult result = BackgroundFetchResult.UNSET; + BackgroundFetchFailureReason failure_reason = + BackgroundFetchFailureReason.NONE; }; // This contains the data we need to record UKM metrics, that isn't needed for
diff --git a/third_party/blink/public/platform/web_feature.mojom b/third_party/blink/public/platform/web_feature.mojom index 96b7b3c..66c582c 100644 --- a/third_party/blink/public/platform/web_feature.mojom +++ b/third_party/blink/public/platform/web_feature.mojom
@@ -1787,15 +1787,6 @@ kColorInputTypeChooserByTrustedClick = 2332, kColorInputTypeChooserByUntrustedClick = 2333, kCSSTypedOMStylePropertyMap = 2334, - kScrollToFragmentRequested = 2335, - kScrollToFragmentSucceedWithRaw = 2336, - kScrollToFragmentSucceedWithASCII = 2337, - kScrollToFragmentSucceedWithUTF8 = 2338, - kScrollToFragmentSucceedWithIsomorphic = 2339, - kScrollToFragmentFailWithASCII = 2341, - kScrollToFragmentFailWithUTF8 = 2342, - kScrollToFragmentFailWithIsomorphic = 2343, - kScrollToFragmentFailWithInvalidEncoding = 2345, kRTCPeerConnectionWithActiveCsp = 2346, // The above items are available as of the M65 branch.
diff --git a/third_party/blink/public/web/web_local_frame.h b/third_party/blink/public/web/web_local_frame.h index eec8cd4..d51ace4 100644 --- a/third_party/blink/public/web/web_local_frame.h +++ b/third_party/blink/public/web/web_local_frame.h
@@ -28,10 +28,6 @@ #include "third_party/blink/public/web/web_text_direction.h" #include "v8/include/v8.h" -namespace service_manager { -class InterfaceProvider; -} // namespace service_manager - namespace blink { class FrameScheduler; @@ -135,8 +131,6 @@ virtual void SetAutofillClient(WebAutofillClient*) = 0; virtual WebAutofillClient* AutofillClient() = 0; - virtual void InitializeSharedWorkerRepositoryClient( - service_manager::InterfaceProvider*) = 0; // Closing -------------------------------------------------------------
diff --git a/third_party/blink/renderer/DEPS b/third_party/blink/renderer/DEPS index 9fc2759d..c305f913 100644 --- a/third_party/blink/renderer/DEPS +++ b/third_party/blink/renderer/DEPS
@@ -9,6 +9,7 @@ "+base/format_macros.h", "+base/gtest_prod_util.h", "+base/location.h", + "+base/logging.h", "+base/macros.h", "+base/memory/ptr_util.h", "+base/memory/weak_ptr.h",
diff --git a/third_party/blink/renderer/bindings/core/v8/js_event_listener.h b/third_party/blink/renderer/bindings/core/v8/js_event_listener.h index dead4b4..b153ea0 100644 --- a/third_party/blink/renderer/bindings/core/v8/js_event_listener.h +++ b/third_party/blink/renderer/bindings/core/v8/js_event_listener.h
@@ -26,8 +26,7 @@ v8::Local<v8::Object> listener, const V8PrivateProperty::Symbol& property) : JSBasedEventListener(kJSEventListenerType), - event_listener_(V8EventListener::CreateOrNull(listener)) { - DCHECK(event_listener_); + event_listener_(V8EventListener::Create(listener)) { Attach(script_state, listener, property, this); }
diff --git a/third_party/blink/renderer/bindings/core/v8/script_controller.cc b/third_party/blink/renderer/bindings/core/v8/script_controller.cc index e9d6c32..35405dba 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_controller.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_controller.cc
@@ -217,7 +217,8 @@ return false; const int kJavascriptSchemeLength = sizeof("javascript:") - 1; - String script_source = DecodeURLEscapeSequences(url.GetString()); + String script_source = DecodeURLEscapeSequences( + url.GetString(), DecodeURLMode::kUTF8OrIsomorphic); bool should_bypass_main_world_content_security_policy = ContentSecurityPolicy::ShouldBypassMainWorld(GetFrame()->GetDocument());
diff --git a/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc b/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc index eb50536..53b11854 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.cc
@@ -24,6 +24,45 @@ namespace blink { +namespace { + +// Returns false if GetOwnPropertyDescriptor() or Get() failed and the callsite +// needs to rethrow an exception. Returns true otherwise. +// |result_desc| is not updated if property_name is not found in the prototype +// chain. +bool GetPropertyDescriptorOnPrototypeChain( + v8::Local<v8::Object> start_prototype, + const char* property_name, + v8::Isolate* isolate, + v8::Local<v8::Value>* result_desc) { + DCHECK(isolate); + DCHECK(result_desc); + v8::Local<v8::Context> current_context = isolate->GetCurrentContext(); + v8::Local<v8::Value> prototype = start_prototype; + v8::Local<v8::String> v8_prototype = V8AtomicString(isolate, "__proto__"); + v8::Local<v8::String> v8_name = V8AtomicString(isolate, property_name); + while (prototype->IsObject()) { + v8::Local<v8::Value> desc; + if (!prototype.As<v8::Object>() + ->GetOwnPropertyDescriptor(current_context, v8_name) + .ToLocal(&desc)) + return false; + if (desc->IsObject()) { + *result_desc = desc; + return true; + } + v8::Local<v8::Value> parent_prototype; + if (!prototype.As<v8::Object>() + ->Get(current_context, v8_prototype) + .ToLocal(&parent_prototype)) + return false; + prototype = parent_prototype; + } + return true; +} + +} // anonymous namespace + ScriptCustomElementDefinitionBuilder::ScriptCustomElementDefinitionBuilder( ScriptState* script_state, CustomElementRegistry* registry, @@ -195,14 +234,12 @@ v8::Local<v8::Context> current_context = isolate->GetCurrentContext(); v8::TryCatch try_catch(isolate); v8::Local<v8::Value> value_desc; - if (!prototype - ->GetOwnPropertyDescriptor(current_context, - V8AtomicString(isolate, "value")) - .ToLocal(&value_desc)) { + if (!GetPropertyDescriptorOnPrototypeChain(prototype, "value", isolate, + &value_desc)) { exception_state_.RethrowV8Exception(try_catch.Exception()); return false; } - if (!value_desc->IsObject()) { + if (value_desc.IsEmpty() || !value_desc->IsObject()) { exception_state_.ThrowDOMException( DOMExceptionCode::kTypeMismatchError, "A class for form-associated custom elements must have a 'value' "
diff --git a/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc b/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc index 15576be..5703b2a5 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_event_listener.cc
@@ -55,7 +55,7 @@ OrdinalNumber::First()); String source_url; - v8::Isolate* isolate = ToIsolate(&node->GetDocument()); + v8::Isolate* isolate = node->GetDocument().GetIsolate(); v8::HandleScope scope(isolate); if (LocalFrame* frame = node->GetDocument().GetFrame()) {
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_property_base.cc b/third_party/blink/renderer/bindings/core/v8/script_promise_property_base.cc index fa1fb64..472f8da 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_property_base.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_property_base.cc
@@ -16,7 +16,7 @@ ExecutionContext* execution_context, Name name) : ContextClient(execution_context), - isolate_(ToIsolate(execution_context)), + isolate_(execution_context->GetIsolate()), name_(name), state_(kPending) {}
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc b/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc index 627e808f0..78cce798 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc
@@ -112,7 +112,7 @@ virtual ~ScriptPromisePropertyTestBase() { DestroyContext(); } Document& GetDocument() { return page_->GetDocument(); } - v8::Isolate* GetIsolate() { return ToIsolate(&GetDocument()); } + v8::Isolate* GetIsolate() { return GetDocument().GetIsolate(); } ScriptState* MainScriptState() { return ToScriptStateForMainWorld(GetDocument().GetFrame()); }
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc b/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc index 31129d4..88d5483 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc
@@ -872,22 +872,6 @@ return iterator_getter->IsFunction(); } -v8::Isolate* ToIsolate(const ExecutionContext* context) { - if (!context) - return nullptr; - -#if DCHECK_IS_ON() - v8::Isolate* isolate; - if (context && context->IsDocument()) - isolate = V8PerIsolateData::MainThreadIsolate(); - else - isolate = v8::Isolate::GetCurrent(); - DCHECK(context->GetIsolate() == isolate); -#endif - - return context->GetIsolate(); -} - v8::Isolate* ToIsolate(const LocalFrame* frame) { DCHECK(frame); return frame->GetWindowProxyManager()->GetIsolate();
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h b/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h index 8fcde322..3504d75 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h +++ b/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h
@@ -436,7 +436,6 @@ v8::Local<v8::Value>, ExceptionState&); -CORE_EXPORT v8::Isolate* ToIsolate(const ExecutionContext*); CORE_EXPORT v8::Isolate* ToIsolate(const LocalFrame*); CORE_EXPORT DOMWindow* ToDOMWindow(v8::Isolate*, v8::Local<v8::Value>);
diff --git a/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl b/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl index fd7c045f..a0bf43f 100644 --- a/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl +++ b/third_party/blink/renderer/bindings/templates/callback_interface.cc.tmpl
@@ -68,19 +68,6 @@ return "{{v8_class}}"; } -// static -{{v8_class}}* {{v8_class}}::CreateOrNull(v8::Local<v8::Object> callback_object) { - v8::Local<v8::Context> creation_context = callback_object->CreationContext(); - // When |callback_object| is an object in RemoteContext (i.e. RemoteInstance), - // the object has no creation context, and no way to proceed. - // TODO(crbug.com/886588): Make CreateOrNull into Create removing the early - // return with nullptr. - if (creation_context.IsEmpty()) - return nullptr; - - return MakeGarbageCollected<{{v8_class}}>(callback_object, creation_context); -} - {% for method in methods %} v8::Maybe<{{method.cpp_type}}> {{v8_class}}::{{method.name}}({{method.argument_declarations | join(', ')}}) {
diff --git a/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl b/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl index 80fea06d..fa25931 100644 --- a/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl +++ b/third_party/blink/renderer/bindings/templates/callback_interface.h.tmpl
@@ -33,19 +33,15 @@ {% endfor %} {% endif %} - // Creates and returns a new instance. Returns nullptr when |callback_object| - // is an object in a remote context (e.g. cross origin window object). The - // call sites may want to throw a SecurityError in the case. - // See also crbug.com/886588 - static {{v8_class}}* CreateOrNull(v8::Local<v8::Object> callback_object); + static {{v8_class}}* Create(v8::Local<v8::Object> callback_object) { + return MakeGarbageCollected<{{v8_class}}>(callback_object); + } {% set single_operation_enum_value = 'kSingleOperation' if is_single_operation_callback_interface else 'kNotSingleOperation' %} - explicit {{v8_class}}( - v8::Local<v8::Object> callback_object, - v8::Local<v8::Context> callback_object_creation_context) - : CallbackInterfaceBase(callback_object, callback_object_creation_context, + explicit {{v8_class}}(v8::Local<v8::Object> callback_object) + : CallbackInterfaceBase(callback_object, {{single_operation_enum_value}}) {} ~{{v8_class}}() override = default;
diff --git a/third_party/blink/renderer/bindings/templates/methods.cc.tmpl b/third_party/blink/renderer/bindings/templates/methods.cc.tmpl index 0ad3aed0..6de09d31 100644 --- a/third_party/blink/renderer/bindings/templates/methods.cc.tmpl +++ b/third_party/blink/renderer/bindings/templates/methods.cc.tmpl
@@ -174,12 +174,7 @@ {% endif %}{# method.name #} {% else %}{# argument.idl_type == 'EventListener' #} if (info[{{argument.index}}]->IsObject()) { - {{argument.local_cpp_variable}} = V8{{argument.idl_type}}::CreateOrNull(info[{{argument.index}}].As<v8::Object>()); - if (!{{argument.local_cpp_variable}}) { - {{define_exception_state}} - exception_state.ThrowSecurityError("The callback provided as parameter {{argument.index + 1}} is a cross origin object."); - return; - } + {{argument.local_cpp_variable}} = V8{{argument.idl_type}}::Create(info[{{argument.index}}].As<v8::Object>()); {% if argument.is_nullable %} } else if (info[{{argument.index}}]->IsNullOrUndefined()) { {{argument.local_cpp_variable}} = nullptr;
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc index 0ddc03a1a..bb04992b 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc
@@ -25,19 +25,6 @@ return "V8TestCallbackInterface"; } -// static -V8TestCallbackInterface* V8TestCallbackInterface::CreateOrNull(v8::Local<v8::Object> callback_object) { - v8::Local<v8::Context> creation_context = callback_object->CreationContext(); - // When |callback_object| is an object in RemoteContext (i.e. RemoteInstance), - // the object has no creation context, and no way to proceed. - // TODO(crbug.com/886588): Make CreateOrNull into Create removing the early - // return with nullptr. - if (creation_context.IsEmpty()) - return nullptr; - - return MakeGarbageCollected<V8TestCallbackInterface>(callback_object, creation_context); -} - v8::Maybe<void> V8TestCallbackInterface::voidMethod(ScriptWrappable* callback_this_value) { ScriptState* callback_relevant_script_state = CallbackRelevantScriptStateOrThrowException(
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.h b/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.h index 8408b70..3a72e75 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.h +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.h
@@ -20,16 +20,12 @@ class CORE_EXPORT V8TestCallbackInterface final : public CallbackInterfaceBase { public: - // Creates and returns a new instance. Returns nullptr when |callback_object| - // is an object in a remote context (e.g. cross origin window object). The - // call sites may want to throw a SecurityError in the case. - // See also crbug.com/886588 - static V8TestCallbackInterface* CreateOrNull(v8::Local<v8::Object> callback_object); + static V8TestCallbackInterface* Create(v8::Local<v8::Object> callback_object) { + return MakeGarbageCollected<V8TestCallbackInterface>(callback_object); + } - explicit V8TestCallbackInterface( - v8::Local<v8::Object> callback_object, - v8::Local<v8::Context> callback_object_creation_context) - : CallbackInterfaceBase(callback_object, callback_object_creation_context, + explicit V8TestCallbackInterface(v8::Local<v8::Object> callback_object) + : CallbackInterfaceBase(callback_object, kNotSingleOperation) {} ~V8TestCallbackInterface() override = default;
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.cc index 572cfc6..2be000d 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.cc
@@ -83,19 +83,6 @@ return "V8TestLegacyCallbackInterface"; } -// static -V8TestLegacyCallbackInterface* V8TestLegacyCallbackInterface::CreateOrNull(v8::Local<v8::Object> callback_object) { - v8::Local<v8::Context> creation_context = callback_object->CreationContext(); - // When |callback_object| is an object in RemoteContext (i.e. RemoteInstance), - // the object has no creation context, and no way to proceed. - // TODO(crbug.com/886588): Make CreateOrNull into Create removing the early - // return with nullptr. - if (creation_context.IsEmpty()) - return nullptr; - - return MakeGarbageCollected<V8TestLegacyCallbackInterface>(callback_object, creation_context); -} - v8::Maybe<uint16_t> V8TestLegacyCallbackInterface::acceptNode(ScriptWrappable* callback_this_value, Node* node) { ScriptState* callback_relevant_script_state = CallbackRelevantScriptStateOrThrowException(
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.h b/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.h index 09a3e3c..da89c7e 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.h +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_legacy_callback_interface.h
@@ -33,16 +33,12 @@ // Constants static constexpr uint16_t CONST_VALUE_USHORT_42 = 42; - // Creates and returns a new instance. Returns nullptr when |callback_object| - // is an object in a remote context (e.g. cross origin window object). The - // call sites may want to throw a SecurityError in the case. - // See also crbug.com/886588 - static V8TestLegacyCallbackInterface* CreateOrNull(v8::Local<v8::Object> callback_object); + static V8TestLegacyCallbackInterface* Create(v8::Local<v8::Object> callback_object) { + return MakeGarbageCollected<V8TestLegacyCallbackInterface>(callback_object); + } - explicit V8TestLegacyCallbackInterface( - v8::Local<v8::Object> callback_object, - v8::Local<v8::Context> callback_object_creation_context) - : CallbackInterfaceBase(callback_object, callback_object_creation_context, + explicit V8TestLegacyCallbackInterface(v8::Local<v8::Object> callback_object) + : CallbackInterfaceBase(callback_object, kSingleOperation) {} ~V8TestLegacyCallbackInterface() override = default;
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc index ab8da69..945ae8d 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_object.cc
@@ -5607,8 +5607,6 @@ } static void VoidMethodTestCallbackInterfaceArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { - ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodTestCallbackInterfaceArg"); - TestObject* impl = V8TestObject::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { @@ -5618,11 +5616,7 @@ V8TestCallbackInterface* test_callback_interface_arg; if (info[0]->IsObject()) { - test_callback_interface_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!test_callback_interface_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + test_callback_interface_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodTestCallbackInterfaceArg", "TestObject", "The callback provided as parameter 1 is not an object.")); return; @@ -5632,17 +5626,11 @@ } static void VoidMethodOptionalTestCallbackInterfaceArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { - ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodOptionalTestCallbackInterfaceArg"); - TestObject* impl = V8TestObject::ToImpl(info.Holder()); V8TestCallbackInterface* optional_test_callback_interface_arg; if (info[0]->IsObject()) { - optional_test_callback_interface_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!optional_test_callback_interface_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + optional_test_callback_interface_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else if (info[0]->IsUndefined()) { optional_test_callback_interface_arg = nullptr; } else { @@ -5654,8 +5642,6 @@ } static void VoidMethodTestCallbackInterfaceOrNullArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { - ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodTestCallbackInterfaceOrNullArg"); - TestObject* impl = V8TestObject::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { @@ -5665,11 +5651,7 @@ V8TestCallbackInterface* test_callback_interface_arg; if (info[0]->IsObject()) { - test_callback_interface_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!test_callback_interface_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + test_callback_interface_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else if (info[0]->IsNullOrUndefined()) { test_callback_interface_arg = nullptr; } else { @@ -5911,8 +5893,6 @@ } static void VoidMethodNodeFilterArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { - ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodNodeFilterArg"); - TestObject* impl = V8TestObject::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { @@ -5922,11 +5902,7 @@ V8NodeFilter* node_filter_arg; if (info[0]->IsObject()) { - node_filter_arg = V8NodeFilter::CreateOrNull(info[0].As<v8::Object>()); - if (!node_filter_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + node_filter_arg = V8NodeFilter::Create(info[0].As<v8::Object>()); } else { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodNodeFilterArg", "TestObject", "The callback provided as parameter 1 is not an object.")); return; @@ -7451,17 +7427,11 @@ } static void OverloadedMethodN2Method(const v8::FunctionCallbackInfo<v8::Value>& info) { - ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "overloadedMethodN"); - TestObject* impl = V8TestObject::ToImpl(info.Holder()); V8TestCallbackInterface* test_callback_interface_arg; if (info[0]->IsObject()) { - test_callback_interface_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!test_callback_interface_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + test_callback_interface_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("overloadedMethodN", "TestObject", "The callback provided as parameter 1 is not an object.")); return; @@ -8659,11 +8629,7 @@ V8TestCallbackInterface* test_callback_interface_arg; if (info[0]->IsObject()) { - test_callback_interface_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!test_callback_interface_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + test_callback_interface_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else { exception_state.ThrowTypeError("The callback provided as parameter 1 is not an object."); return; @@ -8682,11 +8648,7 @@ V8TestCallbackInterface* optional_test_callback_interface_arg; if (info[0]->IsObject()) { - optional_test_callback_interface_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!optional_test_callback_interface_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + optional_test_callback_interface_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else if (info[0]->IsUndefined()) { optional_test_callback_interface_arg = nullptr; } else {
diff --git a/third_party/blink/renderer/bindings/tests/results/core/v8_test_typedefs.cc b/third_party/blink/renderer/bindings/tests/results/core/v8_test_typedefs.cc index 3b0548a..0f065b4 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/v8_test_typedefs.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/v8_test_typedefs.cc
@@ -211,8 +211,6 @@ } static void VoidMethodTestCallbackInterfaceTypeArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { - ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestTypedefs", "voidMethodTestCallbackInterfaceTypeArg"); - TestTypedefs* impl = V8TestTypedefs::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { @@ -222,11 +220,7 @@ V8TestCallbackInterface* test_callback_interface_type_arg; if (info[0]->IsObject()) { - test_callback_interface_type_arg = V8TestCallbackInterface::CreateOrNull(info[0].As<v8::Object>()); - if (!test_callback_interface_type_arg) { - exception_state.ThrowSecurityError("The callback provided as parameter 1 is a cross origin object."); - return; - } + test_callback_interface_type_arg = V8TestCallbackInterface::Create(info[0].As<v8::Object>()); } else { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodTestCallbackInterfaceTypeArg", "TestTypedefs", "The callback provided as parameter 1 is not an object.")); return;
diff --git a/third_party/blink/renderer/core/DEPS b/third_party/blink/renderer/core/DEPS index bfc6022..ce3fc32 100644 --- a/third_party/blink/renderer/core/DEPS +++ b/third_party/blink/renderer/core/DEPS
@@ -75,7 +75,7 @@ # TODO(crbug.com/838693): Test harnesses use LayerTreeView # from content instead of a fake WebLayerTreeView implementation, so # that the Web abstraction can go away. - "+content/renderer/gpu", + "+content/renderer/compositor", "+content/test", "+third_party/blink/renderer/core/frame/web_local_frame_impl.h", "+third_party/blink/renderer/core/frame/web_remote_frame_impl.h",
diff --git a/third_party/blink/renderer/core/css/css_style_sheet.cc b/third_party/blink/renderer/core/css/css_style_sheet.cc index eba4085..1e1674bf 100644 --- a/third_party/blink/renderer/core/css/css_style_sheet.cc +++ b/third_party/blink/renderer/core/css/css_style_sheet.cc
@@ -21,6 +21,8 @@ #include "third_party/blink/renderer/core/css/css_style_sheet.h" #include "third_party/blink/renderer/bindings/core/v8/media_list_or_string.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/core/css/css_import_rule.h" #include "third_party/blink/renderer/core/css/css_rule_list.h" @@ -41,6 +43,7 @@ #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/core/svg/svg_style_element.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" @@ -93,6 +96,12 @@ } CSSStyleSheet* CSSStyleSheet::Create(Document& document, + ExceptionState& exception_state) { + return CSSStyleSheet::Create(document, CSSStyleSheetInit::Create(), + exception_state); +} + +CSSStyleSheet* CSSStyleSheet::Create(Document& document, const CSSStyleSheetInit* options, ExceptionState& exception_state) { if (!RuntimeEnabledFeatures::ConstructableStylesheetsEnabled()) { @@ -104,9 +113,12 @@ CSSParserContext* parser_context = CSSParserContext::Create(document); StyleSheetContents* contents = StyleSheetContents::Create(parser_context); CSSStyleSheet* sheet = MakeGarbageCollected<CSSStyleSheet>(contents, nullptr); + sheet->SetAssociatedDocument(&document); + sheet->SetIsConstructed(true); sheet->SetTitle(options->title()); sheet->ClearOwnerNode(); sheet->ClearOwnerRule(); + contents->RegisterClient(sheet); scoped_refptr<MediaQuerySet> media_query_set; if (options->media().IsString()) media_query_set = MediaQuerySet::Create(options->media().GetAsString()); @@ -328,6 +340,8 @@ if (is_inline_stylesheet_) return true; + if (is_constructed_) + return true; KURL base_url = contents_->BaseURL(); if (base_url.IsEmpty()) return true; @@ -357,6 +371,14 @@ return 0; } + if (is_constructed_ && resolver_) { + // We can't access rules on a constructed stylesheet if it's still waiting + // for some imports to load (|resolver_| is still set). + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Can't modify rules while the sheet is waiting for some @imports."); + return 0; + } DCHECK(child_rule_cssom_wrappers_.IsEmpty() || child_rule_cssom_wrappers_.size() == contents_->RuleCount()); @@ -380,6 +402,12 @@ return 0; } RuleMutationScope mutation_scope(this); + if (rule->IsImportRule() && is_constructed_) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Can't insert @import rules to a constructed stylesheet."); + return 0; + } bool success = contents_->WrapperInsertRule(rule, index); if (!success) { if (rule->IsNamespaceRule()) @@ -405,6 +433,15 @@ return; } + if (is_constructed_ && resolver_) { + // We can't access rules on a constructed stylesheet if it's still waiting + // for some imports to load (|resolver_| is still set). + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Can't modify rules while the sheet is waiting for some @imports."); + return; + } + DCHECK(child_rule_cssom_wrappers_.IsEmpty() || child_rule_cssom_wrappers_.size() == contents_->RuleCount()); @@ -455,6 +492,45 @@ return addRule(selector, style, length(), exception_state); } +ScriptPromise CSSStyleSheet::replace(ScriptState* script_state, + const String& text, + ExceptionState& exception_state) { + if (!is_constructed_) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Can't call replace on non-constructed CSSStyleSheets."); + } + // Parses the text synchronously, loads import rules asynchronously. + SetText(text, true /* allow_import_rules */, exception_state); + if (!IsLoading()) + return ScriptPromise::Cast(script_state, ToV8(this, script_state)); + resolver_ = ScriptPromiseResolver::Create(script_state); + return resolver_->Promise(); +} + +void CSSStyleSheet::replaceSync(const String& text, + ExceptionState& exception_state) { + if (!is_constructed_) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Can't call replaceSync on non-constructed CSSStyleSheets."); + } + SetText(text, false /* allow_import_rules */, exception_state); +} + +void CSSStyleSheet::ResolveReplacePromiseIfNeeded(bool load_error_occured) { + if (!resolver_) + return; + if (load_error_occured) { + resolver_->Reject(DOMException::Create(DOMExceptionCode::kNotAllowedError, + "Loading @imports failed.")); + } else { + resolver_->Resolve(this); + } + resolver_ = nullptr; + DidMutateRules(); +} + CSSRuleList* CSSStyleSheet::cssRules(ExceptionState& exception_state) { if (!CanAccessRules()) { exception_state.ThrowSecurityError("Cannot access rules"); @@ -496,6 +572,8 @@ } Document* CSSStyleSheet::OwnerDocument() const { + if (is_constructed_) + return associated_document_; const CSSStyleSheet* root = this; while (root->parentStyleSheet()) root = root->parentStyleSheet(); @@ -594,6 +672,7 @@ visitor->Trace(rule_list_cssom_wrapper_); visitor->Trace(adopted_tree_scopes_); visitor->Trace(associated_document_); + visitor->Trace(resolver_); StyleSheet::Trace(visitor); }
diff --git a/third_party/blink/renderer/core/css/css_style_sheet.h b/third_party/blink/renderer/core/css/css_style_sheet.h index 51d77f9..1695241 100644 --- a/third_party/blink/renderer/core/css/css_style_sheet.h +++ b/third_party/blink/renderer/core/css/css_style_sheet.h
@@ -44,6 +44,9 @@ class Document; class ExceptionState; class MediaQuerySet; +class ScriptPromise; +class ScriptPromiseResolver; +class ScriptState; class SecurityOrigin; class StyleSheetContents; @@ -53,6 +56,7 @@ public: static const Document* SingleOwnerDocument(const CSSStyleSheet*); + static CSSStyleSheet* Create(Document&, ExceptionState&); static CSSStyleSheet* Create(Document&, const CSSStyleSheetInit*, ExceptionState&); @@ -100,6 +104,12 @@ deleteRule(index, exception_state); } + ScriptPromise replace(ScriptState* script_state, + const String& text, + ExceptionState&); + void replaceSync(const String& text, ExceptionState&); + void ResolveReplacePromiseIfNeeded(bool load_error_occured); + // For CSSRuleList. unsigned length() const; CSSRule* item(unsigned index); @@ -195,6 +205,12 @@ bool IsAlternate() const; bool CanBeActivated(const String& current_preferrable_name) const; + void SetIsConstructed(bool is_constructed) { + is_constructed_ = is_constructed; + } + + bool IsConstructed() { return is_constructed_; } + void Trace(blink::Visitor*) override; private: @@ -235,6 +251,8 @@ bool alternate_from_constructor_ = false; bool enable_rule_access_for_inspector_ = false; + bool is_constructed_ = false; + String title_; scoped_refptr<MediaQuerySet> media_queries_; MediaQueryResultList viewport_dependent_media_query_results_; @@ -247,6 +265,7 @@ HeapHashSet<Member<TreeScope>> adopted_tree_scopes_; Member<Document> associated_document_; HashSet<AtomicString> custom_element_tag_names_; + Member<ScriptPromiseResolver> resolver_; TextPosition start_position_; Member<MediaList> media_cssom_wrapper_;
diff --git a/third_party/blink/renderer/core/css/css_style_sheet.idl b/third_party/blink/renderer/core/css/css_style_sheet.idl index 1251d19..1b4ce40 100644 --- a/third_party/blink/renderer/core/css/css_style_sheet.idl +++ b/third_party/blink/renderer/core/css/css_style_sheet.idl
@@ -21,6 +21,9 @@ // https://drafts.csswg.org/cssom/#the-cssstylesheet-interface [ + ConstructorCallWith=Document, + RaisesException=Constructor, + Constructor(optional CSSStyleSheetInit options), Exposed=Window ] interface CSSStyleSheet : StyleSheet { readonly attribute CSSRule? ownerRule; @@ -28,6 +31,9 @@ [RaisesException] unsigned long insertRule(DOMString rule, optional unsigned long index = 0); [RaisesException] void deleteRule(unsigned long index); + [RuntimeEnabled=ConstructableStylesheets, CallWith=ScriptState, RaisesException] Promise<CSSStyleSheet> replace(DOMString text); + [RuntimeEnabled=ConstructableStylesheets, RaisesException] void replaceSync(DOMString text); + // Non-standard APIs [MeasureAs=CSSStyleSheetRules, RaisesException] readonly attribute CSSRuleList rules; [MeasureAs=CSSStyleSheetAddRule, RaisesException] long addRule([Default=Undefined] optional DOMString selector, [Default=Undefined] optional DOMString style, optional unsigned long index);
diff --git a/third_party/blink/renderer/core/css/css_style_sheet_test.cc b/third_party/blink/renderer/core/css/css_style_sheet_test.cc index 3cdf716..31fc8cea 100644 --- a/third_party/blink/renderer/core/css/css_style_sheet_test.cc +++ b/third_party/blink/renderer/core/css/css_style_sheet_test.cc
@@ -80,114 +80,4 @@ ASSERT_FALSE(exception_state.HadException()); } -TEST_F(CSSStyleSheetTest, CreateEmptyCSSStyleSheetWithEmptyCSSStyleSheetInit) { - V8TestingScope scope; - DummyExceptionStateForTesting exception_state; - CSSStyleSheet* sheet = GetDocument().createEmptyCSSStyleSheet( - scope.GetScriptState(), CSSStyleSheetInit::Create(), exception_state); - ASSERT_FALSE(exception_state.HadException()); - EXPECT_TRUE(sheet->href().IsNull()); - EXPECT_EQ(sheet->parentStyleSheet(), nullptr); - EXPECT_EQ(sheet->ownerNode(), nullptr); - EXPECT_EQ(sheet->ownerRule(), nullptr); - EXPECT_EQ(sheet->media()->length(), 0U); - EXPECT_EQ(sheet->title(), StringImpl::empty_); - EXPECT_FALSE(sheet->AlternateFromConstructor()); - EXPECT_FALSE(sheet->disabled()); - EXPECT_EQ(sheet->cssRules(exception_state)->length(), 0U); - ASSERT_FALSE(exception_state.HadException()); -} - -TEST_F(CSSStyleSheetTest, - CreateEmptyCSSStyleSheetWithNonEmptyCSSStyleSheetInit) { - CSSStyleSheetInit* init = CSSStyleSheetInit::Create(); - init->setMedia(MediaListOrString::FromString("screen, print")); - init->setTitle("test"); - init->setAlternate(true); - init->setDisabled(true); - V8TestingScope scope; - DummyExceptionStateForTesting exception_state; - CSSStyleSheet* sheet = GetDocument().createEmptyCSSStyleSheet( - scope.GetScriptState(), init, exception_state); - ASSERT_FALSE(exception_state.HadException()); - EXPECT_TRUE(sheet->href().IsNull()); - EXPECT_EQ(sheet->parentStyleSheet(), nullptr); - EXPECT_EQ(sheet->ownerNode(), nullptr); - EXPECT_EQ(sheet->ownerRule(), nullptr); - EXPECT_EQ(sheet->media()->length(), 2U); - EXPECT_EQ(sheet->media()->mediaText(), init->media().GetAsString()); - EXPECT_EQ(sheet->title(), init->title()); - EXPECT_TRUE(sheet->AlternateFromConstructor()); - EXPECT_TRUE(sheet->disabled()); - ASSERT_FALSE(exception_state.HadException()); -} - -TEST_F(CSSStyleSheetTest, - CreateCSSStyleSheetWithEmptyCSSStyleSheetInitAndText) { - V8TestingScope scope; - DummyExceptionStateForTesting exception_state; - ScriptPromise promise = GetDocument().createCSSStyleSheet( - scope.GetScriptState(), "", CSSStyleSheetInit::Create(), exception_state); - EXPECT_FALSE(promise.IsEmpty()); - ASSERT_FALSE(exception_state.HadException()); - ScriptValue on_fulfilled, on_rejected; - promise.Then( - FunctionForTest::CreateFunction(scope.GetScriptState(), &on_fulfilled), - FunctionForTest::CreateFunction(scope.GetScriptState(), &on_rejected)); - - v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate()); - CSSStyleSheet* sheet = V8CSSStyleSheet::ToImplWithTypeCheck( - scope.GetIsolate(), on_fulfilled.V8Value()); - EXPECT_TRUE(sheet->href().IsNull()); - EXPECT_EQ(sheet->parentStyleSheet(), nullptr); - EXPECT_EQ(sheet->ownerNode(), nullptr); - EXPECT_EQ(sheet->ownerRule(), nullptr); - EXPECT_EQ(sheet->media()->length(), 0U); - EXPECT_EQ(sheet->title(), StringImpl::empty_); - EXPECT_FALSE(sheet->AlternateFromConstructor()); - EXPECT_FALSE(sheet->disabled()); - EXPECT_EQ(sheet->cssRules(exception_state)->length(), 0U); - ASSERT_FALSE(exception_state.HadException()); -} - -TEST_F(CSSStyleSheetTest, - CreateCSSStyleSheetWithNonEmptyCSSStyleSheetInitAndText) { - String styleText[2] = {".red { color: red; }", - ".red + span + span { color: red; }"}; - CSSStyleSheetInit* init = CSSStyleSheetInit::Create(); - init->setMedia(MediaListOrString::FromString("screen, print")); - init->setTitle("test"); - init->setAlternate(true); - init->setDisabled(true); - V8TestingScope scope; - DummyExceptionStateForTesting exception_state; - ScriptPromise promise = GetDocument().createCSSStyleSheet( - scope.GetScriptState(), styleText[0] + styleText[1], init, - exception_state); - EXPECT_FALSE(promise.IsEmpty()); - ASSERT_FALSE(exception_state.HadException()); - ScriptValue on_fulfilled, on_rejected; - promise.Then( - FunctionForTest::CreateFunction(scope.GetScriptState(), &on_fulfilled), - FunctionForTest::CreateFunction(scope.GetScriptState(), &on_rejected)); - - v8::MicrotasksScope::PerformCheckpoint(scope.GetIsolate()); - CSSStyleSheet* sheet = V8CSSStyleSheet::ToImplWithTypeCheck( - scope.GetIsolate(), on_fulfilled.V8Value()); - - EXPECT_TRUE(sheet->href().IsNull()); - EXPECT_EQ(sheet->parentStyleSheet(), nullptr); - EXPECT_EQ(sheet->ownerNode(), nullptr); - EXPECT_EQ(sheet->ownerRule(), nullptr); - EXPECT_EQ(sheet->media()->length(), 2U); - EXPECT_EQ(sheet->media()->mediaText(), init->media().GetAsString()); - EXPECT_EQ(sheet->title(), init->title()); - EXPECT_TRUE(sheet->AlternateFromConstructor()); - EXPECT_TRUE(sheet->disabled()); - EXPECT_EQ(sheet->cssRules(exception_state)->length(), 2U); - EXPECT_EQ(sheet->cssRules(exception_state)->item(0)->cssText(), styleText[0]); - EXPECT_EQ(sheet->cssRules(exception_state)->item(1)->cssText(), styleText[1]); - ASSERT_FALSE(exception_state.HadException()); -} - } // namespace blink
diff --git a/third_party/blink/renderer/core/css/resolver/element_style_resources.cc b/third_party/blink/renderer/core/css/resolver/element_style_resources.cc index 8cf83d11..1ad8fc1 100644 --- a/third_party/blink/renderer/core/css/resolver/element_style_resources.cc +++ b/third_party/blink/renderer/core/css/resolver/element_style_resources.cc
@@ -108,8 +108,8 @@ if (value.IsLocal(element_->GetDocument())) { SVGTreeScopeResources& tree_scope_resources = tree_scope.EnsureSVGTreeScopedResources(); - AtomicString decoded_fragment( - DecodeURLEscapeSequences(value.FragmentIdentifier())); + AtomicString decoded_fragment(DecodeURLEscapeSequences( + value.FragmentIdentifier(), DecodeURLMode::kUTF8OrIsomorphic)); return tree_scope_resources.ResourceForId(decoded_fragment); } if (allow_external == kAllowExternalResource)
diff --git a/third_party/blink/renderer/core/css/style_sheet_contents.cc b/third_party/blink/renderer/core/css/style_sheet_contents.cc index 28a2e179..8ac62e91 100644 --- a/third_party/blink/renderer/core/css/style_sheet_contents.cc +++ b/third_party/blink/renderer/core/css/style_sheet_contents.cc
@@ -426,6 +426,12 @@ if (loading_clients[i]->LoadCompleted()) continue; + if (loading_clients[i]->IsConstructed()) { + // Resolve the promise for CSSStyleSheet.replace calls. + loading_clients[i]->ResolveReplacePromiseIfNeeded(did_load_error_occur_); + continue; + } + // sheetLoaded might be invoked after its owner node is removed from // document. if (Node* owner_node = loading_clients[i]->ownerNode()) { @@ -552,7 +558,6 @@ void StyleSheetContents::RegisterClient(CSSStyleSheet* sheet) { DCHECK(!loading_clients_.Contains(sheet)); DCHECK(!completed_clients_.Contains(sheet)); - // InspectorCSSAgent::BuildObjectForRule creates CSSStyleSheet without any // owner node. if (!sheet->OwnerDocument())
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index bf77ab1..044a538 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -51,7 +51,6 @@ #include "third_party/blink/public/platform/web_prerendering_support.h" #include "third_party/blink/renderer/bindings/core/v8/html_script_element_or_svg_script_element.h" #include "third_party/blink/renderer/bindings/core/v8/script_controller.h" -#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/bindings/core/v8/source_location.h" #include "third_party/blink/renderer/bindings/core/v8/string_or_element_creation_options.h" @@ -69,7 +68,6 @@ #include "third_party/blink/renderer/core/css/css_property_value_set.h" #include "third_party/blink/renderer/core/css/css_style_declaration.h" #include "third_party/blink/renderer/core/css/css_style_sheet.h" -#include "third_party/blink/renderer/core/css/css_style_sheet_init.h" #include "third_party/blink/renderer/core/css/cssom/computed_style_property_map.h" #include "third_party/blink/renderer/core/css/font_face_set_document.h" #include "third_party/blink/renderer/core/css/invalidation/style_invalidator.h" @@ -255,7 +253,6 @@ #include "third_party/blink/renderer/core/timing/window_performance.h" #include "third_party/blink/renderer/core/trustedtypes/trusted_html.h" #include "third_party/blink/renderer/core/trustedtypes/trusted_url.h" -#include "third_party/blink/renderer/core/workers/shared_worker_repository_client.h" #include "third_party/blink/renderer/core/xml/parser/xml_document_parser.h" #include "third_party/blink/renderer/core/xml_names.h" #include "third_party/blink/renderer/core/xmlns_names.h" @@ -1132,63 +1129,6 @@ flags, is); } -ScriptPromise Document::createCSSStyleSheet(ScriptState* script_state, - const String& text, - ExceptionState& exception_state) { - return Document::createCSSStyleSheet( - script_state, text, CSSStyleSheetInit::Create(), exception_state); -} - -ScriptPromise Document::createCSSStyleSheet(ScriptState* script_state, - const String& text, - const CSSStyleSheetInit* options, - ExceptionState& exception_state) { - // Even though this function returns a Promise, it actually does all the work - // at once here because CSS parsing is done synchronously on the main thread. - // TODO(rakina): Find a way to improve this. - CSSStyleSheet* sheet = CSSStyleSheet::Create(*this, options, exception_state); - sheet->SetText(text, true /* allow_import_rules */, exception_state); - sheet->SetAssociatedDocument(this); - return ScriptPromise::Cast(script_state, ToV8(sheet, script_state)); -} - -CSSStyleSheet* Document::createCSSStyleSheetSync( - ScriptState* script_state, - const String& text, - ExceptionState& exception_state) { - return Document::createCSSStyleSheetSync( - script_state, text, CSSStyleSheetInit::Create(), exception_state); -} - -CSSStyleSheet* Document::createCSSStyleSheetSync( - ScriptState* script_state, - const String& text, - const CSSStyleSheetInit* options, - ExceptionState& exception_state) { - CSSStyleSheet* sheet = CSSStyleSheet::Create(*this, options, exception_state); - sheet->SetText(text, false /* allow_import_rules */, exception_state); - if (exception_state.HadException()) - return nullptr; - sheet->SetAssociatedDocument(this); - return sheet; -} - -CSSStyleSheet* Document::createEmptyCSSStyleSheet( - ScriptState* script_state, - const CSSStyleSheetInit* options, - ExceptionState& exception_state) { - CSSStyleSheet* sheet = CSSStyleSheet::Create(*this, options, exception_state); - sheet->SetAssociatedDocument(this); - return sheet; -} - -CSSStyleSheet* Document::createEmptyCSSStyleSheet( - ScriptState* script_state, - ExceptionState& exception_state) { - return Document::createEmptyCSSStyleSheet( - script_state, CSSStyleSheetInit::Create(), exception_state); -} - ScriptValue Document::registerElement(ScriptState* script_state, const AtomicString& name, const ElementRegistrationOptions* options, @@ -2836,9 +2776,6 @@ GetPage()->DocumentDetached(this); probe::documentDetached(this); - if (frame_->Client()->GetSharedWorkerRepositoryClient()) - frame_->Client()->GetSharedWorkerRepositoryClient()->DocumentDetached(this); - // FIXME: consider using PausableObject. if (scripted_animation_controller_) scripted_animation_controller_->ClearDocumentPointer();
diff --git a/third_party/blink/renderer/core/dom/document.h b/third_party/blink/renderer/core/dom/document.h index 089ee7c..12eaadbe 100644 --- a/third_party/blink/renderer/core/dom/document.h +++ b/third_party/blink/renderer/core/dom/document.h
@@ -89,7 +89,6 @@ class Attr; class CDATASection; class CSSStyleSheet; -class CSSStyleSheetInit; class CanvasFontCache; class ChromeClient; class Comment; @@ -160,7 +159,6 @@ class ResizeObserverController; class ResourceFetcher; class RootScrollerController; -class ScriptPromise; class ScriptValue; class SVGDocumentExtensions; class SVGUseElement; @@ -349,30 +347,6 @@ Element* CreateRawElement(const QualifiedName&, const CreateElementFlags = CreateElementFlags()); - CSSStyleSheet* createEmptyCSSStyleSheet(ScriptState*, - const CSSStyleSheetInit*, - ExceptionState&); - - CSSStyleSheet* createEmptyCSSStyleSheet(ScriptState*, ExceptionState&); - - ScriptPromise createCSSStyleSheet(ScriptState*, - const String&, - ExceptionState&); - - ScriptPromise createCSSStyleSheet(ScriptState*, - const String&, - const CSSStyleSheetInit*, - ExceptionState&); - - CSSStyleSheet* createCSSStyleSheetSync(ScriptState*, - const String&, - const CSSStyleSheetInit*, - ExceptionState&); - - CSSStyleSheet* createCSSStyleSheetSync(ScriptState*, - const String&, - ExceptionState&); - Element* ElementFromPoint(double x, double y) const; HeapVector<Member<Element>> ElementsFromPoint(double x, double y) const; Range* caretRangeFromPoint(int x, int y);
diff --git a/third_party/blink/renderer/core/dom/document.idl b/third_party/blink/renderer/core/dom/document.idl index c82681f4..d0fb671 100644 --- a/third_party/blink/renderer/core/dom/document.idl +++ b/third_party/blink/renderer/core/dom/document.idl
@@ -74,11 +74,6 @@ [NewObject] Range createRange(); - [CallWith=ScriptState, NewObject, RaisesException, RuntimeEnabled=ConstructableStylesheets] Promise<CSSStyleSheet> createCSSStyleSheet(DOMString text, optional CSSStyleSheetInit options); - [CallWith=ScriptState, NewObject, RaisesException, RuntimeEnabled=ConstructableStylesheets] CSSStyleSheet createCSSStyleSheetSync(DOMString text, optional CSSStyleSheetInit options); - [CallWith=ScriptState, NewObject, RaisesException, RuntimeEnabled=ConstructableStylesheets] CSSStyleSheet createEmptyCSSStyleSheet(optional CSSStyleSheetInit options); - - // NodeFilter.SHOW_ALL = 0xFFFFFFFF [NewObject] NodeIterator createNodeIterator(Node root, optional unsigned long whatToShow = 0xFFFFFFFF, optional NodeFilter? filter = null); [NewObject] TreeWalker createTreeWalker(Node root, optional unsigned long whatToShow = 0xFFFFFFFF, optional NodeFilter? filter = null);
diff --git a/third_party/blink/renderer/core/dom/tree_scope.cc b/third_party/blink/renderer/core/dom/tree_scope.cc index 1c64558..baa51c8 100644 --- a/third_party/blink/renderer/core/dom/tree_scope.cc +++ b/third_party/blink/renderer/core/dom/tree_scope.cc
@@ -354,24 +354,18 @@ adopted_style_sheets ? adopted_style_sheets->length() : 0; for (unsigned i = 0; i < style_sheets_count; ++i) { CSSStyleSheet* style_sheet = ToCSSStyleSheet(adopted_style_sheets->item(i)); + if (!style_sheet->IsConstructed()) { + exception_state.ThrowDOMException( + DOMExceptionCode::kNotAllowedError, + "Can't adopt non-constructed stylesheets."); + } Document* associated_document = style_sheet->AssociatedDocument(); - Node* owner_node = style_sheet->ownerNode(); if (associated_document && *associated_document != GetDocument()) { exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError, - "Sharing constructable stylesheets in " + "Sharing constructed stylesheets in " "multiple documents is not allowed"); return; } - if (owner_node && owner_node->GetDocument() != GetDocument()) { - exception_state.ThrowDOMException( - DOMExceptionCode::kNotAllowedError, - "When the style sheet's owner node and the AdoptedStyleSheets' tree " - "scope is not in the same Document tree, adding non-constructed " - "stylesheets to AdoptedStyleSheets is not allowed"); - return; - } - // TODO(momon): Don't allow using non-constructed stylesheets, pending - // resolution of https://github.com/WICG/construct-stylesheets/issues/34 } SetAdoptedStyleSheets(adopted_style_sheets); }
diff --git a/third_party/blink/renderer/core/exported/BUILD.gn b/third_party/blink/renderer/core/exported/BUILD.gn index 6b0519c..d2a515fa 100644 --- a/third_party/blink/renderer/core/exported/BUILD.gn +++ b/third_party/blink/renderer/core/exported/BUILD.gn
@@ -7,8 +7,6 @@ sources = [ "local_frame_client_impl.cc", "local_frame_client_impl.h", - "shared_worker_repository_client_impl.cc", - "shared_worker_repository_client_impl.h", "web_array_buffer.cc", "web_array_buffer_converter.cc", "web_associated_url_loader_impl.cc",
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl.cc b/third_party/blink/renderer/core/exported/local_frame_client_impl.cc index 1ee3401..796789d0 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl.cc
@@ -66,7 +66,6 @@ #include "third_party/blink/renderer/core/events/current_input_event.h" #include "third_party/blink/renderer/core/events/message_event.h" #include "third_party/blink/renderer/core/events/mouse_event.h" -#include "third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.h" #include "third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h" #include "third_party/blink/renderer/core/exported/web_document_loader_impl.h" #include "third_party/blink/renderer/core/exported/web_plugin_container_impl.h" @@ -949,11 +948,6 @@ return web_frame_->GetContentSettingsClient(); } -SharedWorkerRepositoryClient* -LocalFrameClientImpl::GetSharedWorkerRepositoryClient() { - return web_frame_->SharedWorkerRepositoryClient(); -} - std::unique_ptr<WebApplicationCacheHost> LocalFrameClientImpl::CreateApplicationCacheHost( WebApplicationCacheHostClient* client) {
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl.h b/third_party/blink/renderer/core/exported/local_frame_client_impl.h index 518e9b24..f831f58 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl.h +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl.h
@@ -222,8 +222,6 @@ override; WebContentSettingsClient* GetContentSettingsClient() override; - SharedWorkerRepositoryClient* GetSharedWorkerRepositoryClient() override; - std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( WebApplicationCacheHostClient*) override;
diff --git a/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc b/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc deleted file mode 100644 index 3b3b7eb..0000000 --- a/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.cc +++ /dev/null
@@ -1,181 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.h" - -#include <memory> -#include <utility> -#include "services/service_manager/public/cpp/interface_provider.h" -#include "third_party/blink/public/mojom/worker/shared_worker_info.mojom-blink.h" -#include "third_party/blink/public/platform/web_content_security_policy.h" -#include "third_party/blink/public/platform/web_string.h" -#include "third_party/blink/public/platform/web_url.h" -#include "third_party/blink/public/web/blink.h" -#include "third_party/blink/public/web/web_shared_worker.h" -#include "third_party/blink/renderer/core/dom/events/event.h" -#include "third_party/blink/renderer/core/execution_context/execution_context.h" -#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" -#include "third_party/blink/renderer/core/frame/use_counter.h" -#include "third_party/blink/renderer/core/probe/core_probes.h" -#include "third_party/blink/renderer/core/workers/shared_worker.h" -#include "third_party/blink/renderer/platform/loader/fetch/resource_response.h" - -namespace blink { -namespace { - -mojom::SharedWorkerCreationContextType ToCreationContextType( - bool is_secure_context) { - return is_secure_context ? mojom::SharedWorkerCreationContextType::kSecure - : mojom::SharedWorkerCreationContextType::kNonsecure; -} - -} // namespace - -// This is the client implementation to ServiceWorkerConnectorImpl in the -// browser process. This will be destructed when the owner document is -// destroyed. -// TODO(nhiroki): Move this class into its own file. -class SharedWorkerConnectListener final - : public mojom::blink::SharedWorkerClient { - public: - explicit SharedWorkerConnectListener(SharedWorker* worker) - : worker_(worker) {} - - ~SharedWorkerConnectListener() override { - // We have lost our connection to the worker. If this happens before - // Connected() is called, then it suggests that the document is gone or - // going away. - } - - // mojom::blink::SharedWorkerClient overrides. - void OnCreated( - mojom::SharedWorkerCreationContextType creation_context_type) override { - worker_->SetIsBeingConnected(true); - - // No nested workers (for now) - connect() can only be called from a - // document context. - DCHECK(worker_->GetExecutionContext()->IsDocument()); - DCHECK_EQ(creation_context_type, - ToCreationContextType( - worker_->GetExecutionContext()->IsSecureContext())); - } - - void OnConnected(const Vector<mojom::WebFeature>& features_used) override { - worker_->SetIsBeingConnected(false); - for (auto feature : features_used) - OnFeatureUsed(feature); - } - - void OnScriptLoadFailed() override { - worker_->DispatchEvent(*Event::CreateCancelable(event_type_names::kError)); - worker_->SetIsBeingConnected(false); - } - - void OnFeatureUsed(mojom::WebFeature feature) override { - UseCounter::Count(worker_->GetExecutionContext(), feature); - } - - Persistent<SharedWorker> worker_; -}; - -void SharedWorkerRepositoryClientImpl::Connect( - SharedWorker* worker, - MessagePortChannel port, - const KURL& url, - mojom::blink::BlobURLTokenPtr blob_url_token, - const String& name) { - DCHECK(!name.IsNull()); - - // Lazily bind the connector. - if (!connector_) - interface_provider_->GetInterface(mojo::MakeRequest(&connector_)); - - // TODO(estark): this is broken, as it only uses the first header - // when multiple might have been sent. Fix by making the - // mojom::blink::SharedWorkerInfo take a map that can contain multiple - // headers. - Vector<CSPHeaderAndType> headers = - worker->GetExecutionContext()->GetContentSecurityPolicy()->Headers(); - WebString header = ""; - auto header_type = mojom::ContentSecurityPolicyType::kReport; - if (headers.size() > 0) { - header = headers[0].first; - header_type = - static_cast<mojom::ContentSecurityPolicyType>(headers[0].second); - } - - mojom::blink::SharedWorkerInfoPtr info(mojom::blink::SharedWorkerInfo::New( - url, name, header, header_type, - worker->GetExecutionContext()->GetSecurityContext().AddressSpace())); - - // No nested workers (for now) - connect() can only be called from a document - // context. - Document* document = To<Document>(worker->GetExecutionContext()); - mojom::blink::SharedWorkerClientPtr client_ptr; - AddWorker(document, std::make_unique<SharedWorkerConnectListener>(worker), - mojo::MakeRequest(&client_ptr)); - - connector_->Connect( - std::move(info), std::move(client_ptr), - ToCreationContextType(worker->GetExecutionContext()->IsSecureContext()), - port.ReleaseHandle(), - mojom::blink::BlobURLTokenPtr(mojom::blink::BlobURLTokenPtrInfo( - blob_url_token.PassInterface().PassHandle(), - mojom::blink::BlobURLToken::Version_))); -} - -void SharedWorkerRepositoryClientImpl::DocumentDetached(Document* document) { - // Delete any associated SharedWorkerConnectListeners, which will signal, via - // the dropped mojo connection, disinterest in the associated shared worker. - client_map_.erase(GetId(document)); -} - -SharedWorkerRepositoryClientImpl::SharedWorkerRepositoryClientImpl( - service_manager::InterfaceProvider* interface_provider) - : interface_provider_(interface_provider) {} - -void SharedWorkerRepositoryClientImpl::AddWorker( - Document* document, - std::unique_ptr<mojom::blink::SharedWorkerClient> client, - mojom::blink::SharedWorkerClientRequest request) { - const auto& result = client_map_.insert(GetId(document), nullptr); - std::unique_ptr<ClientSet>& clients = result.stored_value->value; - if (!clients) - clients = std::make_unique<ClientSet>(); - clients->AddBinding(std::move(client), std::move(request)); -} - -SharedWorkerRepositoryClientImpl::DocumentID -SharedWorkerRepositoryClientImpl::GetId(Document* document) { - DCHECK(document); - return reinterpret_cast<DocumentID>(document); -} - -} // namespace blink
diff --git a/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.h b/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.h deleted file mode 100644 index 2763aaa..0000000 --- a/third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.h +++ /dev/null
@@ -1,98 +0,0 @@ -/* - * Copyright (C) 2013 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_SHARED_WORKER_REPOSITORY_CLIENT_IMPL_H_ -#define THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_SHARED_WORKER_REPOSITORY_CLIENT_IMPL_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/memory/scoped_refptr.h" -#include "mojo/public/cpp/bindings/strong_binding_set.h" -#include "third_party/blink/public/mojom/worker/shared_worker_client.mojom-blink.h" -#include "third_party/blink/public/mojom/worker/shared_worker_connector.mojom-blink.h" -#include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/core/workers/shared_worker_repository_client.h" - -namespace service_manager { -class InterfaceProvider; -} // namespace service_manager - -namespace blink { - -// TODO(nhiroki): Merge this file into -// core/workers/shared_worker_repository_client.h. -class CORE_EXPORT SharedWorkerRepositoryClientImpl final - : public SharedWorkerRepositoryClient { - USING_FAST_MALLOC(SharedWorkerRepositoryClientImpl); - - public: - static std::unique_ptr<SharedWorkerRepositoryClientImpl> Create( - service_manager::InterfaceProvider* interface_provider) { - return base::WrapUnique( - new SharedWorkerRepositoryClientImpl(interface_provider)); - } - - ~SharedWorkerRepositoryClientImpl() override = default; - - void Connect(SharedWorker*, - MessagePortChannel, - const KURL&, - mojom::blink::BlobURLTokenPtr, - const String& name) override; - void DocumentDetached(Document*) override; - - private: - explicit SharedWorkerRepositoryClientImpl( - service_manager::InterfaceProvider*); - - void AddWorker(Document* document, - std::unique_ptr<mojom::blink::SharedWorkerClient> client, - mojom::blink::SharedWorkerClientRequest request); - - // Unique identifier for the parent document of a worker (unique within a - // given process). - using DocumentID = unsigned long long; - static DocumentID GetId(Document*); - - service_manager::InterfaceProvider* interface_provider_; - mojom::blink::SharedWorkerConnectorPtr connector_; - - using ClientSet = mojo::StrongBindingSet<mojom::blink::SharedWorkerClient>; - using ClientMap = HashMap<DocumentID, std::unique_ptr<ClientSet>>; - ClientMap client_map_; - - DISALLOW_COPY_AND_ASSIGN(SharedWorkerRepositoryClientImpl); -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EXPORTED_SHARED_WORKER_REPOSITORY_CLIENT_IMPL_H_
diff --git a/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc b/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc index 03ff89c..3def816 100644 --- a/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc +++ b/third_party/blink/renderer/core/exported/web_plugin_container_impl.cc
@@ -547,7 +547,8 @@ const KURL& kurl = url; DCHECK(kurl.ProtocolIs("javascript")); - String script = DecodeURLEscapeSequences(kurl.GetString()); + String script = DecodeURLEscapeSequences(kurl.GetString(), + DecodeURLMode::kUTF8OrIsomorphic); if (!element_->GetDocument().GetContentSecurityPolicy()->AllowJavaScriptURLs( element_, script, element_->GetDocument().Url(), OrdinalNumber())) {
diff --git a/third_party/blink/renderer/core/fileapi/file.cc b/third_party/blink/renderer/core/fileapi/file.cc index 22cfc783..45d9c51 100644 --- a/third_party/blink/renderer/core/fileapi/file.cc +++ b/third_party/blink/renderer/core/fileapi/file.cc
@@ -232,7 +232,8 @@ metadata.length)), has_backing_file_(false), user_visibility_(user_visibility), - name_(DecodeURLEscapeSequences(file_system_url.LastPathComponent())), + name_(DecodeURLEscapeSequences(file_system_url.LastPathComponent(), + DecodeURLMode::kUTF8OrIsomorphic)), file_system_url_(file_system_url), snapshot_size_(metadata.length), snapshot_modification_time_ms_(metadata.modification_time) {}
diff --git a/third_party/blink/renderer/core/frame/csp/content_security_policy.cc b/third_party/blink/renderer/core/frame/csp/content_security_policy.cc index 2242204..e28b9a4 100644 --- a/third_party/blink/renderer/core/frame/csp/content_security_policy.cc +++ b/third_party/blink/renderer/core/frame/csp/content_security_policy.cc
@@ -1649,7 +1649,7 @@ if (!context) return false; - v8::Isolate* isolate = ToIsolate(context); + v8::Isolate* isolate = context->GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Context> v8_context = isolate->GetCurrentContext(); if (v8_context.IsEmpty())
diff --git a/third_party/blink/renderer/core/frame/csp/csp_source.cc b/third_party/blink/renderer/core/frame/csp/csp_source.cc index 5bd52a44..5d41751d 100644 --- a/third_party/blink/renderer/core/frame/csp/csp_source.cc +++ b/third_party/blink/renderer/core/frame/csp/csp_source.cc
@@ -146,7 +146,8 @@ if (path_.IsEmpty() || (path_ == "/" && url_path.IsEmpty())) return true; - String path = DecodeURLEscapeSequences(url_path); + String path = + DecodeURLEscapeSequences(url_path, DecodeURLMode::kUTF8OrIsomorphic); if (path_.EndsWith("/")) return path.StartsWith(path_);
diff --git a/third_party/blink/renderer/core/frame/csp/source_list_directive.cc b/third_party/blink/renderer/core/frame/csp/source_list_directive.cc index b2c776b..273ee814 100644 --- a/third_party/blink/renderer/core/frame/csp/source_list_directive.cc +++ b/third_party/blink/renderer/core/frame/csp/source_list_directive.cc
@@ -568,7 +568,8 @@ } *path = DecodeURLEscapeSequences( - String(begin, static_cast<wtf_size_t>(position - begin))); + String(begin, static_cast<wtf_size_t>(position - begin)), + DecodeURLMode::kUTF8OrIsomorphic); DCHECK(position <= end); DCHECK(position == end || (*position == '#' || *position == '?'));
diff --git a/third_party/blink/renderer/core/frame/frame_test_helpers.h b/third_party/blink/renderer/core/frame/frame_test_helpers.h index 6dfc63b..4e5009c8 100644 --- a/third_party/blink/renderer/core/frame/frame_test_helpers.h +++ b/third_party/blink/renderer/core/frame/frame_test_helpers.h
@@ -38,7 +38,7 @@ #include "base/macros.h" #include "cc/test/test_task_graph_runner.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/test/stub_layer_tree_view_delegate.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/blink/public/common/frame/frame_owner_element_type.h"
diff --git a/third_party/blink/renderer/core/frame/local_frame_client.h b/third_party/blink/renderer/core/frame/local_frame_client.h index 9f97e49..b335603 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client.h +++ b/third_party/blink/renderer/core/frame/local_frame_client.h
@@ -91,7 +91,6 @@ class ResourceRequest; class ResourceResponse; class SecurityOrigin; -class SharedWorkerRepositoryClient; class SubstituteData; class WebApplicationCacheHost; class WebApplicationCacheHostClient; @@ -343,10 +342,6 @@ virtual WebContentSettingsClient* GetContentSettingsClient() = 0; - virtual SharedWorkerRepositoryClient* GetSharedWorkerRepositoryClient() { - return nullptr; - } - virtual std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( WebApplicationCacheHostClient*) = 0;
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 904b8a9..9a387b8a 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -1367,55 +1367,22 @@ !frame_->GetDocument()->IsSVGDocument()) return; - UseCounter::Count(&GetFrame(), WebFeature::kScrollToFragmentRequested); // Try the raw fragment for HTML documents, but skip it for `svgView()`: String fragment_identifier = url.FragmentIdentifier(); if (!frame_->GetDocument()->IsSVGDocument() && ProcessUrlFragmentHelper(fragment_identifier, behavior)) { - UseCounter::Count(&GetFrame(), WebFeature::kScrollToFragmentSucceedWithRaw); return; } - // Try again after decoding the fragment. - if (frame_->GetDocument()->Encoding().IsValid()) { - DecodeURLResult decode_result; - if (ProcessUrlFragmentHelper( - DecodeURLEscapeSequences(fragment_identifier, &decode_result), - behavior)) { - switch (decode_result) { - case DecodeURLResult::kAsciiOnly: - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentSucceedWithASCII); - break; - case DecodeURLResult::kUTF8: - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentSucceedWithUTF8); - break; - case DecodeURLResult::kIsomorphic: - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentSucceedWithIsomorphic); - break; - } - } else { - switch (decode_result) { - case DecodeURLResult::kAsciiOnly: - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentFailWithASCII); - break; - case DecodeURLResult::kUTF8: - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentFailWithUTF8); - break; - case DecodeURLResult::kIsomorphic: - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentFailWithIsomorphic); - break; - } - } - } else { - UseCounter::Count(&GetFrame(), - WebFeature::kScrollToFragmentFailWithInvalidEncoding); - } + // https://html.spec.whatwg.org/multipage/browsing-the-web.html#the-indicated-part-of-the-document + // 5. Let decodedFragment be the result of running UTF-8 decode without BOM on + // fragmentBytes. + String decoded_fragment = + DecodeURLEscapeSequences(fragment_identifier, DecodeURLMode::kUTF8); + // 6. If find a potential indicated element with decodedFragment + // returns non-null, then the return value is the indicated part of + // the document; return. + ProcessUrlFragmentHelper(decoded_fragment, behavior); } bool LocalFrameView::ProcessUrlFragmentHelper(const String& name, @@ -2992,9 +2959,16 @@ SCOPED_UMA_AND_UKM_TIMER(EnsureUkmAggregator(), LocalFrameUkmAggregator::kCompositingCommit); + PaintArtifactCompositor::ViewportProperties viewport_properties; + viewport_properties.page_scale = page->GetVisualViewport().GetPageScaleNode(); + + PaintArtifactCompositor::Settings settings; + settings.prefer_compositing_to_lcd_text = + page->GetSettings().GetPreferCompositingToLCDTextEnabled(); + paint_artifact_compositor_->Update( paint_controller_->GetPaintArtifactShared(), composited_element_ids, - page->GetVisualViewport().GetPageScaleNode()); + viewport_properties, settings); } std::unique_ptr<JSONObject> LocalFrameView::CompositedLayersAsJSON(
diff --git a/third_party/blink/renderer/core/frame/location.cc b/third_party/blink/renderer/core/frame/location.cc index 27bc9a1..6890c71 100644 --- a/third_party/blink/renderer/core/frame/location.cc +++ b/third_party/blink/renderer/core/frame/location.cc
@@ -303,7 +303,8 @@ Document* current_document = current_window->document(); if (current_document && completed_url.ProtocolIsJavaScript() && !ContentSecurityPolicy::ShouldBypassMainWorld(current_document)) { - String script_source = DecodeURLEscapeSequences(completed_url.GetString()); + String script_source = DecodeURLEscapeSequences( + completed_url.GetString(), DecodeURLMode::kUTF8OrIsomorphic); if (!current_document->GetContentSecurityPolicy()->AllowJavaScriptURLs( nullptr, script_source, current_document->Url(), OrdinalNumber())) { return;
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index 81f3b170d..bbe55ee9 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -168,7 +168,6 @@ #include "third_party/blink/renderer/core/editing/visible_position.h" #include "third_party/blink/renderer/core/editing/writing_direction.h" #include "third_party/blink/renderer/core/exported/local_frame_client_impl.h" -#include "third_party/blink/renderer/core/exported/shared_worker_repository_client_impl.h" #include "third_party/blink/renderer/core/exported/web_associated_url_loader_impl.h" #include "third_party/blink/renderer/core/exported/web_dev_tools_agent_impl.h" #include "third_party/blink/renderer/core/exported/web_document_loader_impl.h" @@ -578,12 +577,6 @@ content_settings_client_ = client; } -void WebLocalFrameImpl::InitializeSharedWorkerRepositoryClient( - service_manager::InterfaceProvider* interface_provider) { - shared_worker_repository_client_ = - SharedWorkerRepositoryClientImpl::Create(interface_provider); -} - ScrollableArea* WebLocalFrameImpl::LayoutViewport() const { if (LocalFrameView* view = GetFrameView()) return view->LayoutViewport(); @@ -2088,7 +2081,8 @@ String script = DecodeURLEscapeSequences( static_cast<const KURL&>(url).GetString().Substring( - strlen("javascript:"))); + strlen("javascript:")), + DecodeURLMode::kUTF8OrIsomorphic); std::unique_ptr<UserGestureIndicator> gesture_indicator = LocalFrame::NotifyUserActivation(GetFrame(), UserGestureToken::kNewGesture);
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/third_party/blink/renderer/core/frame/web_local_frame_impl.h index 700bf5a8..3f359150e 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.h +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -58,7 +58,6 @@ class IntSize; class LocalFrameClientImpl; class ScrollableArea; -class SharedWorkerRepositoryClientImpl; class TextFinder; class WebAssociatedURLLoader; struct WebAssociatedURLLoaderOptions; @@ -92,8 +91,6 @@ WebString AssignedName() const override; void SetName(const WebString&) override; WebVector<WebIconURL> IconURLs(int icon_types_mask) const override; - void InitializeSharedWorkerRepositoryClient( - service_manager::InterfaceProvider*) override; WebSize GetScrollOffset() const override; void SetScrollOffset(const WebSize&) override; WebSize DocumentSize() const override; @@ -420,10 +417,6 @@ return content_settings_client_; } - SharedWorkerRepositoryClientImpl* SharedWorkerRepositoryClient() const { - return shared_worker_repository_client_.get(); - } - void SetInputEventsScaleForEmulation(float); WebTextCheckClient* GetTextCheckerClient() const { @@ -496,8 +489,6 @@ WebAutofillClient* autofill_client_; WebContentSettingsClient* content_settings_client_ = nullptr; - std::unique_ptr<SharedWorkerRepositoryClientImpl> - shared_worker_repository_client_; Member<FindInPage> find_in_page_;
diff --git a/third_party/blink/renderer/core/html/html_frame_element_base.cc b/third_party/blink/renderer/core/html/html_frame_element_base.cc index 466ad257..14734c34 100644 --- a/third_party/blink/renderer/core/html/html_frame_element_base.cc +++ b/third_party/blink/renderer/core/html/html_frame_element_base.cc
@@ -63,7 +63,7 @@ // frame. NB: This check can be invoked without any JS on the stack for some // parser operations. In such case, we use the origin of the frame element's // containing document as the caller context. - v8::Isolate* isolate = ToIsolate(&GetDocument()); + v8::Isolate* isolate = GetDocument().GetIsolate(); LocalDOMWindow* accessing_window = isolate->InContext() ? CurrentDOMWindow(isolate) : GetDocument().domWindow();
diff --git a/third_party/blink/renderer/core/html/image_document.cc b/third_party/blink/renderer/core/html/image_document.cc index 7deabda..be763ac34 100644 --- a/third_party/blink/renderer/core/html/image_document.cc +++ b/third_party/blink/renderer/core/html/image_document.cc
@@ -167,7 +167,8 @@ // Compute the title, we use the decoded filename of the resource, falling // back on the (decoded) hostname if there is no path. String file_name = - DecodeURLEscapeSequences(GetDocument()->Url().LastPathComponent()); + DecodeURLEscapeSequences(GetDocument()->Url().LastPathComponent(), + DecodeURLMode::kUTF8OrIsomorphic); if (file_name.IsEmpty()) file_name = GetDocument()->Url().Host(); GetDocument()->setTitle(ImageTitle(file_name, size));
diff --git a/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc b/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc index a9b6e63..1bdbeef 100644 --- a/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc +++ b/third_party/blink/renderer/core/html/media/media_fragment_uri_parser.cc
@@ -112,12 +112,16 @@ // a. Decode percent-encoded octets in name and value as defined by RFC // 3986. If either name or value are not valid percent-encoded strings, // then remove the name-value pair from the list. - String name = DecodeURLEscapeSequences(fragment_string.Substring( - parameter_start, equal_offset - parameter_start)); + String name = DecodeURLEscapeSequences( + fragment_string.Substring(parameter_start, + equal_offset - parameter_start), + DecodeURLMode::kUTF8OrIsomorphic); String value; if (equal_offset != parameter_end) { - value = DecodeURLEscapeSequences(fragment_string.Substring( - equal_offset + 1, parameter_end - equal_offset - 1)); + value = DecodeURLEscapeSequences( + fragment_string.Substring(equal_offset + 1, + parameter_end - equal_offset - 1), + DecodeURLMode::kUTF8OrIsomorphic); } // b. Convert name and value to Unicode strings by interpreting them as
diff --git a/third_party/blink/renderer/core/loader/form_submission.cc b/third_party/blink/renderer/core/loader/form_submission.cc index 77e931a..91cccdf 100644 --- a/third_party/blink/renderer/core/loader/form_submission.cc +++ b/third_party/blink/renderer/core/loader/form_submission.cc
@@ -70,7 +70,8 @@ // Convention seems to be to decode, and s/&/\r\n/. Also, spaces are encoded // as %20. body = DecodeURLEscapeSequences( - body.Replace('&', "\r\n").Replace('+', ' ') + "\r\n"); + body.Replace('&', "\r\n").Replace('+', ' ') + "\r\n", + DecodeURLMode::kUTF8OrIsomorphic); } Vector<char> body_data;
diff --git a/third_party/blink/renderer/core/loader/resource/script_resource.cc b/third_party/blink/renderer/core/loader/resource/script_resource.cc index 17457a31..2c8da582 100644 --- a/third_party/blink/renderer/core/loader/resource/script_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/script_resource.cc
@@ -156,7 +156,6 @@ // the assumptions are confirmed. if (IsLoaded()) { - CHECK(IsFinishedInternal()); if (!source_text_.IsNull()) { // 1. We have finished loading, and have already decoded the buffer into // the source text and cleared the resource buffer to save space. @@ -164,15 +163,19 @@ } // 2. We have finished loading with no data received, so no streaming ever - // happened or streaming was suppressed. + // happened or streaming was suppressed. Note that the finished + // notification may not have come through yet because of task posting, so + // NotifyFinished may not have been called yet. Regardless, there was no + // data, so the text should be empty. // // TODO(crbug/909858) Currently this CHECK can occasionally fail, but this // doesn't seem to cause real issues immediately. For now, we suppress the // crashes on release builds by making this a DCHECK and continue baking the // script streamer control (crbug/865098) on beta, while investigating the // failure reason on canary. - DCHECK(!streamer_ || streamer_->StreamingSuppressedReason() == - ScriptStreamer::kScriptTooSmall); + DCHECK(!IsFinishedInternal() || !streamer_ || + streamer_->StreamingSuppressedReason() == + ScriptStreamer::kScriptTooSmall); return ""; }
diff --git a/third_party/blink/renderer/core/messaging/message_port.cc b/third_party/blink/renderer/core/messaging/message_port.cc index 196ab5f..a296a04f 100644 --- a/third_party/blink/renderer/core/messaging/message_port.cc +++ b/third_party/blink/renderer/core/messaging/message_port.cc
@@ -313,7 +313,7 @@ evt = MessageEvent::CreateError(); } - v8::Isolate* isolate = ToIsolate(GetExecutionContext()); + v8::Isolate* isolate = GetExecutionContext()->GetIsolate(); ThreadDebugger* debugger = ThreadDebugger::From(isolate); if (debugger) debugger->ExternalAsyncTaskStarted(message.sender_stack_trace_id);
diff --git a/third_party/blink/renderer/core/page/create_window.cc b/third_party/blink/renderer/core/page/create_window.cc index cfc96f5..aa201c0 100644 --- a/third_party/blink/renderer/core/page/create_window.cc +++ b/third_party/blink/renderer/core/page/create_window.cc
@@ -386,7 +386,8 @@ opener_frame.GetDocument()->GetContentSecurityPolicy() && !ContentSecurityPolicy::ShouldBypassMainWorld( opener_frame.GetDocument())) { - String script_source = DecodeURLEscapeSequences(completed_url.GetString()); + String script_source = DecodeURLEscapeSequences( + completed_url.GetString(), DecodeURLMode::kUTF8OrIsomorphic); if (!opener_frame.GetDocument() ->GetContentSecurityPolicy()
diff --git a/third_party/blink/renderer/core/paint/box_painter.cc b/third_party/blink/renderer/core/paint/box_painter.cc index a6b0a5b0..251668fc 100644 --- a/third_party/blink/renderer/core/paint/box_painter.cc +++ b/third_party/blink/renderer/core/paint/box_painter.cc
@@ -95,6 +95,12 @@ } bool BoxPainter::BackgroundIsKnownToBeOpaque(const PaintInfo& paint_info) { + // If the box has multiple fragments, its VisualRect is the bounding box of + // all fragments' visual rects, which is likely to cover areas that are not + // covered by painted background. + if (layout_box_.FirstFragment().NextFragment()) + return false; + LayoutRect bounds = BoxModelObjectPainter::IsPaintingScrollingBackground( &layout_box_, paint_info) ? layout_box_.LayoutOverflowRect()
diff --git a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc index cc5519b..38f5047 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
@@ -487,6 +487,13 @@ bool NGBoxFragmentPainter::BackgroundIsKnownToBeOpaque( const PaintInfo& paint_info) { const LayoutBox& layout_box = ToLayoutBox(*box_fragment_.GetLayoutObject()); + + // If the box has multiple fragments, its VisualRect is the bounding box of + // all fragments' visual rects, which is likely to cover areas that are not + // covered by painted background. + if (layout_box.FirstFragment().NextFragment()) + return false; + LayoutRect bounds = IsPaintingScrollingBackground(box_fragment_, paint_info) ? layout_box.LayoutOverflowRect() : layout_box.SelfVisualOverflowRect();
diff --git a/third_party/blink/renderer/core/probe/core_probes.cc b/third_party/blink/renderer/core/probe/core_probes.cc index e559212..4ed6927 100644 --- a/third_party/blink/renderer/core/probe/core_probes.cc +++ b/third_party/blink/renderer/core/probe/core_probes.cc
@@ -51,7 +51,8 @@ void* task, const char* step, bool enabled) - : debugger_(enabled ? ThreadDebugger::From(ToIsolate(context)) : nullptr), + : debugger_(enabled && context ? ThreadDebugger::From(context->GetIsolate()) + : nullptr), task_(AsyncId(task)), recurring_(step) { if (recurring_) { @@ -80,8 +81,10 @@ TRACE_EVENT_FLOW_BEGIN1("devtools.timeline.async", "AsyncTask", TRACE_ID_LOCAL(reinterpret_cast<uintptr_t>(task)), "data", inspector_async_task::Data(name)); - if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) - debugger->AsyncTaskScheduled(name, AsyncId(task), true); + if (context) { + if (ThreadDebugger* debugger = ThreadDebugger::From(context->GetIsolate())) + debugger->AsyncTaskScheduled(name, AsyncId(task), true); + } } void AsyncTaskScheduledBreakable(ExecutionContext* context, @@ -92,7 +95,7 @@ } void AsyncTaskCanceled(ExecutionContext* context, void* task) { - AsyncTaskCanceled(ToIsolate(context), task); + AsyncTaskCanceled(context ? context->GetIsolate() : nullptr, task); } void AsyncTaskCanceled(v8::Isolate* isolate, void* task) { @@ -110,8 +113,10 @@ } void AllAsyncTasksCanceled(ExecutionContext* context) { - if (ThreadDebugger* debugger = ThreadDebugger::From(ToIsolate(context))) - debugger->AllAsyncTasksCanceled(); + if (context) { + if (ThreadDebugger* debugger = ThreadDebugger::From(context->GetIsolate())) + debugger->AllAsyncTasksCanceled(); + } } } // namespace probe
diff --git a/third_party/blink/renderer/core/svg/svg_resource.cc b/third_party/blink/renderer/core/svg/svg_resource.cc index bf7c8a1..d767e45 100644 --- a/third_party/blink/renderer/core/svg/svg_resource.cc +++ b/third_party/blink/renderer/core/svg/svg_resource.cc
@@ -155,8 +155,8 @@ Document* external_document = resource_document_->GetDocument(); if (!external_document) return nullptr; - AtomicString decoded_fragment( - DecodeURLEscapeSequences(url_.FragmentIdentifier())); + AtomicString decoded_fragment(DecodeURLEscapeSequences( + url_.FragmentIdentifier(), DecodeURLMode::kUTF8OrIsomorphic)); return external_document->getElementById(decoded_fragment); }
diff --git a/third_party/blink/renderer/core/svg/svg_uri_reference.cc b/third_party/blink/renderer/core/svg/svg_uri_reference.cc index 83d6e05..3f4d84ac 100644 --- a/third_party/blink/renderer/core/svg/svg_uri_reference.cc +++ b/third_party/blink/renderer/core/svg/svg_uri_reference.cc
@@ -90,8 +90,8 @@ AtomicString SVGURLReferenceResolver::FragmentIdentifier() const { // Use KURL's FragmentIdentifier to ensure that we're handling the // fragment in a consistent manner. - return AtomicString( - DecodeURLEscapeSequences(AbsoluteUrl().FragmentIdentifier())); + return AtomicString(DecodeURLEscapeSequences( + AbsoluteUrl().FragmentIdentifier(), DecodeURLMode::kUTF8OrIsomorphic)); } AtomicString SVGURIReference::FragmentIdentifierFromIRIString(
diff --git a/third_party/blink/renderer/core/svg/svg_use_element.cc b/third_party/blink/renderer/core/svg/svg_use_element.cc index 93c756fa..46096de 100644 --- a/third_party/blink/renderer/core/svg/svg_use_element.cc +++ b/third_party/blink/renderer/core/svg/svg_use_element.cc
@@ -307,8 +307,8 @@ Element* SVGUseElement::ResolveTargetElement(ObserveBehavior observe_behavior) { if (!element_url_.HasFragmentIdentifier()) return nullptr; - AtomicString element_identifier( - DecodeURLEscapeSequences(element_url_.FragmentIdentifier())); + AtomicString element_identifier(DecodeURLEscapeSequences( + element_url_.FragmentIdentifier(), DecodeURLMode::kUTF8OrIsomorphic)); if (!IsStructurallyExternal()) { if (observe_behavior == kDontAddObserver) return GetTreeScope().getElementById(element_identifier);
diff --git a/third_party/blink/renderer/core/testing/DEPS b/third_party/blink/renderer/core/testing/DEPS index 1cd6cec..982d4f4 100644 --- a/third_party/blink/renderer/core/testing/DEPS +++ b/third_party/blink/renderer/core/testing/DEPS
@@ -3,7 +3,7 @@ # TODO(crbug.com/838693): Test harnesses use LayerTreeView # from content instead of a fake WebLayerTreeView implementation, so # that the Web abstraction can go away. - "+content/renderer/gpu", + "+content/renderer/compositor", "+content/test", "+gpu/command_buffer/client/gles2_interface.h", ]
diff --git a/third_party/blink/renderer/core/testing/sim/sim_compositor.h b/third_party/blink/renderer/core/testing/sim/sim_compositor.h index 784300e..8a3b8ea 100644 --- a/third_party/blink/renderer/core/testing/sim/sim_compositor.h +++ b/third_party/blink/renderer/core/testing/sim/sim_compositor.h
@@ -7,7 +7,7 @@ #include "base/time/time.h" #include "cc/trees/layer_tree_host.h" -#include "content/renderer/gpu/layer_tree_view.h" +#include "content/renderer/compositor/layer_tree_view.h" #include "content/test/stub_layer_tree_view_delegate.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/testing/sim/sim_canvas.h"
diff --git a/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc b/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc index 068d0750e..83cbee3 100644 --- a/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc +++ b/third_party/blink/renderer/core/trustedtypes/trusted_types_util.cc
@@ -90,7 +90,7 @@ } TrustedHTML* result = default_policy->CreateHTML( - ToIsolate(doc), string_or_trusted_html.GetAsString(), exception_state); + doc->GetIsolate(), string_or_trusted_html.GetAsString(), exception_state); if (exception_state.HadException()) { exception_state.ClearException(); exception_state.ThrowTypeError( @@ -146,7 +146,7 @@ ? g_empty_string : string_or_trusted_script.GetAsString(); TrustedScript* result = default_policy->CreateScript( - ToIsolate(doc), string_value_or_empty, exception_state); + doc->GetIsolate(), string_value_or_empty, exception_state); DCHECK_EQ(!result, exception_state.HadException()); if (exception_state.HadException()) { exception_state.ClearException(); @@ -186,7 +186,7 @@ } TrustedScriptURL* result = default_policy->CreateScriptURL( - ToIsolate(doc), string_or_trusted_script_url.GetAsString(), + doc->GetIsolate(), string_or_trusted_script_url.GetAsString(), exception_state); if (exception_state.HadException()) { @@ -226,7 +226,8 @@ } TrustedURL* result = default_policy->CreateURL( - ToIsolate(doc), string_or_trusted_url.GetAsUSVString(), exception_state); + doc->GetIsolate(), string_or_trusted_url.GetAsUSVString(), + exception_state); if (exception_state.HadException()) { exception_state.ClearException(); exception_state.ThrowTypeError(
diff --git a/third_party/blink/renderer/core/url/url_search_params.cc b/third_party/blink/renderer/core/url/url_search_params.cc index 034bbe3..fd43bb8 100644 --- a/third_party/blink/renderer/core/url/url_search_params.cc +++ b/third_party/blink/renderer/core/url/url_search_params.cc
@@ -133,7 +133,8 @@ } static String DecodeString(String input) { - return DecodeURLEscapeSequences(input.Replace('+', ' ')); + return DecodeURLEscapeSequences(input.Replace('+', ' '), + DecodeURLMode::kUTF8OrIsomorphic); } void URLSearchParams::SetInputWithoutUpdate(const String& query_string) {
diff --git a/third_party/blink/renderer/core/workers/BUILD.gn b/third_party/blink/renderer/core/workers/BUILD.gn index eef62db..b9727e22 100644 --- a/third_party/blink/renderer/core/workers/BUILD.gn +++ b/third_party/blink/renderer/core/workers/BUILD.gn
@@ -41,12 +41,15 @@ "parent_execution_context_task_runners.h", "shared_worker.cc", "shared_worker.h", + "shared_worker_connect_listener.cc", + "shared_worker_connect_listener.h", "shared_worker_content_settings_proxy.cc", "shared_worker_content_settings_proxy.h", "shared_worker_global_scope.cc", "shared_worker_global_scope.h", "shared_worker_reporting_proxy.cc", "shared_worker_reporting_proxy.h", + "shared_worker_repository_client.cc", "shared_worker_repository_client.h", "shared_worker_thread.cc", "shared_worker_thread.h",
diff --git a/third_party/blink/renderer/core/workers/dedicated_worker.cc b/third_party/blink/renderer/core/workers/dedicated_worker.cc index 80101c65..59f9f76c 100644 --- a/third_party/blink/renderer/core/workers/dedicated_worker.cc +++ b/third_party/blink/renderer/core/workers/dedicated_worker.cc
@@ -164,7 +164,7 @@ DCHECK(GetExecutionContext()->IsContextThread()); v8_inspector::V8StackTraceId stack_id = - ThreadDebugger::From(ToIsolate(GetExecutionContext())) + ThreadDebugger::From(GetExecutionContext()->GetIsolate()) ->StoreCurrentStackTrace("Worker Created"); if (auto* scope = DynamicTo<WorkerGlobalScope>(*GetExecutionContext()))
diff --git a/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc b/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc index f849cba..7734b5cb 100644 --- a/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc +++ b/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
@@ -53,7 +53,7 @@ InitializeWorkerThread( std::move(creation_params), - CreateBackingThreadStartupData(ToIsolate(GetExecutionContext()))); + CreateBackingThreadStartupData(GetExecutionContext()->GetIsolate())); // Step 13: "Obtain script by switching on the value of options's type // member:" @@ -140,7 +140,7 @@ return; ThreadDebugger* debugger = - ThreadDebugger::From(ToIsolate(GetExecutionContext())); + ThreadDebugger::From(GetExecutionContext()->GetIsolate()); MessagePortArray* ports = MessagePort::EntanglePorts( *GetExecutionContext(), std::move(message.ports)); debugger->ExternalAsyncTaskStarted(message.sender_stack_trace_id);
diff --git a/third_party/blink/renderer/core/workers/experimental/task.cc b/third_party/blink/renderer/core/workers/experimental/task.cc index 4626c59..01a57b7 100644 --- a/third_party/blink/renderer/core/workers/experimental/task.cc +++ b/third_party/blink/renderer/core/workers/experimental/task.cc
@@ -170,7 +170,7 @@ DCHECK(v8_result_); ScriptState::Scope scope( worker_thread_->GlobalScope()->ScriptController()->GetScriptState()); - v8::Isolate* isolate = ToIsolate(worker_thread_->GlobalScope()); + v8::Isolate* isolate = worker_thread_->GlobalScope()->GetIsolate(); serialized_result_ = SerializedScriptValue::SerializeAndSwallowExceptions( isolate, v8_result_->GetResult(isolate)); } @@ -250,7 +250,7 @@ State state) { DCHECK(worker_thread_->IsCurrentThread()); v8_result_ = MakeGarbageCollected<V8ResultHolder>( - ToIsolate(worker_thread_->GlobalScope()), v8_result); + worker_thread_->GlobalScope()->GetIsolate(), v8_result); function_ = nullptr; arguments_.clear(); @@ -278,7 +278,7 @@ // so no mutex needed while actually running the task. WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope(); ScriptState::Scope scope(global_scope->ScriptController()->GetScriptState()); - v8::Isolate* isolate = ToIsolate(global_scope); + v8::Isolate* isolate = global_scope->GetIsolate(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Function> script_function; @@ -401,7 +401,7 @@ DCHECK(worker_thread_->IsCurrentThread()); if (!WillStartTaskOnWorkerThread()) { WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope(); - v8::Isolate* isolate = ToIsolate(global_scope); + v8::Isolate* isolate = global_scope->GetIsolate(); ScriptState::Scope scope( global_scope->ScriptController()->GetScriptState()); TaskCompletedOnWorkerThread(V8String(isolate, "Task aborted"),
diff --git a/third_party/blink/renderer/core/workers/shared_worker.cc b/third_party/blink/renderer/core/workers/shared_worker.cc index 46dcdca..bdca697e 100644 --- a/third_party/blink/renderer/core/workers/shared_worker.cc +++ b/third_party/blink/renderer/core/workers/shared_worker.cc
@@ -34,8 +34,6 @@ #include "third_party/blink/public/common/blob/blob_utils.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/fileapi/public_url_manager.h" -#include "third_party/blink/renderer/core/frame/local_frame.h" -#include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/messaging/message_channel.h" #include "third_party/blink/renderer/core/messaging/message_port.h" @@ -87,20 +85,18 @@ MakeRequest(&blob_url_token)); } - if (document->GetFrame()->Client()->GetSharedWorkerRepositoryClient()) { - // |name| should not be null according to the HTML spec, but the current - // impl wrongly allows it when |name| is omitted. See TODO comment in - // shared_worker.idl. - // TODO(nhiroki): Stop assigning null to |name| as a default value, and - // remove this hack. - String worker_name = ""; - if (!name.IsNull()) - worker_name = name; + // |name| should not be null according to the HTML spec, but the current impl + // wrongly allows it when |name| is omitted. See TODO comment in + // shared_worker.idl. + // TODO(nhiroki): Stop assigning null to |name| as a default value, and remove + // this hack. + String worker_name = ""; + if (!name.IsNull()) + worker_name = name; - document->GetFrame()->Client()->GetSharedWorkerRepositoryClient()->Connect( - worker, std::move(remote_port), script_url, std::move(blob_url_token), - worker_name); - } + SharedWorkerRepositoryClient::From(*document)->Connect( + worker, std::move(remote_port), script_url, std::move(blob_url_token), + worker_name); return worker; }
diff --git a/third_party/blink/renderer/core/workers/shared_worker_connect_listener.cc b/third_party/blink/renderer/core/workers/shared_worker_connect_listener.cc new file mode 100644 index 0000000..86ac86e --- /dev/null +++ b/third_party/blink/renderer/core/workers/shared_worker_connect_listener.cc
@@ -0,0 +1,53 @@ +// 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 "third_party/blink/renderer/core/workers/shared_worker_connect_listener.h" + +#include "base/logging.h" +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/frame/use_counter.h" +#include "third_party/blink/renderer/core/workers/shared_worker.h" + +namespace blink { + +SharedWorkerConnectListener::SharedWorkerConnectListener(SharedWorker* worker) + : worker_(worker) {} + +SharedWorkerConnectListener::~SharedWorkerConnectListener() { + // We have lost our connection to the worker. If this happens before + // OnConnected() is called, then it suggests that the document is gone or + // going away. +} + +void SharedWorkerConnectListener::OnCreated( + mojom::SharedWorkerCreationContextType creation_context_type) { + worker_->SetIsBeingConnected(true); + + // No nested workers (for now) - connect() can only be called from a + // document context. + DCHECK(worker_->GetExecutionContext()->IsDocument()); + DCHECK_EQ(creation_context_type, + worker_->GetExecutionContext()->IsSecureContext() + ? mojom::SharedWorkerCreationContextType::kSecure + : mojom::SharedWorkerCreationContextType::kNonsecure); +} + +void SharedWorkerConnectListener::OnConnected( + const Vector<mojom::WebFeature>& features_used) { + worker_->SetIsBeingConnected(false); + for (auto feature : features_used) + OnFeatureUsed(feature); +} + +void SharedWorkerConnectListener::OnScriptLoadFailed() { + worker_->DispatchEvent(*Event::CreateCancelable(event_type_names::kError)); + worker_->SetIsBeingConnected(false); +} + +void SharedWorkerConnectListener::OnFeatureUsed(mojom::WebFeature feature) { + UseCounter::Count(worker_->GetExecutionContext(), feature); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/workers/shared_worker_connect_listener.h b/third_party/blink/renderer/core/workers/shared_worker_connect_listener.h new file mode 100644 index 0000000..3851612 --- /dev/null +++ b/third_party/blink/renderer/core/workers/shared_worker_connect_listener.h
@@ -0,0 +1,34 @@ +// 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 THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_CONNECT_LISTENER_H_ +#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_CONNECT_LISTENER_H_ + +#include "third_party/blink/public/mojom/worker/shared_worker_client.mojom-blink.h" + +#include "third_party/blink/renderer/platform/heap/persistent.h" + +namespace blink { + +class SharedWorker; + +class SharedWorkerConnectListener final + : public mojom::blink::SharedWorkerClient { + public: + explicit SharedWorkerConnectListener(SharedWorker*); + ~SharedWorkerConnectListener() override; + + // mojom::blink::SharedWorkerClient overrides. + void OnCreated(mojom::SharedWorkerCreationContextType) override; + void OnConnected(const Vector<mojom::WebFeature>& features_used) override; + void OnScriptLoadFailed() override; + void OnFeatureUsed(mojom::WebFeature feature) override; + + private: + Persistent<SharedWorker> worker_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_CONNECT_LISTENER_H_
diff --git a/third_party/blink/renderer/core/workers/shared_worker_repository_client.cc b/third_party/blink/renderer/core/workers/shared_worker_repository_client.cc new file mode 100644 index 0000000..03b0147 --- /dev/null +++ b/third_party/blink/renderer/core/workers/shared_worker_repository_client.cc
@@ -0,0 +1,126 @@ +/* + * Copyright (C) 2009 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "third_party/blink/renderer/core/workers/shared_worker_repository_client.h" + +#include <memory> +#include <utility> +#include "base/logging.h" +#include "services/service_manager/public/cpp/interface_provider.h" +#include "third_party/blink/public/common/messaging/message_port_channel.h" +#include "third_party/blink/public/mojom/worker/shared_worker_info.mojom-blink.h" +#include "third_party/blink/public/platform/web_content_security_policy.h" +#include "third_party/blink/public/platform/web_string.h" +#include "third_party/blink/public/platform/web_url.h" +#include "third_party/blink/public/web/blink.h" +#include "third_party/blink/public/web/web_shared_worker.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h" +#include "third_party/blink/renderer/core/workers/shared_worker.h" +#include "third_party/blink/renderer/core/workers/shared_worker_connect_listener.h" + +namespace blink { + +const char SharedWorkerRepositoryClient::kSupplementName[] = + "SharedWorkerRepositoryClient"; + +SharedWorkerRepositoryClient* SharedWorkerRepositoryClient::From( + Document& document) { + DCHECK(IsMainThread()); + SharedWorkerRepositoryClient* client = + Supplement<Document>::From<SharedWorkerRepositoryClient>(document); + if (!client) { + client = MakeGarbageCollected<SharedWorkerRepositoryClient>(document); + Supplement<Document>::ProvideTo(document, client); + } + return client; +} + +SharedWorkerRepositoryClient::SharedWorkerRepositoryClient(Document& document) + : ContextLifecycleObserver(&document) { + DCHECK(IsMainThread()); + document.GetInterfaceProvider()->GetInterface(mojo::MakeRequest(&connector_)); +} + +void SharedWorkerRepositoryClient::Connect( + SharedWorker* worker, + MessagePortChannel port, + const KURL& url, + mojom::blink::BlobURLTokenPtr blob_url_token, + const String& name) { + DCHECK(IsMainThread()); + DCHECK(!name.IsNull()); + + // TODO(estark): this is broken, as it only uses the first header + // when multiple might have been sent. Fix by making the + // mojom::blink::SharedWorkerInfo take a map that can contain multiple + // headers. + Vector<CSPHeaderAndType> headers = + worker->GetExecutionContext()->GetContentSecurityPolicy()->Headers(); + WebString header = ""; + auto header_type = mojom::ContentSecurityPolicyType::kReport; + if (headers.size() > 0) { + header = headers[0].first; + header_type = + static_cast<mojom::ContentSecurityPolicyType>(headers[0].second); + } + + mojom::blink::SharedWorkerInfoPtr info(mojom::blink::SharedWorkerInfo::New( + url, name, header, header_type, + worker->GetExecutionContext()->GetSecurityContext().AddressSpace())); + + mojom::blink::SharedWorkerClientPtr client_ptr; + client_set_.AddBinding(std::make_unique<SharedWorkerConnectListener>(worker), + mojo::MakeRequest(&client_ptr)); + + connector_->Connect( + std::move(info), std::move(client_ptr), + worker->GetExecutionContext()->IsSecureContext() + ? mojom::SharedWorkerCreationContextType::kSecure + : mojom::SharedWorkerCreationContextType::kNonsecure, + port.ReleaseHandle(), + mojom::blink::BlobURLTokenPtr(mojom::blink::BlobURLTokenPtrInfo( + blob_url_token.PassInterface().PassHandle(), + mojom::blink::BlobURLToken::Version_))); +} + +void SharedWorkerRepositoryClient::ContextDestroyed(ExecutionContext*) { + DCHECK(IsMainThread()); + // Close mojo connections which will signal disinterest in the associated + // shared worker. + client_set_.CloseAllBindings(); +} + +void SharedWorkerRepositoryClient::Trace(Visitor* visitor) { + Supplement<Document>::Trace(visitor); + ContextLifecycleObserver::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/workers/shared_worker_repository_client.h b/third_party/blink/renderer/core/workers/shared_worker_repository_client.h index 16f7c62d..b1701bd 100644 --- a/third_party/blink/renderer/core/workers/shared_worker_repository_client.h +++ b/third_party/blink/renderer/core/workers/shared_worker_repository_client.h
@@ -31,35 +31,60 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_REPOSITORY_CLIENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_REPOSITORY_CLIENT_H_ +#include <memory> + #include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "mojo/public/cpp/bindings/strong_binding_set.h" #include "third_party/blink/public/mojom/blob/blob_url_store.mojom-blink.h" +#include "third_party/blink/public/mojom/worker/shared_worker_client.mojom-blink.h" +#include "third_party/blink/public/mojom/worker/shared_worker_connector.mojom-blink.h" #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/wtf/forward.h" namespace blink { -class Document; class MessagePortChannel; class KURL; class SharedWorker; -class CORE_EXPORT SharedWorkerRepositoryClient { - DISALLOW_NEW(); +// This manages connections with SharedWorkerServiceImpl in the browser process. +// This is owned by Document on the main thread. +// TODO(nhiroki): Rename this class because SharedWorkerRepository doesn't +// exist. +class CORE_EXPORT SharedWorkerRepositoryClient final + : public GarbageCollectedFinalized<SharedWorkerRepositoryClient>, + public Supplement<Document>, + public ContextLifecycleObserver { + USING_GARBAGE_COLLECTED_MIXIN(SharedWorkerRepositoryClient); public: - SharedWorkerRepositoryClient() = default; + static const char kSupplementName[]; + static SharedWorkerRepositoryClient* From(Document& document); + + explicit SharedWorkerRepositoryClient(Document&); virtual ~SharedWorkerRepositoryClient() = default; - virtual void Connect(SharedWorker*, - MessagePortChannel, - const KURL&, - mojom::blink::BlobURLTokenPtr, - const String& name) = 0; + // Establishes a connection with SharedWorkerServiceImpl in the browser + // process. + void Connect(SharedWorker*, + MessagePortChannel, + const KURL&, + mojom::blink::BlobURLTokenPtr, + const String& name); - virtual void DocumentDetached(Document*) = 0; + // Overrides ContextLifecycleObserver. + void ContextDestroyed(ExecutionContext*) override; + + void Trace(Visitor* visitor) override; private: + mojom::blink::SharedWorkerConnectorPtr connector_; + mojo::StrongBindingSet<mojom::blink::SharedWorkerClient> client_set_; + DISALLOW_COPY_AND_ASSIGN(SharedWorkerRepositoryClient); };
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc index f58adaf6..f6778b5e 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
@@ -270,7 +270,7 @@ } XMLHttpRequest* XMLHttpRequest::Create(ExecutionContext* context) { - v8::Isolate* isolate = ToIsolate(context); + v8::Isolate* isolate = context->GetIsolate(); CHECK(isolate); return MakeGarbageCollected<XMLHttpRequest>(context, isolate, false, nullptr);
diff --git a/third_party/blink/renderer/devtools/BUILD.gn b/third_party/blink/renderer/devtools/BUILD.gn index 12ffdeb1..4c27f03 100644 --- a/third_party/blink/renderer/devtools/BUILD.gn +++ b/third_party/blink/renderer/devtools/BUILD.gn
@@ -270,6 +270,8 @@ "front_end/emulation/devicesSettingsTab.css", "front_end/emulation/DevicesSettingsTab.js", "front_end/emulation/EmulatedDevices.js", + "front_end/emulation/geolocationsSettingsTab.css", + "front_end/emulation/GeolocationsSettingsTab.js", "front_end/emulation/inspectedPagePlaceholder.css", "front_end/emulation/InspectedPagePlaceholder.js", "front_end/emulation/mediaQueryInspector.css", @@ -985,9 +987,9 @@ ] devtools_image_files = [ - "front_end/Images/accelerometer-back.png", + "front_end/Images/accelerometer-back.svg", "front_end/Images/accelerometer-bottom.png", - "front_end/Images/accelerometer-front.png", + "front_end/Images/accelerometer-front.svg", "front_end/Images/accelerometer-left.png", "front_end/Images/accelerometer-right.png", "front_end/Images/accelerometer-top.png",
diff --git a/third_party/blink/renderer/devtools/front_end/Images/accelerometer-back.png b/third_party/blink/renderer/devtools/front_end/Images/accelerometer-back.png deleted file mode 100644 index e300cb9..0000000 --- a/third_party/blink/renderer/devtools/front_end/Images/accelerometer-back.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/renderer/devtools/front_end/Images/accelerometer-back.svg b/third_party/blink/renderer/devtools/front_end/Images/accelerometer-back.svg new file mode 100644 index 0000000..603a094 --- /dev/null +++ b/third_party/blink/renderer/devtools/front_end/Images/accelerometer-back.svg
@@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://creativecommons.org/ns#" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + viewBox="0 0 770.00001 1580" + version="1.1" + width="770" + height="1580" + id="svg11071"> + <defs + id="defs3775" /> + <metadata + id="metadata11076"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:title></dc:title> + </cc:Work> + </rdf:RDF> + </metadata> + <g + transform="matrix(-1,0,0,1,770.5,0)" + id="layer3"> + <path + style="fill:none;stroke:#ff8800;stroke-width:9" + d="M 766,366 V 466" + id="path11635" /> + <path + style="fill:none;stroke:#888888;stroke-width:9" + d="M 766,768 V 568" + id="path11637" /> + <g + style="fill-rule:evenodd" + id="g3764"> + <rect + style="fill:#222222" + x="0" + y="0" + width="767" + height="1580" + ry="80" + rx="80" + id="rect11633" /> + </g> + <g + style="fill:#ffffff;fill-rule:evenodd" + id="g3769"> + <rect + style="fill-opacity:0.13332998" + x="273.5" + y="1526" + width="220" + height="15" + ry="5" + rx="5" + id="rect11707" /> + <path + style="fill-opacity:0.86667002" + d="M 70.36319,6.9493575 C 28.332124,5.755102 4.8083241,47.982906 4.8378685,83.222978 L 6.032124,1507.7128 c 0.025949,30.952 32.037776,68.2787 64.633409,68.2161 l 622.086167,-1.1942 c 30.87325,-0.059 68.21618,-37.2632 68.21618,-64.6334 V 76.057445 c 0,-31.282766 -24.68851,-66.7195765 -63.13681,-70.302343 C 456.89848,4.61017 269.72229,6.9493575 70.36319,6.9493575 Z" + id="path11722" /> + </g> + </g> +</svg>
diff --git a/third_party/blink/renderer/devtools/front_end/Images/accelerometer-front.png b/third_party/blink/renderer/devtools/front_end/Images/accelerometer-front.png deleted file mode 100644 index e78de3e..0000000 --- a/third_party/blink/renderer/devtools/front_end/Images/accelerometer-front.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/renderer/devtools/front_end/Images/accelerometer-front.svg b/third_party/blink/renderer/devtools/front_end/Images/accelerometer-front.svg new file mode 100644 index 0000000..6e90a4b --- /dev/null +++ b/third_party/blink/renderer/devtools/front_end/Images/accelerometer-front.svg
@@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> +<svg id="svg11071" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="1580" width="770" version="1.1" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" viewBox="0 0 770.00001 1580"> + <metadata id="metadata11076"> + <rdf:RDF> + <cc:Work rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/> + <dc:title/> + </cc:Work> + </rdf:RDF> + </metadata> + <g id="layer3"> + <path id="path11635" d="m766 366v100" stroke="#f80" stroke-width="9" fill="none"/> + <path id="path11637" d="m766 768v-200" stroke="#888" stroke-width="9" fill="none"/> + <g fill-rule="evenodd"> + <rect id="rect11633" rx="80" ry="80" height="1580" width="767" y="0" x="0" fill="#222"/> + <rect id="rect11061" fill-opacity=".13333" rx="5" ry="5" height="18" width="80" y="80" x="343.5" fill="#fff"/> + <circle id="path11063" cx="459" fill-opacity=".26667" cy="76.25" r="15" fill="#00f"/> + <circle id="path11069" cx="297.25" fill-opacity=".26667" cy="74" r="17.5" fill="#00f"/> + </g> + <g fill-rule="evenodd" fill="#fff"> + <rect id="rect11705" fill-opacity=".13333" rx="10" ry="10" height="25" width="50" y="34" x="358.5"/> + <rect id="rect11707" fill-opacity=".13333" rx="5" ry="5" height="15" width="220" y="1526" x="273.5"/> + <path id="path11722" d="m83.5 38c-27.7 0-50 22.3-50 50v1360c0 16.62 13.38 30 30 30h640c16.62 0 30-13.38 30-30v-1360c0-27.7-22.3-50-50-50h-90-50c-19.39 0-35 15.61-35 35v4c0 24.93-20.07 45-45 45h-160c-24.93 0-45-20.07-45-45v-4c0-19.39-15.61-35-35-35h-70z" fill-opacity=".86667"/> + </g> + </g> +</svg>
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js b/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js new file mode 100644 index 0000000..4b114db --- /dev/null +++ b/third_party/blink/renderer/devtools/front_end/emulation/GeolocationsSettingsTab.js
@@ -0,0 +1,189 @@ +// 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. + +/** + * @implements {UI.ListWidget.Delegate} + * @unrestricted + */ +Emulation.GeolocationsSettingsTab = class extends UI.VBox { + constructor() { + super(true); + this.registerRequiredCSS('emulation/geolocationsSettingsTab.css'); + + this.contentElement.createChild('div', 'header').textContent = Common.UIString('Custom Geolocations'); + + const addButton = UI.createTextButton( + Common.UIString('Add location...'), this._addButtonClicked.bind(this), 'add-geolocations-button'); + this.contentElement.appendChild(addButton); + + this._list = new UI.ListWidget(this); + this._list.element.classList.add('geolocations-list'); + this._list.registerRequiredCSS('emulation/geolocationsSettingsTab.css'); + this._list.show(this.contentElement); + + this._customSetting = Common.moduleSetting('emulation.geolocations'); + this._customSetting.addChangeListener(this._geolocationsUpdated, this); + + this.setDefaultFocusedElement(addButton); + this.contentElement.tabIndex = 0; + } + + /** + * @override + */ + wasShown() { + super.wasShown(); + this._geolocationsUpdated(); + } + + _geolocationsUpdated() { + this._list.clear(); + + const conditions = this._customSetting.get(); + for (let i = 0; i < conditions.length; ++i) + this._list.appendItem(conditions[i], true); + + this._list.appendSeparator(); + } + + _addButtonClicked() { + this._list.addNewItem(this._customSetting.get().length, {title: '', lat: 0, long: 0}); + } + + /** + * @override + * @param {*} item + * @param {boolean} editable + * @return {!Element} + */ + renderItem(item, editable) { + const geolocation = /** @type {!Emulation.GeolocationsSettingsTab.Item} */ (item); + const element = createElementWithClass('div', 'geolocations-list-item'); + const title = element.createChild('div', 'geolocations-list-text geolocations-list-title'); + const titleText = title.createChild('div', 'geolocations-list-title-text'); + titleText.textContent = geolocation.title; + titleText.title = geolocation.title; + element.createChild('div', 'geolocations-list-separator'); + element.createChild('div', 'geolocations-list-text').textContent = geolocation.lat; + element.createChild('div', 'geolocations-list-separator'); + element.createChild('div', 'geolocations-list-text').textContent = geolocation.long; + return element; + } + + /** + * @override + * @param {*} item + * @param {number} index + */ + removeItemRequested(item, index) { + const list = this._customSetting.get(); + list.splice(index, 1); + this._customSetting.set(list); + } + + /** + * @override + * @param {*} item + * @param {!UI.ListWidget.Editor} editor + * @param {boolean} isNew + */ + commitEdit(item, editor, isNew) { + const geolocation = /** @type {?Emulation.GeolocationsSettingsTab.Item} */ (item); + geolocation.title = editor.control('title').value.trim(); + const lat = editor.control('lat').value.trim(); + geolocation.lat = lat ? parseFloat(lat) : 0; + const long = editor.control('long').value.trim(); + geolocation.long = long ? parseFloat(long) : 0; + + const list = this._customSetting.get(); + if (isNew) + list.push(geolocation); + this._customSetting.set(list); + } + + /** + * @override + * @param {*} item + * @return {!UI.ListWidget.Editor} + */ + beginEdit(item) { + const geolocation = /** @type {?Emulation.GeolocationsSettingsTab.Item} */ (item); + const editor = this._createEditor(); + editor.control('title').value = geolocation.title; + editor.control('lat').value = String(geolocation.lat); + editor.control('long').value = String(geolocation.long); + return editor; + } + + /** + * @return {!UI.ListWidget.Editor} + */ + _createEditor() { + if (this._editor) + return this._editor; + + const editor = new UI.ListWidget.Editor(); + this._editor = editor; + const content = editor.contentElement(); + + const titles = content.createChild('div', 'geolocations-edit-row'); + titles.createChild('div', 'geolocations-list-text geolocations-list-title').textContent = + Common.UIString('Location name'); + titles.createChild('div', 'geolocations-list-separator geolocations-list-separator-invisible'); + titles.createChild('div', 'geolocations-list-text').textContent = Common.UIString('Lat'); + titles.createChild('div', 'geolocations-list-separator geolocations-list-separator-invisible'); + titles.createChild('div', 'geolocations-list-text').textContent = Common.UIString('Long'); + + const fields = content.createChild('div', 'geolocations-edit-row'); + fields.createChild('div', 'geolocations-list-text geolocations-list-title') + .appendChild(editor.createInput('title', 'text', '', titleValidator)); + fields.createChild('div', 'geolocations-list-separator geolocations-list-separator-invisible'); + + let cell = fields.createChild('div', 'geolocations-list-text'); + cell.appendChild(editor.createInput('lat', 'text', '', latValidator)); + fields.createChild('div', 'geolocations-list-separator geolocations-list-separator-invisible'); + + cell = fields.createChild('div', 'geolocations-list-text'); + cell.appendChild(editor.createInput('long', 'text', '', longValidator)); + fields.createChild('div', 'geolocations-list-separator geolocations-list-separator-invisible'); + + return editor; + + /** + * @param {*} item + * @param {number} index + * @param {!HTMLInputElement|!HTMLSelectElement} input + * @return {boolean} + */ + function titleValidator(item, index, input) { + const value = input.value.trim(); + return value.length > 0 && value.length < 50; + } + + /** + * @param {*} item + * @param {number} index + * @param {!HTMLInputElement|!HTMLSelectElement} input + * @return {boolean} + */ + function latValidator(item, index, input) { + const value = input.value.trim(); + return !value || (/^-?[\d]+(\.\d+)?|\.\d+$/.test(value) && value >= -90 && value <= 90); + } + + /** + * @param {*} item + * @param {number} index + * @param {!HTMLInputElement|!HTMLSelectElement} input + * @return {boolean} + */ + function longValidator(item, index, input) { + const value = input.value.trim(); + return !value || (/^-?[\d]+(\.\d+)?|\.\d+$/.test(value) && value >= -180 && value <= 180); + } + } +}; + +/** @typedef {{title: string, lat: number, long: number}} */ +Emulation.GeolocationsSettingsTab.Item; \ No newline at end of file
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js b/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js index 9bb1e558..18dab20 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js +++ b/third_party/blink/renderer/devtools/front_end/emulation/SensorsView.js
@@ -48,24 +48,38 @@ title: Common.UIString('No override'), location: Emulation.SensorsView.NonPresetOptions.NoOverride }; + + this._locationSelectElement = fields.createChild('select', 'chrome-select'); + + // No override + this._locationSelectElement.appendChild(new Option(noOverrideOption.title, noOverrideOption.location)); + + // Locations + this._customLocationsGroup = this._locationSelectElement.createChild('optgroup'); + this._customLocationsGroup.label = ls`Overrides`; + const customGeolocations = Common.moduleSetting('emulation.geolocations'); + fields.appendChild(UI.createTextButton(ls`Manage`, () => Common.Revealer.reveal(customGeolocations))); + const fillCustomSettings = () => { + this._customLocationsGroup.removeChildren(); + for (const geolocation of customGeolocations.get()) + this._customLocationsGroup.appendChild(new Option(geolocation.title, JSON.stringify(geolocation))); + }; + customGeolocations.addChangeListener(fillCustomSettings); + fillCustomSettings(); + + // Other location const customLocationOption = { - title: Common.UIString('Custom location...'), + title: Common.UIString('Other\u2026'), location: Emulation.SensorsView.NonPresetOptions.Custom }; - this._locationSelectElement = this.contentElement.createChild('select', 'chrome-select'); - this._locationSelectElement.appendChild(new Option(noOverrideOption.title, noOverrideOption.location)); this._locationSelectElement.appendChild(new Option(customLocationOption.title, customLocationOption.location)); - const locationGroups = Emulation.SensorsView.PresetLocations; - for (let i = 0; i < locationGroups.length; ++i) { - const group = locationGroups[i].value; - const groupElement = this._locationSelectElement.createChild('optgroup'); - groupElement.label = locationGroups[i].title; - for (let j = 0; j < group.length; ++j) - groupElement.appendChild(new Option(group[j].title, group[j].location)); - } + // Error location. + const group = this._locationSelectElement.createChild('optgroup'); + group.label = ls`Error`; + group.appendChild(new Option(ls`Location unavailable`, Emulation.SensorsView.NonPresetOptions.Unavailable)); + this._locationSelectElement.selectedIndex = 0; - fields.appendChild(this._locationSelectElement); this._locationSelectElement.addEventListener('change', this._geolocationSelectChanged.bind(this)); // Validated input fieldset. @@ -117,9 +131,9 @@ } else { this._geolocationOverrideEnabled = true; const coordinates = JSON.parse(value); - this._geolocation = new SDK.EmulationModel.Geolocation(coordinates[0], coordinates[1], false); - this._latitudeSetter(coordinates[0]); - this._longitudeSetter(coordinates[1]); + this._geolocation = new SDK.EmulationModel.Geolocation(coordinates.lat, coordinates.long, false); + this._latitudeSetter(coordinates.lat); + this._longitudeSetter(coordinates.long); } this._applyGeolocation(); @@ -462,35 +476,11 @@ /** {string} */ Emulation.SensorsView.NonPresetOptions = { - 'NoOverride': 'noOverride', - 'Custom': 'custom', - 'Unavailable': 'unavailable' + NoOverride: 'noOverride', + Custom: 'custom', + Unavailable: 'unavailable' }; -/** @type {!Array.<{title: string, value: !Array.<{title: string, location: string}>}>} */ -Emulation.SensorsView.PresetLocations = [ - { - title: 'Presets', - value: [ - {title: Common.UIString('Berlin'), location: '[52.520007, 13.404954]'}, - {title: Common.UIString('London'), location: '[51.507351, -0.127758]'}, - {title: Common.UIString('Moscow'), location: '[55.755826, 37.617300]'}, - {title: Common.UIString('Mountain View'), location: '[37.386052, -122.083851]'}, - {title: Common.UIString('Mumbai'), location: '[19.075984, 72.877656]'}, - {title: Common.UIString('San Francisco'), location: '[37.774929, -122.419416]'}, - {title: Common.UIString('Shanghai'), location: '[31.230416, 121.473701]'}, - {title: Common.UIString('São Paulo'), location: '[-23.550520, -46.633309]'}, - {title: Common.UIString('Tokyo'), location: '[35.689487, 139.691706]'}, - ] - }, - { - title: 'Error', - value: [ - {title: Common.UIString('Location unavailable'), location: Emulation.SensorsView.NonPresetOptions.Unavailable} - ] - } -]; - /** @type {!Array.<{title: string, value: !Array.<{title: string, orientation: string}>}>} */ Emulation.SensorsView.PresetOrientations = [{ title: 'Presets',
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/geolocationsSettingsTab.css b/third_party/blink/renderer/devtools/front_end/emulation/geolocationsSettingsTab.css new file mode 100644 index 0000000..53c1f185e --- /dev/null +++ b/third_party/blink/renderer/devtools/front_end/emulation/geolocationsSettingsTab.css
@@ -0,0 +1,94 @@ +/* + * 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. + */ + +:host { + overflow:hidden; +} + +.header { + padding: 0 0 6px; + border-bottom: 1px solid #EEEEEE; + font-size: 18px; + font-weight: normal; + flex: none; +} + +.add-geolocations-button { + flex: none; + margin: 10px 2px; + min-width: 140px; + align-self: flex-start; +} + +.geolocations-list { + max-width: 500px; + min-width: 340px; + flex: auto; +} + +.geolocations-list-item { + padding: 3px 5px 3px 5px; + height: 30px; + display: flex; + align-items: center; + position: relative; + flex: auto 1 1; +} + +.geolocations-list-text { + white-space: nowrap; + text-overflow: ellipsis; + flex: 0 0 70px; + -webkit-user-select: none; + color: #222; + text-align: end; + position: relative; +} + +.geolocations-list-title { + text-align: start; + flex: auto; + display: flex; + align-items: flex-start; +} + +.geolocations-list-title-text { + overflow: hidden; + flex: auto; + white-space: nowrap; + text-overflow: ellipsis; +} + +.geolocations-list-separator { + flex: 0 0 1px; + background-color: rgb(231, 231, 231); + height: 30px; + margin: 0 4px; +} + +.geolocations-list-separator-invisible { + visibility: hidden; + height: 100% !important; +} + +.geolocations-edit-row { + flex: none; + display: flex; + flex-direction: row; + margin: 6px 5px; +} + +.geolocations-edit-row input { + width: 100%; + text-align: inherit; +} + +.geolocations-edit-optional { + position: absolute; + bottom: -20px; + right: 0; + color: rgb(128, 128, 128); +}
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/module.json b/third_party/blink/renderer/devtools/front_end/emulation/module.json index 51b0d64..ba41bcb 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/module.json +++ b/third_party/blink/renderer/devtools/front_end/emulation/module.json
@@ -149,6 +149,33 @@ "order": 100, "className": "Emulation.SensorsView", "tags": "geolocation, accelerometer, device orientation" + }, + { + "type": "setting", + "settingName": "emulation.geolocations", + "settingType": "array", + "defaultValue": [ + {"title": "Berlin", "lat": 52.520007, "long": 13.404954}, + {"title": "London", "lat": 51.507351, "long": -0.127758}, + {"title": "Moscow", "lat": 55.755826, "long": 37.617300}, + {"title": "Mountain View", "lat": 37.386052, "long": -122.083851}, + {"title": "Mumbai", "lat": 19.075984, "long": 72.877656}, + {"title": "San Francisco", "lat": 37.774929, "long": -122.419416}, + {"title": "Shanghai", "lat": 31.230416, "long": 121.473701}, + {"title": "São Paulo", "lat": -23.550520, "long": -46.633309}, + {"title": "Tokyo", "lat": 35.689487, "long": 139.691706} + ] + }, + { + "type": "view", + "location": "settings-view", + "id": "emulation-geolocations", + "title": "Geolocations", + "order": 40, + "className": "Emulation.GeolocationsSettingsTab", + "settings": [ + "emulation.geolocations" + ] } ], "dependencies": [ @@ -168,12 +195,14 @@ "DeviceModeModel.js", "DeviceModeToolbar.js", "DeviceModeView.js", - "DeviceModeWrapper.js" + "DeviceModeWrapper.js", + "GeolocationsSettingsTab.js" ], "resources": [ "devicesSettingsTab.css", "deviceModeToolbar.css", "deviceModeView.css", + "geolocationsSettingsTab.css", "inspectedPagePlaceholder.css", "mediaQueryInspector.css", "sensors.css"
diff --git a/third_party/blink/renderer/devtools/front_end/emulation/sensors.css b/third_party/blink/renderer/devtools/front_end/emulation/sensors.css index 03c1311..a261d73 100644 --- a/third_party/blink/renderer/devtools/front_end/emulation/sensors.css +++ b/third_party/blink/renderer/devtools/front_end/emulation/sensors.css
@@ -113,7 +113,7 @@ } .orientation-box { - width: 66px; + width: 62px; height: 122px; left: 0; right: 0; @@ -136,31 +136,31 @@ .orientation-front, .orientation-back { - width: 66px; + width: 62px; height: 122px; border-radius: 8px; } .orientation-front { - background-image: url(Images/accelerometer-front.png); + background-image: url(Images/accelerometer-front.svg); } .orientation-back { - transform: rotateY(180deg) translateZ(12px); - background-image: url(Images/accelerometer-back.png); + transform: rotateY(180deg) translateZ(8px); + background-image: url(Images/accelerometer-back.svg); } .orientation-left, .orientation-right { - width: 12px; + width: 8px; height: 106px; top: 8px; background-position: center center; } .orientation-left { - left: -12px; + left: -8px; transform-origin: right center; transform: rotateY(-90deg); background-image: url(Images/accelerometer-left.png); @@ -168,7 +168,7 @@ .orientation-right { - right: -12px; + right: -8px; transform-origin: left center; transform: rotateY(90deg); background-image: url(Images/accelerometer-right.png); @@ -180,7 +180,7 @@ .orientation-right::after { content: ''; - width: 12px; + width: 8px; height: 6px; } @@ -215,13 +215,13 @@ .orientation-top, .orientation-bottom { width: 50px; - height: 12px; + height: 8px; left: 8px; background-position: center center; } .orientation-top { - top: -12px; + top: -8px; transform-origin: center bottom; transform: rotateX(90deg); background-image: url(Images/accelerometer-top.png); @@ -229,7 +229,7 @@ .orientation-bottom { - bottom: -12px; + bottom: -8px; transform-origin: center top; transform: rotateX(-90deg); background-image: url(Images/accelerometer-bottom.png); @@ -243,7 +243,7 @@ { content: ''; width: 8px; - height: 12px; + height: 8px; } .orientation-top::before, @@ -301,7 +301,7 @@ .panel-section-separator { height: 2px; - margin-bottom: 12px; + margin-bottom: 8px; background: #f1f1f1; } @@ -309,3 +309,7 @@ align-self: center; margin-left: 10px; } + +button[is=text-button] { + margin: 0 10px; +}
diff --git a/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js b/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js index b720830..cb0f436 100644 --- a/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js +++ b/third_party/blink/renderer/devtools/front_end/protocol_monitor/ProtocolMonitor.js
@@ -48,6 +48,8 @@ DataGrid.DataGrid.Events.SelectedNode, event => this._infoWidget.render(event.data.data)); this._dataGrid.addEventListener(DataGrid.DataGrid.Events.DeselectedNode, event => this._infoWidget.render(null)); this._dataGrid.setHeaderContextMenuCallback(this._innerHeaderContextMenu.bind(this)); + this._dataGrid.setRowContextMenuCallback(this._innerRowContextMenu.bind(this)); + this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this._sortDataGrid.bind(this)); this._dataGrid.setStickToBottom(true); @@ -65,9 +67,12 @@ const filters = this._filterParser.parse(query); this._filter = node => { for (const {key, text, negative} of filters) { - if (!(key in node.data) || !text) + if (!text) continue; - const found = JSON.stringify(node.data[key]).indexOf(text) !== -1; + const data = key ? node.data[key] : node.data; + if (!data) + continue; + const found = JSON.stringify(data).toLowerCase().indexOf(text.toLowerCase()) !== -1; if (found === negative) return false; } @@ -102,6 +107,22 @@ } /** + * @param {!UI.ContextMenu} contextMenu + * @param {!ProtocolMonitor.ProtocolMonitor.ProtocolNode} node + */ + _innerRowContextMenu(contextMenu, node) { + contextMenu.defaultSection().appendItem(ls`Filter`, () => { + this._textFilterUI.setValue(`method:${node.data.method}`, true); + }); + contextMenu.defaultSection().appendItem(ls`Documentation`, () => { + const [domain, method] = node.data.method.split('.'); + const type = node.data.direction === 'sent' ? 'method' : 'event'; + InspectorFrontendHost.openInNewTab( + `https://chromedevtools.github.io/devtools-protocol/tot/${domain}#${type}-${method}`); + }); + } + + /** * @param {!Object} columnConfig */ _toggleColumnVisibility(columnConfig) { @@ -164,7 +185,8 @@ const node = this._nodeForId[message.id]; if (!node) return; - node.data.response = message.result; + node.data.response = message.result || message.error; + node.hasError = !!message.error; node.refresh(); if (this._dataGrid.selectedNode === node) this._infoWidget.render(node.data); @@ -201,6 +223,7 @@ ProtocolMonitor.ProtocolMonitor.ProtocolNode = class extends DataGrid.SortableDataGridNode { constructor(data) { super(data); + this.hasError = false; } /** @@ -241,6 +264,7 @@ const element = super.element(); element.classList.toggle('protocol-message-sent', this.data.direction === 'sent'); element.classList.toggle('protocol-message-recieved', this.data.direction !== 'sent'); + element.classList.toggle('error', this.hasError); return element; } };
diff --git a/third_party/blink/renderer/devtools/front_end/protocol_monitor/protocolMonitor.css b/third_party/blink/renderer/devtools/front_end/protocol_monitor/protocolMonitor.css index 5787a07..1c511de8 100644 --- a/third_party/blink/renderer/devtools/front_end/protocol_monitor/protocolMonitor.css +++ b/third_party/blink/renderer/devtools/front_end/protocol_monitor/protocolMonitor.css
@@ -30,3 +30,8 @@ .protocol-monitor-toolbar { border-bottom:var(--divider-border); } + +.error { + background-color: hsl(0, 100%, 97%); + color: red; +} \ No newline at end of file
diff --git a/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js b/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js index 58cef46..aa8a58f3 100644 --- a/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js +++ b/third_party/blink/renderer/devtools/front_end/resources/AppManifestView.js
@@ -25,13 +25,8 @@ this._reportView.hideWidget(); this._errorsSection = this._reportView.appendSection(Common.UIString('Errors and warnings')); + this._installabilitySection = this._reportView.appendSection(Common.UIString('Installability')); this._identitySection = this._reportView.appendSection(Common.UIString('Identity')); - const toolbar = this._identitySection.createToolbar(); - toolbar.renderAsLinks(); - const addToHomeScreen = - new UI.ToolbarButton(Common.UIString('Add to homescreen'), undefined, Common.UIString('Add to homescreen')); - addToHomeScreen.addEventListener(UI.ToolbarButton.Events.Click, this._addToHomescreen, this); - toolbar.appendToolbarItem(addToHomeScreen); this._presentationSection = this._reportView.appendSection(Common.UIString('Presentation')); this._iconsSection = this._reportView.appendSection(Common.UIString('Icons')); @@ -64,7 +59,7 @@ return; this._resourceTreeModel = resourceTreeModel; this._updateManifest(); - resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this); + resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded, this._updateManifest, this); } /** @@ -74,7 +69,7 @@ modelRemoved(resourceTreeModel) { if (!this._resourceTreeModel || this._resourceTreeModel !== resourceTreeModel) return; - resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.MainFrameNavigated, this._updateManifest, this); + resourceTreeModel.removeEventListener(SDK.ResourceTreeModel.Events.DOMContentLoaded, this._updateManifest, this); delete this._resourceTreeModel; } @@ -107,17 +102,24 @@ if (!data) return; + const installabilityErrors = []; + if (data.charCodeAt(0) === 0xFEFF) data = data.slice(1); // Trim the BOM as per https://tools.ietf.org/html/rfc7159#section-8.1. const parsedManifest = JSON.parse(data); this._nameField.textContent = stringProperty('name'); this._shortNameField.textContent = stringProperty('short_name'); + if (!this._nameField.textContent && !this._shortNameField.textContent) + installabilityErrors.push(ls`Either 'name' or 'short_name' is required`); + this._startURLField.removeChildren(); const startURL = stringProperty('start_url'); if (startURL) { const completeURL = /** @type {string} */ (Common.ParsedURL.completeURL(url, startURL)); this._startURLField.appendChild(Components.Linkifier.linkifyURL(completeURL, {text: startURL})); + } else { + installabilityErrors.push(ls`'start_url' needs to be a valid URL`); } this._themeColorSwatch.classList.toggle('hidden', !stringProperty('theme_color')); @@ -129,18 +131,36 @@ this._backgroundColorSwatch.setColor(/** @type {!Common.Color} */ (backgroundColor)); this._orientationField.textContent = stringProperty('orientation'); - this._displayField.textContent = stringProperty('display'); + const displayType = stringProperty('display'); + this._displayField.textContent = displayType; + if (!['minimal-ui', 'standalone', 'fullscreen'].includes(displayType)) + installabilityErrors.push(ls`'display' property must be set to 'standalone', 'fullscreen' or 'minimal-ui'`); const icons = parsedManifest['icons'] || []; + let hasInstallableIcon = false; this._iconsSection.clearContent(); for (const icon of icons) { + if (!icon.sizes) + hasInstallableIcon = true; // any const title = (icon['sizes'] || '') + '\n' + (icon['type'] || ''); + try { + const widthHeight = icon['sizes'].split('x'); + if (parseInt(widthHeight[0], 10) >= 144 && parseInt(widthHeight[1], 10) >= 144) + hasInstallableIcon = true; + } catch (e) { + } const field = this._iconsSection.appendField(title); const imageElement = field.createChild('img'); imageElement.style.maxWidth = '200px'; imageElement.style.maxHeight = '200px'; imageElement.src = Common.ParsedURL.completeURL(url, icon['src']); } + if (!hasInstallableIcon) + installabilityErrors.push(ls`An icon at least 144px x 144px large is required`); + this._installabilitySection.clearContent(); + this._installabilitySection.element.classList.toggle('hidden', !installabilityErrors.length); + for (const error of installabilityErrors) + this._installabilitySection.appendRow().appendChild(UI.createLabel(error, 'smallicon-warning')); /** * @param {string} name @@ -153,15 +173,4 @@ return value; } } - - /** - * @param {!Common.Event} event - */ - _addToHomescreen(event) { - const target = SDK.targetManager.mainTarget(); - if (target && target.type() === SDK.Target.Type.Frame) { - target.pageAgent().requestAppBanner(); - Common.console.show(); - } - } };
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Dialog.js b/third_party/blink/renderer/devtools/front_end/ui/Dialog.js index ee18e276..a60ba4f 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Dialog.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Dialog.js
@@ -120,7 +120,8 @@ * @param {!Event} event */ _onKeyDown(event) { - if (this._closeOnEscape && event.keyCode === UI.KeyboardShortcut.Keys.Esc.code) { + if (this._closeOnEscape && event.keyCode === UI.KeyboardShortcut.Keys.Esc.code && + UI.KeyboardShortcut.hasNoModifiers(event)) { event.consume(true); this.hide(); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js b/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js index 04fd21a..bd54790 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js +++ b/third_party/blink/renderer/devtools/front_end/ui/Toolbar.js
@@ -578,7 +578,7 @@ const clearButton = this.element.createChild('div', 'toolbar-input-clear-button'); clearButton.appendChild(UI.Icon.create('mediumicon-gray-cross-hover', 'search-cancel-button')); clearButton.addEventListener('click', () => { - this._internalSetValue('', true); + this.setValue('', true); this._prompt.focus(); }); @@ -595,16 +595,9 @@ /** * @param {string} value + * @param {boolean=} notify */ - setValue(value) { - this._internalSetValue(value, false); - } - - /** - * @param {string} value - * @param {boolean} notify - */ - _internalSetValue(value, notify) { + setValue(value, notify) { this._prompt.setText(value); if (notify) this._onChangeCallback(); @@ -624,7 +617,7 @@ _onKeydownCallback(event) { if (!isEscKey(event) || !this._prompt.text()) return; - this._internalSetValue('', true); + this.setValue('', true); event.consume(true); }
diff --git a/third_party/blink/renderer/devtools/front_end/ui/inspectorCommon.css b/third_party/blink/renderer/devtools/front_end/ui/inspectorCommon.css index 824db97f..40892fe 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/inspectorCommon.css +++ b/third_party/blink/renderer/devtools/front_end/ui/inspectorCommon.css
@@ -50,6 +50,10 @@ outline-width: 0; } +input[type=radio]:focus { + outline: auto 5px -webkit-focus-ring-color; +} + img { -webkit-user-drag: none; }
diff --git a/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc b/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc index 193c0cf..f9af248 100644 --- a/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc +++ b/third_party/blink/renderer/modules/indexeddb/idb_key_range.cc
@@ -40,13 +40,13 @@ if (value.IsUndefined() || value.IsNull()) return nullptr; - IDBKeyRange* const range = - ScriptValue::To<IDBKeyRange*>(ToIsolate(context), value, exception_state); + IDBKeyRange* const range = ScriptValue::To<IDBKeyRange*>( + context->GetIsolate(), value, exception_state); if (range) return range; std::unique_ptr<IDBKey> key = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(context), value, exception_state); + context->GetIsolate(), value, exception_state); if (exception_state.HadException()) return nullptr; if (!key || !key->IsValid()) { @@ -105,8 +105,7 @@ const ScriptValue& key_value, ExceptionState& exception_state) { std::unique_ptr<IDBKey> key = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(ExecutionContext::From(script_state)), key_value, - exception_state); + script_state->GetIsolate(), key_value, exception_state); if (exception_state.HadException()) return nullptr; if (!key || !key->IsValid()) { @@ -126,7 +125,7 @@ bool open, ExceptionState& exception_state) { std::unique_ptr<IDBKey> bound = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(ExecutionContext::From(script_state)), bound_value, + ExecutionContext::From(script_state)->GetIsolate(), bound_value, exception_state); if (exception_state.HadException()) return nullptr; @@ -146,7 +145,7 @@ bool open, ExceptionState& exception_state) { std::unique_ptr<IDBKey> bound = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(ExecutionContext::From(script_state)), bound_value, + ExecutionContext::From(script_state)->GetIsolate(), bound_value, exception_state); if (exception_state.HadException()) return nullptr; @@ -167,7 +166,7 @@ bool upper_open, ExceptionState& exception_state) { std::unique_ptr<IDBKey> lower = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(ExecutionContext::From(script_state)), lower_value, + ExecutionContext::From(script_state)->GetIsolate(), lower_value, exception_state); if (exception_state.HadException()) return nullptr; @@ -178,7 +177,7 @@ } std::unique_ptr<IDBKey> upper = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(ExecutionContext::From(script_state)), upper_value, + ExecutionContext::From(script_state)->GetIsolate(), upper_value, exception_state); if (exception_state.HadException()) @@ -214,7 +213,7 @@ const ScriptValue& key_value, ExceptionState& exception_state) { std::unique_ptr<IDBKey> key = ScriptValue::To<std::unique_ptr<IDBKey>>( - ToIsolate(ExecutionContext::From(script_state)), key_value, + ExecutionContext::From(script_state)->GetIsolate(), key_value, exception_state); if (exception_state.HadException()) return false;
diff --git a/third_party/blink/renderer/modules/modules_initializer.cc b/third_party/blink/renderer/modules/modules_initializer.cc index 9911416..255cb05 100644 --- a/third_party/blink/renderer/modules/modules_initializer.cc +++ b/third_party/blink/renderer/modules/modules_initializer.cc
@@ -222,10 +222,10 @@ MakeGarbageCollected<DeviceOrientationInspectorAgent>(inspected_frames)); session->Append( MakeGarbageCollected<InspectorDOMStorageAgent>(inspected_frames)); + session->Append(MakeGarbageCollected<InspectorAccessibilityAgent>( + inspected_frames, dom_agent)); if (allow_view_agents) { session->Append(InspectorDatabaseAgent::Create(page)); - session->Append(MakeGarbageCollected<InspectorAccessibilityAgent>( - inspected_frames, dom_agent)); session->Append(InspectorCacheStorageAgent::Create(inspected_frames)); } }
diff --git a/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc b/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc index 55992d19..3d86413 100644 --- a/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc +++ b/third_party/blink/renderer/modules/payments/abort_payment_respond_with_observer.cc
@@ -38,8 +38,8 @@ DCHECK(GetExecutionContext()); ExceptionState exception_state(value.GetIsolate(), context_type, interface_name, property_name); - bool response = ToBoolean(ToIsolate(GetExecutionContext()), value.V8Value(), - exception_state); + bool response = + ToBoolean(value.GetIsolate(), value.V8Value(), exception_state); if (exception_state.HadException()) { exception_state.ClearException(); OnResponseRejected(blink::mojom::ServiceWorkerResponseError::kNoV8Instance);
diff --git a/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc b/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc index 41e87e2..0a61048 100644 --- a/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc +++ b/third_party/blink/renderer/modules/payments/can_make_payment_respond_with_observer.cc
@@ -38,8 +38,8 @@ DCHECK(GetExecutionContext()); ExceptionState exception_state(value.GetIsolate(), context_type, interface_name, property_name); - bool response = ToBoolean(ToIsolate(GetExecutionContext()), value.V8Value(), - exception_state); + bool response = + ToBoolean(value.GetIsolate(), value.V8Value(), exception_state); if (exception_state.HadException()) { exception_state.ClearException(); OnResponseRejected(blink::mojom::ServiceWorkerResponseError::kNoV8Instance);
diff --git a/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc b/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc index c8e5ee19..cfdcd13 100644 --- a/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc +++ b/third_party/blink/renderer/modules/payments/payment_request_respond_with_observer.cc
@@ -47,7 +47,7 @@ interface_name, property_name); PaymentHandlerResponse* response = NativeValueTraits<PaymentHandlerResponse>::NativeValue( - ToIsolate(GetExecutionContext()), value.V8Value(), exception_state); + value.GetIsolate(), value.V8Value(), exception_state); if (exception_state.HadException()) { exception_state.ClearException(); OnResponseRejected(mojom::ServiceWorkerResponseError::kNoV8Instance);
diff --git a/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc b/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc index d8cd91c6..c21c0f7 100644 --- a/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc +++ b/third_party/blink/renderer/modules/service_worker/fetch_respond_with_observer.cc
@@ -233,13 +233,12 @@ const char* interface_name, const char* property_name) { DCHECK(GetExecutionContext()); - if (!V8Response::HasInstance(value.V8Value(), - ToIsolate(GetExecutionContext()))) { + if (!V8Response::HasInstance(value.V8Value(), value.GetIsolate())) { OnResponseRejected(ServiceWorkerResponseError::kNoV8Instance); return; } - Response* response = V8Response::ToImplWithTypeCheck( - ToIsolate(GetExecutionContext()), value.V8Value()); + Response* response = + V8Response::ToImplWithTypeCheck(value.GetIsolate(), value.V8Value()); // "If one of the following conditions is true, return a network error: // - |response|'s type is |error|. // - |request|'s mode is |same-origin| and |response|'s type is |cors|.
diff --git a/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc b/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc index 7438528..8367c44 100644 --- a/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc +++ b/third_party/blink/renderer/modules/time_zone_monitor/time_zone_monitor_client.cc
@@ -30,7 +30,7 @@ void NotifyTimezoneChangeOnWorkerThread(WorkerThread* worker_thread) { DCHECK(worker_thread->IsCurrentThread()); - NotifyTimezoneChangeToV8(ToIsolate(worker_thread->GlobalScope())); + NotifyTimezoneChangeToV8(worker_thread->GlobalScope()->GetIsolate()); } } // namespace
diff --git a/third_party/blink/renderer/platform/bindings/callback_interface_base.cc b/third_party/blink/renderer/platform/bindings/callback_interface_base.cc index 73b57c5..68b2c8f 100644 --- a/third_party/blink/renderer/platform/bindings/callback_interface_base.cc +++ b/third_party/blink/renderer/platform/bindings/callback_interface_base.cc
@@ -4,25 +4,32 @@ #include "third_party/blink/renderer/platform/bindings/callback_interface_base.h" +#include "third_party/blink/renderer/platform/bindings/binding_security_for_platform.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" + namespace blink { CallbackInterfaceBase::CallbackInterfaceBase( v8::Local<v8::Object> callback_object, - v8::Local<v8::Context> callback_object_creation_context, SingleOperationOrNot single_op_or_not) { DCHECK(!callback_object.IsEmpty()); - DCHECK(!callback_object_creation_context.IsEmpty()); - DCHECK(callback_object->CreationContext() == - callback_object_creation_context); - callback_relevant_script_state_ = - ScriptState::From(callback_object_creation_context); - v8::Isolate* isolate = callback_relevant_script_state_->GetIsolate(); - + v8::Isolate* isolate = callback_object->GetIsolate(); callback_object_.Set(isolate, callback_object); + + incumbent_script_state_ = ScriptState::From(isolate->GetIncumbentContext()); is_callback_object_callable_ = (single_op_or_not == kSingleOperation) && callback_object->IsCallable(); - incumbent_script_state_ = ScriptState::From(isolate->GetIncumbentContext()); + + // Set |callback_relevant_script_state_| iff the creation context and the + // incumbent context are the same origin-domain. Otherwise, leave it as + // nullptr. + v8::Local<v8::Context> creation_context = callback_object->CreationContext(); + if (BindingSecurityForPlatform::ShouldAllowAccessToV8Context( + incumbent_script_state_->GetContext(), creation_context, + BindingSecurityForPlatform::ErrorReportOption::kDoNotReport)) { + callback_relevant_script_state_ = ScriptState::From(creation_context); + } } void CallbackInterfaceBase::Trace(Visitor* visitor) { @@ -34,15 +41,35 @@ ScriptState* CallbackInterfaceBase::CallbackRelevantScriptStateOrReportError( const char* interface, const char* operation) { - // TODO(yukishiino): Implement this function. - return callback_relevant_script_state_; + if (callback_relevant_script_state_) + return callback_relevant_script_state_; + + // Report a SecurityError due to a cross origin callback object. + v8::TryCatch try_catch(GetIsolate()); + try_catch.SetVerbose(true); + ExceptionState exception_state( + GetIsolate(), ExceptionState::kExecutionContext, interface, operation); + ScriptState::Scope incumbent_scope(incumbent_script_state_); + exception_state.ThrowSecurityError( + "An invocation of the provided callback failed due to cross origin " + "access."); + return nullptr; } ScriptState* CallbackInterfaceBase::CallbackRelevantScriptStateOrThrowException( const char* interface, const char* operation) { - // TODO(yukishiino): Implement this function. - return callback_relevant_script_state_; + if (callback_relevant_script_state_) + return callback_relevant_script_state_; + + // Throw a SecurityError due to a cross origin callback object. + ExceptionState exception_state( + GetIsolate(), ExceptionState::kExecutionContext, interface, operation); + ScriptState::Scope incumbent_scope(incumbent_script_state_); + exception_state.ThrowSecurityError( + "An invocation of the provided callback failed due to cross origin " + "access."); + return nullptr; } V8PersistentCallbackInterfaceBase::V8PersistentCallbackInterfaceBase(
diff --git a/third_party/blink/renderer/platform/bindings/callback_interface_base.h b/third_party/blink/renderer/platform/bindings/callback_interface_base.h index 0108ac45..9eba0bc4 100644 --- a/third_party/blink/renderer/platform/bindings/callback_interface_base.h +++ b/third_party/blink/renderer/platform/bindings/callback_interface_base.h
@@ -84,13 +84,13 @@ } protected: - CallbackInterfaceBase(v8::Local<v8::Object> callback_object, - v8::Local<v8::Context> callback_object_creation_context, - SingleOperationOrNot); + explicit CallbackInterfaceBase(v8::Local<v8::Object> callback_object, + SingleOperationOrNot); // Returns true iff the callback interface is a single operation callback // interface and the callback interface type value is callable. bool IsCallbackObjectCallable() const { return is_callback_object_callable_; } + ScriptState* IncumbentScriptState() { return incumbent_script_state_; } private:
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc index f8c7b22..c88080a 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.cc
@@ -519,6 +519,7 @@ void PaintArtifactCompositor::LayerizeGroup( const PaintArtifact& paint_artifact, + const Settings& settings, Vector<PendingLayer>& pending_layers, const EffectPaintPropertyNode& current_group, Vector<PaintChunk>::const_iterator& chunk_it) { @@ -579,8 +580,8 @@ // Case C: The following chunks belong to a subgroup. Process them by // a recursion call. wtf_size_t first_layer_in_subgroup = pending_layers.size(); - LayerizeGroup(paint_artifact, pending_layers, *unaliased_subgroup, - chunk_it); + LayerizeGroup(paint_artifact, settings, pending_layers, + *unaliased_subgroup, chunk_it); // Now the chunk iterator stepped over the subgroup we just saw. // If the subgroup generated 2 or more layers then the subgroup must be // composited to satisfy grouping requirement. @@ -625,11 +626,12 @@ void PaintArtifactCompositor::CollectPendingLayers( const PaintArtifact& paint_artifact, + const Settings& settings, Vector<PendingLayer>& pending_layers) { Vector<PaintChunk>::const_iterator cursor = paint_artifact.PaintChunks().begin(); - LayerizeGroup(paint_artifact, pending_layers, EffectPaintPropertyNode::Root(), - cursor); + LayerizeGroup(paint_artifact, settings, pending_layers, + EffectPaintPropertyNode::Root(), cursor); DCHECK_EQ(paint_artifact.PaintChunks().end(), cursor); } @@ -753,7 +755,8 @@ void PaintArtifactCompositor::Update( scoped_refptr<const PaintArtifact> paint_artifact, CompositorElementIdSet& composited_element_ids, - TransformPaintPropertyNode* viewport_scale_node) { + const ViewportProperties& viewport_properties, + const Settings& settings) { DCHECK(root_layer_); // The tree will be null after detaching and this update can be ignored. @@ -779,13 +782,13 @@ PropertyTreeManager property_tree_manager( *this, *host->property_trees(), root_layer_.get(), &layer_list_builder); Vector<PendingLayer, 0> pending_layers; - CollectPendingLayers(*paint_artifact, pending_layers); + CollectPendingLayers(*paint_artifact, settings, pending_layers); cc::LayerTreeHost::ViewportPropertyIds viewport_property_ids; - if (viewport_scale_node) { + if (viewport_properties.page_scale) { viewport_property_ids.page_scale_transform = property_tree_manager.EnsureCompositorPageScaleTransformNode( - viewport_scale_node); + viewport_properties.page_scale); } if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) host->RegisterViewportPropertyIds(viewport_property_ids);
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h index 8f84f0f..b14654f 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h
@@ -69,13 +69,22 @@ new PaintArtifactCompositor(std::move(scroll_callback))); } + struct ViewportProperties { + const TransformPaintPropertyNode* page_scale = nullptr; + }; + + struct Settings { + bool prefer_compositing_to_lcd_text = false; + }; + // Updates the layer tree to match the provided paint artifact. // // Populates |composited_element_ids| with the CompositorElementId of all // animations for which we saw a paint chunk and created a layer. void Update(scoped_refptr<const PaintArtifact>, CompositorElementIdSet& composited_element_ids, - TransformPaintPropertyNode* viewport_scale_node); + const ViewportProperties& viewport_properties, + const Settings& settings); // The root layer of the tree managed by this object. cc::Layer* RootLayer() const { return root_layer_.get(); } @@ -154,7 +163,9 @@ // Collects the PaintChunks into groups which will end up in the same // cc layer. This is the entry point of the layerization algorithm. void CollectPendingLayers(const PaintArtifact&, + const Settings& settings, Vector<PendingLayer>& pending_layers); + // This is the internal recursion of collectPendingLayers. This function // loops over the list of paint chunks, scoped by an isolated group // (i.e. effect node). Inside of the loop, chunks are tested for overlap @@ -173,6 +184,7 @@ // overlap with other chunks in the parent group, if grouping requirement // can be satisfied (and the effect node has no direct reason). static void LayerizeGroup(const PaintArtifact&, + const Settings& settings, Vector<PendingLayer>& pending_layers, const EffectPaintPropertyNode&, Vector<PaintChunk>::const_iterator& chunk_cursor);
diff --git a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc index d7287772..3dc8a95 100644 --- a/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc +++ b/third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
@@ -131,18 +131,16 @@ Update(artifact, element_ids); } - void Update(scoped_refptr<const PaintArtifact> artifact, - CompositorElementIdSet& element_ids) { - // Pass nullptr for the visual viewport paint property nodes since we're - // really just checking the internals of PaintArtifactCompositor. - Update(artifact, element_ids, nullptr); - } + using ViewportProperties = PaintArtifactCompositor::ViewportProperties; + using Settings = PaintArtifactCompositor::Settings; - void Update(scoped_refptr<const PaintArtifact> artifact, - CompositorElementIdSet& element_ids, - TransformPaintPropertyNode* viewport_scale_transform_node) { + void Update( + scoped_refptr<const PaintArtifact> artifact, + CompositorElementIdSet& element_ids, + const ViewportProperties& viewport_properties = ViewportProperties(), + const Settings& settings = Settings()) { paint_artifact_compositor_->Update(artifact, element_ids, - viewport_scale_transform_node); + viewport_properties, settings); layer_tree_->layer_tree_host()->LayoutAndUpdateLayers(); } @@ -3255,8 +3253,10 @@ TransformPaintPropertyNode::Root(), std::move(transform_state)); TestPaintArtifact artifact; + ViewportProperties viewport_properties; + viewport_properties.page_scale = scale_transform_node.get(); CompositorElementIdSet element_ids; - Update(artifact.Build(), element_ids, scale_transform_node.get()); + Update(artifact.Build(), element_ids, viewport_properties); cc::TransformTree& transform_tree = GetPropertyTrees().transform_tree; cc::TransformNode* cc_transform_node = transform_tree.FindNodeFromElementId(
diff --git a/third_party/blink/renderer/platform/weborigin/kurl.cc b/third_party/blink/renderer/platform/weborigin/kurl.cc index 19f1439..268bfbd0 100644 --- a/third_party/blink/renderer/platform/weborigin/kurl.cc +++ b/third_party/blink/renderer/platform/weborigin/kurl.cc
@@ -619,14 +619,11 @@ ReplaceComponents(replacements); } -String DecodeURLEscapeSequences(const String& string, - DecodeURLResult* optional_result) { +String DecodeURLEscapeSequences(const String& string, DecodeURLMode mode) { StringUTF8Adaptor string_utf8(string); url::RawCanonOutputT<base::char16> unescaped; - DecodeURLResult result = url::DecodeURLEscapeSequences( - string_utf8.Data(), string_utf8.length(), &unescaped); - if (optional_result) - *optional_result = result; + url::DecodeURLEscapeSequences(string_utf8.Data(), string_utf8.length(), mode, + &unescaped); return StringImpl::Create8BitIfPossible( reinterpret_cast<UChar*>(unescaped.data()), unescaped.length()); }
diff --git a/third_party/blink/renderer/platform/weborigin/kurl.h b/third_party/blink/renderer/platform/weborigin/kurl.h index 9dfcab29..617c3944 100644 --- a/third_party/blink/renderer/platform/weborigin/kurl.h +++ b/third_party/blink/renderer/platform/weborigin/kurl.h
@@ -293,8 +293,7 @@ PLATFORM_EXPORT bool IsValidProtocol(const String&); -using DecodeURLResult = url::DecodeURLResult; - +using DecodeURLMode = url::DecodeURLMode; // Unescapes the given string using URL escaping rules. // // DANGER: If the URL has "%00" in it, the resulting string will have embedded @@ -302,9 +301,11 @@ // // This function is also used to decode javascript: URLs and as a general // purpose unescaping function. -// TODO(tkent): Remove the second argument after collecting data. +// +// Caution: Specifying kUTF8OrIsomorphic to the second argument doesn't conform +// to specifications in many cases. PLATFORM_EXPORT String DecodeURLEscapeSequences(const String&, - DecodeURLResult* = nullptr); + DecodeURLMode mode); PLATFORM_EXPORT String EncodeWithURLEscapeSequences(const String&);
diff --git a/third_party/blink/renderer/platform/weborigin/kurl_test.cc b/third_party/blink/renderer/platform/weborigin/kurl_test.cc index ebc778a..1224900 100644 --- a/third_party/blink/renderer/platform/weborigin/kurl_test.cc +++ b/third_party/blink/renderer/platform/weborigin/kurl_test.cc
@@ -234,22 +234,26 @@ for (size_t i = 0; i < arraysize(decode_cases); i++) { String input(decode_cases[i].input); - String str = DecodeURLEscapeSequences(input); + String str = + DecodeURLEscapeSequences(input, DecodeURLMode::kUTF8OrIsomorphic); EXPECT_STREQ(decode_cases[i].output, str.Utf8().data()); } // Our decode should decode %00 - String zero = DecodeURLEscapeSequences("%00"); + String zero = + DecodeURLEscapeSequences("%00", DecodeURLMode::kUTF8OrIsomorphic); EXPECT_STRNE("%00", zero.Utf8().data()); // Decode UTF-8. - String decoded = DecodeURLEscapeSequences("%e6%bc%a2%e5%ad%97"); + String decoded = DecodeURLEscapeSequences("%e6%bc%a2%e5%ad%97", + DecodeURLMode::kUTF8OrIsomorphic); const UChar kDecodedExpected[] = {0x6F22, 0x5b57}; EXPECT_EQ(String(kDecodedExpected, arraysize(kDecodedExpected)), decoded); // Test the error behavior for invalid UTF-8 (we differ from WebKit here). // %e4 %a0 are invalid for UTF-8, but %e5%a5%bd is valid. - String invalid = DecodeURLEscapeSequences("%e4%a0%e5%a5%bd"); + String invalid = DecodeURLEscapeSequences("%e4%a0%e5%a5%bd", + DecodeURLMode::kUTF8OrIsomorphic); UChar invalid_expected_helper[6] = {0x00e4, 0x00a0, 0x00e5, 0x00a5, 0x00bd, 0}; String invalid_expected(
diff --git a/third_party/blink/renderer/platform/weborigin/security_origin.cc b/third_party/blink/renderer/platform/weborigin/security_origin.cc index 81b8fa1..cd541ccd 100644 --- a/third_party/blink/renderer/platform/weborigin/security_origin.cc +++ b/third_party/blink/renderer/platform/weborigin/security_origin.cc
@@ -537,7 +537,8 @@ scoped_refptr<SecurityOrigin> SecurityOrigin::Create(const String& protocol, const String& host, uint16_t port) { - DCHECK_EQ(host, DecodeURLEscapeSequences(host)); + DCHECK_EQ(host, + DecodeURLEscapeSequences(host, DecodeURLMode::kUTF8OrIsomorphic)); String port_part = port ? ":" + String::Number(port) : String(); return Create(KURL(NullURL(), protocol + "://" + host + port_part + "/"));
diff --git a/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer.py b/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer.py index afa44cb..2015d800 100644 --- a/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer.py +++ b/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer.py
@@ -44,10 +44,10 @@ for port_name in port_names: self._ports[port_name] = host.port_factory.get(port_name) - self._layout_tests_dir = default_port.layout_tests_dir() - self._parent_of_tests = self._filesystem.dirname(self._layout_tests_dir) - self._layout_tests_dir_name = self._filesystem.relpath( - self._layout_tests_dir, self._parent_of_tests) + self._web_tests_dir = default_port.web_tests_dir() + self._parent_of_tests = self._filesystem.dirname(self._web_tests_dir) + self._web_tests_dir_name = self._filesystem.relpath( + self._web_tests_dir, self._parent_of_tests) # Only used by unit tests. self.new_results_by_directory = [] @@ -56,7 +56,7 @@ # A visualization of baseline fallback: # https://docs.google.com/drawings/d/13l3IUlSE99RoKjDwEWuY1O77simAhhF6Wi0fZdkSaMA/ # The full document with more details: - # https://chromium.googlesource.com/chromium/src/+/master/docs/testing/layout_test_baseline_fallback.md + # https://chromium.googlesource.com/chromium/src/+/master/docs/testing/web_test_baseline_fallback.md # The virtual and non-virtual subtrees are identical, with the virtual # root being the special node having multiple parents and connecting the # two trees. We patch the virtual subtree to cut its dependencies on the @@ -195,7 +195,7 @@ Returns: The platform name, or '(generic)' if unable to make a guess. """ - platform_dir = self._layout_tests_dir_name + self._filesystem.sep + 'platform' + self._filesystem.sep + platform_dir = self._web_tests_dir_name + self._filesystem.sep + 'platform' + self._filesystem.sep if filename.startswith(platform_dir): return filename.replace(platform_dir, '').split(self._filesystem.sep)[0] platform_dir = self._filesystem.join(self._parent_of_tests, platform_dir) @@ -239,7 +239,7 @@ # independently. If an immediate predecessor is missing a baseline, find # its non-virtual fallback and copy over. _log.debug('Copying non-virtual baselines to the virtual subtree to make it independent.') - virtual_root_baseline_path = self._filesystem.join(self._layout_tests_dir, baseline_name) + virtual_root_baseline_path = self._filesystem.join(self._web_tests_dir, baseline_name) if self._filesystem.exists(virtual_root_baseline_path): return @@ -252,7 +252,7 @@ self._walk_immediate_predecessors_of_virtual_root(test_name, extension, baseline_name, patcher) def _optimize_virtual_root(self, test_name, extension, baseline_name): - virtual_root_baseline_path = self._filesystem.join(self._layout_tests_dir, baseline_name) + virtual_root_baseline_path = self._filesystem.join(self._web_tests_dir, baseline_name) if self._filesystem.exists(virtual_root_baseline_path): _log.debug('Virtual root baseline found. Checking if we can remove it.') self._try_to_remove_virtual_root(test_name, baseline_name, virtual_root_baseline_path) @@ -294,7 +294,7 @@ def _baseline_root(self): """Returns the name of the root (generic) baseline directory.""" - return self._layout_tests_dir_name + return self._web_tests_dir_name def _baseline_search_path(self, port): """Returns the baseline search path (a list of absolute paths) of the @@ -476,7 +476,7 @@ class ResultDigest(object): """Digest of a result file for fast comparison. - A result file can be any actual or expected output from a layout test, + A result file can be any actual or expected output from a web test, including text and image. SHA1 is used internally to digest the file. """
diff --git a/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer_unittest.py b/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer_unittest.py index 0082145..f0c1932 100644 --- a/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer_unittest.py +++ b/third_party/blink/tools/blinkpy/common/checkout/baseline_optimizer_unittest.py
@@ -92,22 +92,22 @@ ['linux-trusty', 'mac-mac10.10', 'mac-mac10.11', 'mac-mac10.12', 'mac-mac10.13', 'win-win10']) def _assert_optimization(self, results_by_directory, directory_to_new_results, baseline_dirname='', suffix='txt'): - layout_tests_dir = PathFinder(self.fs).layout_tests_dir() + web_tests_dir = PathFinder(self.fs).web_tests_dir() test_name = 'mock-test.html' baseline_name = 'mock-test-expected.' + suffix self.fs.write_text_file( - self.fs.join(layout_tests_dir, 'VirtualTestSuites'), + self.fs.join(web_tests_dir, 'VirtualTestSuites'), '[{"prefix": "gpu", "base": "fast/canvas", "args": ["--foo"]}]') for dirname, contents in results_by_directory.items(): - self.fs.write_binary_file(self.fs.join(layout_tests_dir, dirname, baseline_name), contents) + self.fs.write_binary_file(self.fs.join(web_tests_dir, dirname, baseline_name), contents) baseline_optimizer = BaselineOptimizer(self.host, self.host.port_factory.get(), self.host.port_factory.all_port_names()) self.assertTrue(baseline_optimizer.optimize( self.fs.join(baseline_dirname, test_name), suffix)) for dirname, contents in directory_to_new_results.items(): - path = self.fs.join(layout_tests_dir, dirname, baseline_name) + path = self.fs.join(web_tests_dir, dirname, baseline_name) if contents is None: # Check files that are explicitly marked as absent. self.assertFalse(self.fs.exists(path), '%s should not exist after optimization' % path) @@ -115,13 +115,13 @@ self.assertEqual(self.fs.read_binary_file(path), contents, 'Content of %s != "%s"' % (path, contents)) for dirname in results_by_directory: - path = self.fs.join(layout_tests_dir, dirname, baseline_name) + path = self.fs.join(web_tests_dir, dirname, baseline_name) if dirname not in directory_to_new_results or directory_to_new_results[dirname] is None: self.assertFalse(self.fs.exists(path), '%s should not exist after optimization' % path) def _assert_reftest_optimization(self, results_by_directory, directory_to_new_results, test_path='', baseline_dirname=''): - layout_tests_dir = PathFinder(self.fs).layout_tests_dir() - self.fs.write_text_file(self.fs.join(layout_tests_dir, test_path, 'mock-test-expected.html'), 'ref') + web_tests_dir = PathFinder(self.fs).web_tests_dir() + self.fs.write_text_file(self.fs.join(web_tests_dir, test_path, 'mock-test-expected.html'), 'ref') self._assert_optimization(results_by_directory, directory_to_new_results, baseline_dirname, suffix='png') def test_linux_redundant_with_win(self):
diff --git a/third_party/blink/tools/blinkpy/common/config/builders.json b/third_party/blink/tools/blinkpy/common/config/builders.json index d606556..f0cc324 100644 --- a/third_party/blink/tools/blinkpy/common/config/builders.json +++ b/third_party/blink/tools/blinkpy/common/config/builders.json
@@ -92,6 +92,7 @@ "is_try_builder": true }, "android_blink_rel": { + "bucket": "master.tryserver.chromium.android", "port_name": "android-kitkat", "specifiers": ["KitKat", "Release"], "is_try_builder": true
diff --git a/third_party/blink/tools/blinkpy/common/host_mock.py b/third_party/blink/tools/blinkpy/common/host_mock.py index 3b317477..2131a019 100644 --- a/third_party/blink/tools/blinkpy/common/host_mock.py +++ b/third_party/blink/tools/blinkpy/common/host_mock.py
@@ -93,7 +93,7 @@ 'is_try_builder': True, }, 'android_blink_rel': { - 'bucket': 'master.tryserver.chromium.android', + 'bucket': 'luci.chromium.try', 'port_name': 'android-kitkat', 'specifiers': ['KitKat', 'Release'], 'is_try_builder': True, @@ -113,7 +113,7 @@ def _add_base_manifest_to_mock_filesystem(self, filesystem): path_finder = PathFinder(filesystem) - external_dir = path_finder.path_from_layout_tests('external') + external_dir = path_finder.path_from_web_tests('external') filesystem.maybe_make_directory(filesystem.join(external_dir, 'wpt')) # This filename should match the constant BASE_MANIFEST_NAME.
diff --git a/third_party/blink/tools/blinkpy/common/net/buildbot.py b/third_party/blink/tools/blinkpy/common/net/buildbot.py index 3f8b6ac..58ecbe1 100644 --- a/third_party/blink/tools/blinkpy/common/net/buildbot.py +++ b/third_party/blink/tools/blinkpy/common/net/buildbot.py
@@ -110,6 +110,9 @@ """Returns a WebTestResults object for results from a given Build. Uses full_results.json if full is True, otherwise failing_results.json. """ + if not build.builder_name or not build.build_number: + _log.debug('Builder name or build number is None') + return None return self.fetch_web_test_results( self.results_url(build.builder_name, build.build_number, step_name=self.get_layout_test_step_name(build)), @@ -117,6 +120,10 @@ @memoized def get_layout_test_step_name(self, build): + if not build.builder_name or not build.build_number: + _log.debug('Builder name or build number is None') + return None + url = '%s/testfile?%s' % (TEST_RESULTS_SERVER, urllib.urlencode({ 'builder': build.builder_name, 'buildnumber': build.build_number,
diff --git a/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py b/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py index 32bef0b..5c15a51 100644 --- a/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py +++ b/third_party/blink/tools/blinkpy/common/net/buildbot_unittest.py
@@ -84,7 +84,7 @@ 'https://test-results.appspot.com/data/layout_results/B/results/layout-test-results/failing_results.json\n' ]) - def test_fetch_web_test_results_weird_step_name(self): + def test_fetch_results_with_weird_step_name(self): buildbot = BuildBot() def fetch_file(url): @@ -101,6 +101,10 @@ }) self.assertLog([]) + def test_fetch_results_without_build_number(self): + buildbot = BuildBot() + self.assertIsNone(buildbot.fetch_results(Build('builder', None))) + def test_get_step_name(self): buildbot = BuildBot() @@ -116,6 +120,10 @@ self.assertEqual(step_name, 'webkit_layout_tests (with patch)') self.assertLog([]) + def test_get_step_name_without_build_number(self): + buildbot = BuildBot() + self.assertIsNone(buildbot.get_layout_test_step_name(Build('builder', None))) + class BuildBotHelperFunctionTest(unittest.TestCase):
diff --git a/third_party/blink/tools/blinkpy/common/net/git_cl_unittest.py b/third_party/blink/tools/blinkpy/common/net/git_cl_unittest.py index 6fd5a5d..2181e11f 100644 --- a/third_party/blink/tools/blinkpy/common/net/git_cl_unittest.py +++ b/third_party/blink/tools/blinkpy/common/net/git_cl_unittest.py
@@ -52,7 +52,7 @@ ], [ 'git', 'cl', 'try', - '-B', 'master.tryserver.chromium.android', + '-B', 'luci.chromium.try', '-b', 'android_blink_rel', '--auth-refresh-token-json', 'token.json' ],
diff --git a/third_party/blink/tools/blinkpy/common/path_finder.py b/third_party/blink/tools/blinkpy/common/path_finder.py index 3fc8ce1..e4e9656 100644 --- a/third_party/blink/tools/blinkpy/common/path_finder.py +++ b/third_party/blink/tools/blinkpy/common/path_finder.py
@@ -101,7 +101,7 @@ TESTS_IN_BLINK = _does_blink_web_tests_exist() -# LayoutTests / web_tests path relative to the repository root. +# web_tests path relative to the repository root. # Path separators are always '/', and this contains the trailing '/'. RELATIVE_WEB_TESTS = 'third_party/blink/web_tests/' WEB_TESTS_LAST_COMPONENT = 'web_tests' @@ -118,8 +118,7 @@ def chromium_base(self): return self._filesystem.dirname(self._filesystem.dirname(self._blink_base())) - # TODO(tkent): Rename this to web_tests_dir(). - def layout_tests_dir(self): + def web_tests_dir(self): return self.path_from_chromium_base('third_party', 'blink', 'web_tests') def perf_tests_dir(self): @@ -146,8 +145,8 @@ def path_from_blink_tools(self, *comps): return self._filesystem.join(self._filesystem.join(self.chromium_base(), 'third_party', 'blink', 'tools'), *comps) - def path_from_layout_tests(self, *comps): - return self._filesystem.join(self.layout_tests_dir(), *comps) + def path_from_web_tests(self, *comps): + return self._filesystem.join(self.web_tests_dir(), *comps) @memoized def depot_tools_base(self):
diff --git a/third_party/blink/tools/blinkpy/common/path_finder_unittest.py b/third_party/blink/tools/blinkpy/common/path_finder_unittest.py index ec53f4da..13baca96 100644 --- a/third_party/blink/tools/blinkpy/common/path_finder_unittest.py +++ b/third_party/blink/tools/blinkpy/common/path_finder_unittest.py
@@ -21,20 +21,20 @@ finder.path_from_chromium_base('foo', 'bar.baz'), '/mock-checkout/foo/bar.baz') - def test_layout_tests_dir(self): + def test_web_tests_dir(self): finder = PathFinder(MockFileSystem()) self.assertEqual( - finder.layout_tests_dir(), + finder.web_tests_dir(), '/mock-checkout/' + RELATIVE_WEB_TESTS[:-1]) - def test_layout_tests_dir_with_backslash_sep(self): + def test_web_tests_dir_with_backslash_sep(self): filesystem = MockFileSystem() filesystem.sep = '\\' filesystem.path_to_module = lambda _: ( 'C:\\mock-checkout\\third_party\\blink\\tools\\blinkpy\\foo.py') finder = PathFinder(filesystem) self.assertEqual( - finder.layout_tests_dir(), + finder.web_tests_dir(), 'C:\\mock-checkout\\third_party\\blink\\web_tests') def test_perf_tests_dir(self): @@ -43,10 +43,10 @@ finder.perf_tests_dir(), '/mock-checkout/third_party/blink/perf_tests') - def test_path_from_layout_tests(self): + def test_path_from_web_tests(self): finder = PathFinder(MockFileSystem()) self.assertEqual( - finder.path_from_layout_tests('external', 'wpt'), + finder.path_from_web_tests('external', 'wpt'), '/mock-checkout/' + RELATIVE_WEB_TESTS + 'external/wpt') def test_depot_tools_base_not_found(self):
diff --git a/third_party/blink/tools/blinkpy/tool/commands/copy_existing_baselines_unittest.py b/third_party/blink/tools/blinkpy/tool/commands/copy_existing_baselines_unittest.py index 67ab390..2d143297 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/copy_existing_baselines_unittest.py +++ b/third_party/blink/tools/blinkpy/tool/commands/copy_existing_baselines_unittest.py
@@ -21,9 +21,9 @@ options_dict.update(kwargs) return optparse.Values(options_dict) - def baseline_path(self, path_from_layout_test_dir): + def baseline_path(self, path_from_web_test_dir): port = self.tool.port_factory.get() - return self.tool.filesystem.join(port.layout_tests_dir(), path_from_layout_test_dir) + return self.tool.filesystem.join(port.web_tests_dir(), path_from_web_test_dir) # The tests in this class all depend on the fall-back path graph # that is set up in |TestPort.FALLBACK_PATHS|.
diff --git a/third_party/blink/tools/blinkpy/tool/commands/flaky_tests.py b/third_party/blink/tools/blinkpy/tool/commands/flaky_tests.py index b4230ca1..80b0cf5d 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/flaky_tests.py +++ b/third_party/blink/tools/blinkpy/tool/commands/flaky_tests.py
@@ -116,7 +116,7 @@ port = tool.port_factory.get() # Skip any tests which are mentioned in the dashboard but not in our checkout: fs = tool.filesystem - lines = [line for line in lines if fs.exists(fs.join(port.layout_tests_dir(), line.path))] + lines = [line for line in lines if fs.exists(fs.join(port.web_tests_dir(), line.path))] test_names = [line.name for line in lines] flakiness_dashboard_url = self.FLAKINESS_DASHBOARD_URL % ','.join(test_names)
diff --git a/third_party/blink/tools/blinkpy/tool/commands/optimize_baselines_unittest.py b/third_party/blink/tools/blinkpy/tool/commands/optimize_baselines_unittest.py index 821ff40..6ddde1f 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/optimize_baselines_unittest.py +++ b/third_party/blink/tools/blinkpy/tool/commands/optimize_baselines_unittest.py
@@ -12,7 +12,7 @@ command_constructor = OptimizeBaselines def _write_test_file(self, port, path, contents): - abs_path = self.tool.filesystem.join(port.layout_tests_dir(), path) + abs_path = self.tool.filesystem.join(port.web_tests_dir(), path) self.tool.filesystem.write_text_file(abs_path, contents) def setUp(self): @@ -33,13 +33,13 @@ self.assertFalse( self.tool.filesystem.exists(self.tool.filesystem.join( - test_port.layout_tests_dir(), 'platform/mac/another/test-expected.txt'))) + test_port.web_tests_dir(), 'platform/mac/another/test-expected.txt'))) self.assertFalse( self.tool.filesystem.exists(self.tool.filesystem.join( - test_port.layout_tests_dir(), 'platform/mac/another/test-expected.png'))) + test_port.web_tests_dir(), 'platform/mac/another/test-expected.png'))) self.assertTrue( self.tool.filesystem.exists(self.tool.filesystem.join( - test_port.layout_tests_dir(), 'another/test-expected.txt'))) + test_port.web_tests_dir(), 'another/test-expected.txt'))) self.assertTrue( self.tool.filesystem.exists(self.tool.filesystem.join( - test_port.layout_tests_dir(), 'another/test-expected.png'))) + test_port.web_tests_dir(), 'another/test-expected.png')))
diff --git a/third_party/blink/tools/blinkpy/tool/commands/queries.py b/third_party/blink/tools/blinkpy/tool/commands/queries.py index dacafd20..9b14436 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/queries.py +++ b/third_party/blink/tools/blinkpy/tool/commands/queries.py
@@ -105,10 +105,10 @@ if options.paths: files = default_port.expectations_files() - layout_tests_dir = default_port.layout_tests_dir() + web_tests_dir = default_port.web_tests_dir() for file in files: - if file.startswith(layout_tests_dir): - file = file.replace(layout_tests_dir, WEB_TESTS_LAST_COMPONENT) + if file.startswith(web_tests_dir): + file = file.replace(web_tests_dir, WEB_TESTS_LAST_COMPONENT) print file return
diff --git a/third_party/blink/tools/blinkpy/tool/commands/rebaseline.py b/third_party/blink/tools/blinkpy/tool/commands/rebaseline.py index d84d694..f28b7f2 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/rebaseline.py +++ b/third_party/blink/tools/blinkpy/tool/commands/rebaseline.py
@@ -412,8 +412,8 @@ test_baseline_set: A TestBaselineSet instance, which represents a set of tests/platform combinations to rebaseline. """ - if self._tool.git().has_working_directory_changes(pathspec=self._layout_tests_dir()): - _log.error('There are uncommitted changes in the layout tests directory; aborting.') + if self._tool.git().has_working_directory_changes(pathspec=self._web_tests_dir()): + _log.error('There are uncommitted changes in the web tests directory; aborting.') return for test in sorted({t for t, _, _ in test_baseline_set}): @@ -458,12 +458,12 @@ baseline_paths = [] for test in test_baseline_set.all_tests(): filenames = [self._file_name_for_expected_result(test, suffix) for suffix in BASELINE_SUFFIX_LIST] - baseline_paths += [filesystem.join(self._layout_tests_dir(), filename) for filename in filenames] + baseline_paths += [filesystem.join(self._web_tests_dir(), filename) for filename in filenames] baseline_paths.sort() return baseline_paths - def _layout_tests_dir(self): - return self._tool.port_factory.get().layout_tests_dir() + def _web_tests_dir(self): + return self._tool.port_factory.get().web_tests_dir() def _suffixes_for_actual_failures(self, test, build): """Gets the baseline suffixes for actual mismatch failures in some results.
diff --git a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl.py b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl.py index 06bc32ae..fa24038 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl.py +++ b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl.py
@@ -21,7 +21,7 @@ class RebaselineCL(AbstractParallelRebaselineCommand): name = 'rebaseline-cl' help_text = 'Fetches new baselines for a CL from test runs on try bots.' - long_help = ('This command downloads new baselines for failing layout ' + long_help = ('This command downloads new baselines for failing web ' 'tests from archived try job test results. Cross-platform ' 'baselines are deduplicated after downloading. Without ' 'positional parameters or --test-name-file, all failing tests ' @@ -234,7 +234,7 @@ continue if status != TryJobStatus('COMPLETED', 'FAILURE'): # Only completed failed builds will contain actual failed - # layout tests to download baselines for. + # web tests to download baselines for. continue results_url = buildbot.results_url(build.builder_name, build.build_number) web_test_results = buildbot.fetch_results(build) @@ -311,26 +311,26 @@ return test_baseline_set def _test_base_path(self): - """Returns the relative path from the repo root to the layout tests.""" + """Returns the relative path from the repo root to the web tests.""" finder = PathFinder(self._tool.filesystem) return self._tool.filesystem.relpath( - finder.layout_tests_dir(), + finder.web_tests_dir(), finder.path_from_chromium_base()) + '/' - def _tests_to_rebaseline(self, build, layout_test_results): + def _tests_to_rebaseline(self, build, web_test_results): """Fetches a list of tests that should be rebaselined for some build. Args: build: A Build instance. - layout_test_results: A WebTestResults instance or None. + web_test_results: A WebTestResults instance or None. Returns: A sorted list of tests to rebaseline for this build. """ - if layout_test_results is None: + if web_test_results is None: return [] - unexpected_results = layout_test_results.didnt_run_as_expected_results() + unexpected_results = web_test_results.didnt_run_as_expected_results() tests = sorted( r.test_name() for r in unexpected_results if r.is_missing_baseline() or r.has_mismatch_result())
diff --git a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl_unittest.py b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl_unittest.py index 6976ba2..69bd42affb 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl_unittest.py +++ b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_cl_unittest.py
@@ -59,7 +59,7 @@ 'is_try_builder': True, }, }) - layout_test_results = WebTestResults({ + web_test_results = WebTestResults({ 'tests': { 'one': { 'crash.html': {'expected': 'PASS', 'actual': 'CRASH', 'is_unexpected': True}, @@ -75,7 +75,7 @@ }) for build in builds: - self.tool.buildbot.set_results(build, layout_test_results) + self.tool.buildbot.set_results(build, web_test_results) self.tool.buildbot.set_retry_sumary_json(build, json.dumps({ 'failures': [ 'one/flaky-fail.html', @@ -97,7 +97,7 @@ ] for test in tests: path = self.mac_port.host.filesystem.join( - self.mac_port.layout_tests_dir(), test) + self.mac_port.web_tests_dir(), test) self._write(path, 'contents') self.mac_port.host.filesystem.write_text_file( @@ -358,7 +358,7 @@ # one/flaky-fail.html is considered a real test to rebaseline. port = self.tool.port_factory.get('test-win-win7') path = port.host.filesystem.join( - port.layout_tests_dir(), 'one/flaky-fail.html') + port.web_tests_dir(), 'one/flaky-fail.html') self._write(path, 'contents') test_baseline_set = TestBaselineSet(self.tool) test_baseline_set.add(
diff --git a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_server.py b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_server.py index 27ff77d..fad77cd 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_server.py +++ b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_server.py
@@ -26,7 +26,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Starts a local HTTP server which displays layout test failures (given a test +"""Starts a local HTTP server which displays web test failures (given a test results directory), provides comparisons of expected and actual results (both images and text) and allows one-click rebaselining of tests. """ @@ -40,9 +40,9 @@ class TestConfig(object): - def __init__(self, test_port, layout_tests_directory, results_directory, platforms, host): + def __init__(self, test_port, web_tests_directory, results_directory, platforms, host): self.test_port = test_port - self.layout_tests_directory = layout_tests_directory + self.web_tests_directory = web_tests_directory self.results_directory = results_directory self.platforms = platforms self.host = host @@ -88,9 +88,9 @@ results_json = json_results_generator.load_json(host.filesystem, results_json_path) port = tool.port_factory.get() - layout_tests_directory = port.layout_tests_dir() - platforms = host.filesystem.listdir(host.filesystem.join(layout_tests_directory, 'platform')) - self._test_config = TestConfig(port, layout_tests_directory, results_directory, platforms, host) + web_tests_directory = port.web_tests_dir() + platforms = host.filesystem.listdir(host.filesystem.join(web_tests_directory, 'platform')) + self._test_config = TestConfig(port, web_tests_directory, results_directory, platforms, host) print 'Gathering current baselines...' self._gather_baselines(results_json)
diff --git a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_test_unittest.py b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_test_unittest.py index 4e43e3139..7bc85ca 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_test_unittest.py +++ b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_test_unittest.py
@@ -30,7 +30,7 @@ port = self.tool.port_factory.get('test-win-win7') baseline_relative_path = 'platform/test-win-win10/failures/expected/image-expected.txt' - baseline_local_absolute_path = port.host.filesystem.join(port.layout_tests_dir(), baseline_relative_path) + baseline_local_absolute_path = port.host.filesystem.join(port.web_tests_dir(), baseline_relative_path) self._write(baseline_local_absolute_path, 'original win10 result') actual_result_url = ('https://test-results.appspot.com/data/layout_results/MOCK_Win10/' + 'results/layout-test-results/failures/expected/image-actual.txt') @@ -58,7 +58,7 @@ self.assertMultiLineEqual(self._read(baseline_local_absolute_path), 'new win10 result') self.assertFalse(self.tool.filesystem.exists(self.tool.filesystem.join( - port.layout_tests_dir(), 'platform/test-win-win7/failures/expected/image-expected.txt'))) + port.web_tests_dir(), 'platform/test-win-win7/failures/expected/image-expected.txt'))) self.assertMultiLineEqual( out, '{"remove-lines": [{"test": "failures/expected/image.html", "port_name": "test-win-win10"}]}\n')
diff --git a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_unittest.py b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_unittest.py index e54d5ee..6ad5402 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/rebaseline_unittest.py +++ b/third_party/blink/tools/blinkpy/tool/commands/rebaseline_unittest.py
@@ -53,7 +53,7 @@ # In AbstractParallelRebaselineCommand._rebaseline_commands, a default port # object is gotten using self.tool.port_factory.get(), which is used to get - # test paths -- and the layout tests directory may be different for the "test" + # test paths -- and the web tests directory may be different for the "test" # ports and real ports. Since only "test" ports are used in this class, # we can make the default port also a "test" port. self.original_port_factory_get = self.tool.port_factory.get @@ -72,7 +72,7 @@ def _expand(self, path): if self.tool.filesystem.isabs(path): return path - return self.tool.filesystem.join(self.mac_port.layout_tests_dir(), path) + return self.tool.filesystem.join(self.mac_port.web_tests_dir(), path) def _read(self, path): return self.tool.filesystem.read_text_file(self._expand(path)) @@ -702,7 +702,7 @@ host = MockBlinkTool() host.port_factory = MockPortFactory(host) port = host.port_factory.get() - base_dir = port.layout_tests_dir() + base_dir = port.web_tests_dir() host.filesystem.write_text_file(base_dir + '/a/x.html', '<html>') host.filesystem.write_text_file(base_dir + '/a/y.html', '<html>') host.filesystem.write_text_file(base_dir + '/a/z.html', '<html>')
diff --git a/third_party/blink/tools/blinkpy/w3c/chromium_finder.py b/third_party/blink/tools/blinkpy/w3c/chromium_finder.py index 72e4e41..a9665d62 100644 --- a/third_party/blink/tools/blinkpy/w3c/chromium_finder.py +++ b/third_party/blink/tools/blinkpy/w3c/chromium_finder.py
@@ -9,7 +9,7 @@ @memoized def absolute_chromium_wpt_dir(host): finder = PathFinder(host.filesystem) - return finder.path_from_layout_tests('external', 'wpt') + return finder.path_from_web_tests('external', 'wpt') @memoized
diff --git a/third_party/blink/tools/blinkpy/w3c/directory_owners_extractor.py b/third_party/blink/tools/blinkpy/w3c/directory_owners_extractor.py index 0e57805..e7b1264 100644 --- a/third_party/blink/tools/blinkpy/w3c/directory_owners_extractor.py +++ b/third_party/blink/tools/blinkpy/w3c/directory_owners_extractor.py
@@ -43,10 +43,10 @@ Returns: A dict mapping tuples of owner email addresses to lists of - owned directories (paths relative to the root of layout tests). + owned directories (paths relative to the root of web tests). """ email_map = collections.defaultdict(set) - external_root_owners = self.finder.path_from_layout_tests('external', 'OWNERS') + external_root_owners = self.finder.path_from_web_tests('external', 'OWNERS') for relpath in changed_files: # Try to find the first *non-empty* OWNERS file. absolute_path = self.finder.path_from_chromium_base(relpath) @@ -64,7 +64,7 @@ continue owned_directory = self.filesystem.dirname(owners_file) - owned_directory_relpath = self.filesystem.relpath(owned_directory, self.finder.layout_tests_dir()) + owned_directory_relpath = self.filesystem.relpath(owned_directory, self.finder.web_tests_dir()) email_map[tuple(owners)].add(owned_directory_relpath) return {owners: sorted(owned_directories) for owners, owned_directories in email_map.iteritems()} @@ -86,11 +86,11 @@ else self.finder.path_from_chromium_base(start_path)) directory = (abs_start_path if self.filesystem.isdir(abs_start_path) else self.filesystem.dirname(abs_start_path)) - external_root = self.finder.path_from_layout_tests('external') + external_root = self.finder.path_from_web_tests('external') if not directory.startswith(external_root): return None # Stop at web_tests, which is the parent of external_root. - while directory != self.finder.layout_tests_dir(): + while directory != self.finder.web_tests_dir(): owners_file = self.filesystem.join(directory, 'OWNERS') if self.filesystem.isfile(self.finder.path_from_chromium_base(owners_file)): return owners_file
diff --git a/third_party/blink/tools/blinkpy/w3c/import_notifier.py b/third_party/blink/tools/blinkpy/w3c/import_notifier.py index 37b7bfd..11e405a9 100644 --- a/third_party/blink/tools/blinkpy/w3c/import_notifier.py +++ b/third_party/blink/tools/blinkpy/w3c/import_notifier.py
@@ -88,7 +88,7 @@ for test_name in rebaselined_tests: test_without_ext, _ = self.host.filesystem.splitext(test_name) changed_baselines = [] - # TODO(robertma): Refactor this into layout_tests.port.base. + # TODO(robertma): Refactor this into web_tests.port.base. baseline_name = test_without_ext + '-expected.txt' for changed_file in changed_files: if changed_file.endswith(baseline_name): @@ -165,7 +165,7 @@ for directory, failures in self.new_failures_by_directory.iteritems(): summary = '[WPT] New failures introduced in {} by import {}'.format(directory, gerrit_url) - full_directory = self.host.filesystem.join(self.finder.layout_tests_dir(), directory) + full_directory = self.host.filesystem.join(self.finder.web_tests_dir(), directory) owners_file = self.host.filesystem.join(full_directory, 'OWNERS') is_wpt_notify_enabled = self.owners_extractor.is_wpt_notify_enabled(owners_file) @@ -214,7 +214,7 @@ A multi-line string. """ path_from_wpt = self.host.filesystem.relpath( - directory, self.finder.path_from_layout_tests('external', 'wpt')) + directory, self.finder.path_from_web_tests('external', 'wpt')) commit_list = '' for sha, subject in imported_commits: # subject is a Unicode string and can contain non-ASCII characters. @@ -238,12 +238,12 @@ test_name = self.default_port.lookup_virtual_test_base(test_name) # find_owners_file takes either a relative path from the *root* of the # repository, or an absolute path. - abs_test_path = self.finder.path_from_layout_tests(test_name) + abs_test_path = self.finder.path_from_web_tests(test_name) owners_file = self.owners_extractor.find_owners_file(self.host.filesystem.dirname(abs_test_path)) if not owners_file: return None owned_directory = self.host.filesystem.dirname(owners_file) - short_directory = self.host.filesystem.relpath(owned_directory, self.finder.layout_tests_dir()) + short_directory = self.host.filesystem.relpath(owned_directory, self.finder.web_tests_dir()) return short_directory def file_bugs(self, bugs, dry_run, service_account_key_json=None):
diff --git a/third_party/blink/tools/blinkpy/w3c/test_copier.py b/third_party/blink/tools/blinkpy/w3c/test_copier.py index 2ce4ab9..2aa9013 100644 --- a/third_party/blink/tools/blinkpy/w3c/test_copier.py +++ b/third_party/blink/tools/blinkpy/w3c/test_copier.py
@@ -39,7 +39,7 @@ _log = logging.getLogger(__name__) -# Directory for imported tests relative to the layout tests base directory. +# Directory for imported tests relative to the web tests base directory. DEST_DIR_NAME = 'external' class TestCopier(object): @@ -58,10 +58,10 @@ self.filesystem = self.host.filesystem self.path_finder = PathFinder(self.filesystem) - self.layout_tests_dir = self.path_finder.layout_tests_dir() + self.web_tests_dir = self.path_finder.web_tests_dir() self.destination_directory = self.filesystem.normpath( self.filesystem.join( - self.layout_tests_dir, + self.web_tests_dir, DEST_DIR_NAME, self.filesystem.basename(self.source_repo_path))) self.import_in_place = (self.source_repo_path == self.destination_directory) @@ -112,7 +112,7 @@ for filename in files: path_full = self.filesystem.join(root, filename) path_base = path_full.replace(self.source_repo_path + '/', '') - path_base = self.destination_directory.replace(self.layout_tests_dir + '/', '') + '/' + path_base + path_base = self.destination_directory.replace(self.web_tests_dir + '/', '') + '/' + path_base if path_base in paths_to_skip: if self.import_in_place: _log.debug('Pruning: %s', path_base) @@ -136,7 +136,7 @@ def find_paths_to_skip(self): paths_to_skip = set() port = self.host.port_factory.get() - w3c_import_expectations_path = self.path_finder.path_from_layout_tests('W3CImportExpectations') + w3c_import_expectations_path = self.path_finder.path_from_web_tests('W3CImportExpectations') w3c_import_expectations = self.filesystem.read_text_file(w3c_import_expectations_path) parser = TestExpectationParser(port, all_tests=(), is_lint_mode=False) expectation_lines = parser.parse(w3c_import_expectations_path, w3c_import_expectations) @@ -201,7 +201,7 @@ if not self.import_in_place: self.filesystem.maybe_make_directory(self.filesystem.dirname(dest_path)) - relpath = self.filesystem.relpath(dest_path, self.layout_tests_dir) + relpath = self.filesystem.relpath(dest_path, self.web_tests_dir) # FIXME: Maybe doing a file diff is in order here for existing files? # In other words, there's no sense in overwriting identical files, but # there's no harm in copying the identical thing.
diff --git a/third_party/blink/tools/blinkpy/w3c/test_importer.py b/third_party/blink/tools/blinkpy/w3c/test_importer.py index 1e687fc..74c094ff 100644 --- a/third_party/blink/tools/blinkpy/w3c/test_importer.py +++ b/third_party/blink/tools/blinkpy/w3c/test_importer.py
@@ -55,7 +55,7 @@ self.fs = host.filesystem self.finder = PathFinder(self.fs) self.chromium_git = self.host.git(self.finder.chromium_base()) - self.dest_path = self.finder.path_from_layout_tests('external', 'wpt') + self.dest_path = self.finder.path_from_web_tests('external', 'wpt') # A common.net.git_cl.GitCL instance. self.git_cl = None @@ -389,7 +389,7 @@ is_file_exportable(fs.relpath(fs.join(dirname, basename), self.finder.chromium_base()))) files_to_delete = self.fs.files_under(self.dest_path, file_filter=should_remove) for subpath in files_to_delete: - self.remove(self.finder.path_from_layout_tests('external', subpath)) + self.remove(self.finder.path_from_web_tests('external', subpath)) def _commit_changes(self, commit_message): _log.info('Committing changes.') @@ -423,7 +423,7 @@ # - the manifest path could be factored out to a common location, and # - the logic for reading the manifest could be factored out from here # and the Port class. - manifest_path = self.finder.path_from_layout_tests('external', 'wpt', 'MANIFEST.json') + manifest_path = self.finder.path_from_web_tests('external', 'wpt', 'MANIFEST.json') manifest = WPTManifest(self.fs.read_text_file(manifest_path)) wpt_urls = manifest.all_urls() @@ -433,7 +433,7 @@ # TODO(qyearsley): Remove this when this behavior is fixed. wpt_urls = [url.split('?')[0] for url in wpt_urls] - wpt_dir = self.finder.path_from_layout_tests('external', 'wpt') + wpt_dir = self.finder.path_from_web_tests('external', 'wpt') for full_path in baselines: rel_path = self.fs.relpath(full_path, wpt_dir) if not self._has_corresponding_test(rel_path, wpt_urls): @@ -608,12 +608,12 @@ self.host.filesystem.write_text_file(path, new_file_contents) def _list_deleted_tests(self): - """List of layout tests that have been deleted.""" + """List of web tests that have been deleted.""" # TODO(robertma): Improve Git.changed_files so that we can use it here. out = self.chromium_git.run(['diff', 'origin/master', '-M100%', '--diff-filter=D', '--name-only']) deleted_tests = [] for path in out.splitlines(): - test = self._relative_to_layout_test_dir(path) + test = self._relative_to_web_test_dir(path) if test: deleted_tests.append(test) return deleted_tests @@ -627,18 +627,18 @@ renamed_tests = {} for line in out.splitlines(): _, source_path, dest_path = line.split() - source_test = self._relative_to_layout_test_dir(source_path) - dest_test = self._relative_to_layout_test_dir(dest_path) + source_test = self._relative_to_web_test_dir(source_path) + dest_test = self._relative_to_web_test_dir(dest_path) if source_test and dest_test: renamed_tests[source_test] = dest_test return renamed_tests - def _relative_to_layout_test_dir(self, path_relative_to_repo_root): - """Returns a path that's relative to the layout tests directory.""" + def _relative_to_web_test_dir(self, path_relative_to_repo_root): + """Returns a path that's relative to the web tests directory.""" abs_path = self.finder.path_from_chromium_base(path_relative_to_repo_root) - if not abs_path.startswith(self.finder.layout_tests_dir()): + if not abs_path.startswith(self.finder.web_tests_dir()): return None - return self.fs.relpath(abs_path, self.finder.layout_tests_dir()) + return self.fs.relpath(abs_path, self.finder.web_tests_dir()) def _get_last_imported_wpt_revision(self): """Finds the last imported WPT revision."""
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py index 9ae21130..ce7695b 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater.py
@@ -26,7 +26,7 @@ MARKER_COMMENT = '# ====== New tests from wpt-importer added here ======' UMBRELLA_BUG = 'crbug.com/626703' -# TODO(robertma): Investigate reusing layout_tests.models.test_expectations and +# TODO(robertma): Investigate reusing web_tests.models.test_expectations and # alike in this module. SimpleTestResult = namedtuple('SimpleTestResult', ['expected', 'actual', 'bug']) @@ -114,7 +114,7 @@ def get_failing_results_dict(self, build): """Returns a nested dict of failing test results. - Retrieves a full list of layout test results from a builder result URL. + Retrieves a full list of web test results from a builder result URL. Collects the builder name, platform and a list of tests that did not run as expected. @@ -134,24 +134,24 @@ if port_name in self.ports_with_all_pass: # All tests passed, so there should be no failing results. return {} - layout_test_results = self.host.buildbot.fetch_results(build) - if layout_test_results is None: + web_test_results = self.host.buildbot.fetch_results(build) + if web_test_results is None: _log.warning('No results for build %s', build) self.ports_with_no_results.add(self.port_name(build)) return {} - failing_test_results = [result for result in layout_test_results.didnt_run_as_expected_results() if not result.did_pass()] + failing_test_results = [result for result in web_test_results.didnt_run_as_expected_results() if not result.did_pass()] return self.generate_results_dict(self.port_name(build), failing_test_results) @memoized def port_name(self, build): return self.host.builders.port_name_for_builder_name(build.builder_name) - def generate_results_dict(self, full_port_name, layout_test_results): + def generate_results_dict(self, full_port_name, web_test_results): """Makes a dict with results for one platform. Args: full_port_name: The fully-qualified port name, e.g. "win-win10". - layout_test_results: A list of WebTestResult objects. + web_test_results: A list of WebTestResult objects. Returns: A dictionary with the structure: { @@ -161,7 +161,7 @@ } """ test_dict = {} - for result in layout_test_results: + for result in web_test_results: test_name = result.test_name() if not self.port.is_wpt_test(test_name):
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py index 1e0dcc8..5308a22 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_expectations_updater_unittest.py
@@ -61,7 +61,7 @@ # Write a dummy manifest file, describing what tests exist. host.filesystem.write_text_file( - host.port_factory.get().layout_tests_dir() + '/external/wpt/MANIFEST.json', + host.port_factory.get().web_tests_dir() + '/external/wpt/MANIFEST.json', json.dumps({ 'items': { 'reftest': { @@ -469,7 +469,7 @@ def test_generate_results_dict(self): updater = WPTExpectationsUpdater(self.mock_host()) - layout_test_list = [ + web_test_list = [ WebTestResult( 'external/wpt/test/name.html', { 'expected': 'bar', @@ -478,7 +478,7 @@ 'has_stderr': True, }) ] - self.assertEqual(updater.generate_results_dict('test-mac-mac10.10', layout_test_list), { + self.assertEqual(updater.generate_results_dict('test-mac-mac10.10', web_test_list), { 'external/wpt/test/name.html': { 'test-mac-mac10.10': SimpleTestResult( expected='bar',
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_manifest.py b/third_party/blink/tools/blinkpy/w3c/wpt_manifest.py index 2876b3ae..7e18f3b 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_manifest.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_manifest.py
@@ -181,8 +181,8 @@ def ensure_manifest(host): """Updates the MANIFEST.json file, or generates if it does not exist.""" finder = PathFinder(host.filesystem) - manifest_path = finder.path_from_layout_tests('external', 'wpt', 'MANIFEST.json') - base_manifest_path = finder.path_from_layout_tests('external', BASE_MANIFEST_NAME) + manifest_path = finder.path_from_web_tests('external', 'wpt', 'MANIFEST.json') + base_manifest_path = finder.path_from_web_tests('external', BASE_MANIFEST_NAME) if not host.filesystem.exists(base_manifest_path): _log.error('Manifest base not found at "%s".', base_manifest_path) @@ -196,7 +196,7 @@ host.filesystem.remove(manifest_path) host.filesystem.copyfile(base_manifest_path, manifest_path) - wpt_path = finder.path_from_layout_tests('external', 'wpt') + wpt_path = finder.path_from_web_tests('external', 'wpt') WPTManifest.generate_manifest(host, wpt_path) _log.debug('Manifest generation completed.')
diff --git a/third_party/blink/tools/blinkpy/web_tests/controllers/manager.py b/third_party/blink/tools/blinkpy/web_tests/controllers/manager.py index dc09e868..661ccdbd 100644 --- a/third_party/blink/tools/blinkpy/web_tests/controllers/manager.py +++ b/third_party/blink/tools/blinkpy/web_tests/controllers/manager.py
@@ -27,7 +27,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""The Manager orchestrates the overall process of running layout tests. +"""The Manager orchestrates the overall process of running web tests. This includes finding tests to run, reading the test expectations, starting the required helper servers, deciding the order and way to @@ -63,7 +63,7 @@ class Manager(object): - """A class for managing running a series of layout tests.""" + """A class for managing running a series of web tests.""" HTTP_SUBDIR = 'http' PERF_SUBDIR = 'perf' @@ -565,7 +565,7 @@ def _copy_results_html_file(self, destination_dir, filename): """Copies a file from the template directory to the results directory.""" - template_dir = self._path_finder.path_from_layout_tests('fast', 'harness') + template_dir = self._path_finder.path_from_web_tests('fast', 'harness') source_path = self._filesystem.join(template_dir, filename) destination_path = self._filesystem.join(destination_dir, filename) # Note that the results.html template file won't exist when
diff --git a/third_party/blink/tools/blinkpy/web_tests/controllers/single_test_runner.py b/third_party/blink/tools/blinkpy/web_tests/controllers/single_test_runner.py index e6782ee..fd4774c 100644 --- a/third_party/blink/tools/blinkpy/web_tests/controllers/single_test_runner.py +++ b/third_party/blink/tools/blinkpy/web_tests/controllers/single_test_runner.py
@@ -201,7 +201,7 @@ # Remove |output_path| if it exists and is not the generic expectation to # avoid extra baseline if the new baseline is the same as the fallback baseline. - generic_dir = fs.join(port.layout_tests_dir(), + generic_dir = fs.join(port.web_tests_dir(), fs.dirname(port.lookup_virtual_test_base(self._test_name) or self._test_name)) if (not data or output_dir != generic_dir) and fs.exists(output_path): _log.info('Removing the current baseline "%s"', port.relative_test_filename(output_path))
diff --git a/third_party/blink/tools/blinkpy/web_tests/controllers/web_test_finder.py b/third_party/blink/tools/blinkpy/web_tests/controllers/web_test_finder.py index 9a8c96e1..3a2cdbc 100644 --- a/third_party/blink/tools/blinkpy/web_tests/controllers/web_test_finder.py +++ b/third_party/blink/tools/blinkpy/web_tests/controllers/web_test_finder.py
@@ -45,7 +45,7 @@ self._port = port self._options = options self._filesystem = self._port.host.filesystem - self.LAYOUT_TESTS_DIRECTORIES = ('src', 'third_party', 'blink', 'web_tests') + self.WEB_TESTS_DIRECTORIES = ('src', 'third_party', 'blink', 'web_tests') def find_tests(self, args, test_list=None, fastest_percentile=None): paths = self._strip_test_dir_prefixes(args) @@ -118,11 +118,11 @@ def _strip_test_dir_prefix(self, path): # Remove src/third_party/blink/web_tests/ from the front of the test path, # or any subset of these. - for i in range(len(self.LAYOUT_TESTS_DIRECTORIES)): + for i in range(len(self.WEB_TESTS_DIRECTORIES)): # Handle both "web_tests/foo/bar.html" and "web_tests\foo\bar.html" if # the filesystem uses '\\' as a directory separator for separator in (self._port.TEST_PATH_SEPARATOR, self._filesystem.sep): - directory_prefix = separator.join(self.LAYOUT_TESTS_DIRECTORIES[i:]) + separator + directory_prefix = separator.join(self.WEB_TESTS_DIRECTORIES[i:]) + separator if path.startswith(directory_prefix): return path[len(directory_prefix):] return path
diff --git a/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations.py b/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations.py index 5b7acc9..ef05641 100644 --- a/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations.py +++ b/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations.py
@@ -82,7 +82,7 @@ def check_virtual_test_suites(host, options): port = host.port_factory.get(options=options) fs = host.filesystem - layout_tests_dir = port.layout_tests_dir() + web_tests_dir = port.web_tests_dir() virtual_suites = port.virtual_test_suites() failures = [] @@ -91,9 +91,9 @@ # - a top-level README.md (e.g. virtual/foo/README.md) # - a README.txt for each covered dir/file (e.g. # virtual/foo/http/tests/README.txt, virtual/foo/fast/README.txt, ...) - comps = [layout_tests_dir] + suite.name.split('/') + ['README.txt'] + comps = [web_tests_dir] + suite.name.split('/') + ['README.txt'] path_to_readme_txt = fs.join(*comps) - comps = [layout_tests_dir] + suite.name.split('/')[:2] + ['README.md'] + comps = [web_tests_dir] + suite.name.split('/')[:2] + ['README.md'] path_to_readme_md = fs.join(*comps) if not fs.exists(path_to_readme_txt) and not fs.exists(path_to_readme_md): failure = '{} and {} are both missing (each virtual suite must have one).'.format( @@ -107,7 +107,7 @@ def check_smoke_tests(host, options): port = host.port_factory.get(options=options) - smoke_tests_file = host.filesystem.join(port.layout_tests_dir(), 'SmokeTests') + smoke_tests_file = host.filesystem.join(port.web_tests_dir(), 'SmokeTests') failures = [] if not host.filesystem.exists(smoke_tests_file): return failures
diff --git a/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations_unittest.py b/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations_unittest.py index 16e695a1..3102a17 100644 --- a/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/lint_test_expectations_unittest.py
@@ -71,7 +71,7 @@ def extra_expectations_files(self): return ['/fake-port-base-directory/web_tests/ExtraExpectations'] - def layout_tests_dir(self): + def web_tests_dir(self): return '/fake-port-base-directory/web_tests'
diff --git a/third_party/blink/tools/blinkpy/web_tests/models/test_expectations_unittest.py b/third_party/blink/tools/blinkpy/web_tests/models/test_expectations_unittest.py index a81fbaa..8331dea 100644 --- a/third_party/blink/tools/blinkpy/web_tests/models/test_expectations_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/models/test_expectations_unittest.py
@@ -168,8 +168,8 @@ def test_parse_warning(self): try: filesystem = self._port.host.filesystem - filesystem.write_text_file(filesystem.join(self._port.layout_tests_dir(), 'disabled-test.html-disabled'), 'content') - filesystem.write_text_file(filesystem.join(self._port.layout_tests_dir(), 'test-to-rebaseline.html'), 'content') + filesystem.write_text_file(filesystem.join(self._port.web_tests_dir(), 'disabled-test.html-disabled'), 'content') + filesystem.write_text_file(filesystem.join(self._port.web_tests_dir(), 'test-to-rebaseline.html'), 'content') self.parse_exp('Bug(user) [ FOO ] failures/expected/text.html [ Failure ]\n' 'Bug(user) non-existent-test.html [ Failure ]\n' 'Bug(user) disabled-test.html-disabled [ Failure ]\n', @@ -242,7 +242,7 @@ self.assert_exp('failures/expected/text.html', FAIL) self.assertNotIn( self._port.host.filesystem.join( - self._port.layout_tests_dir(), + self._port.web_tests_dir(), 'failures/expected/text.html'), self._exp.get_tests_with_result_type(SKIP)) @@ -284,7 +284,7 @@ options=optparse.Values({'ignore_tests': ignore_tests})) port.host.filesystem.write_text_file( port.host.filesystem.join( - port.layout_tests_dir(), 'failures/expected/text.html'), + port.web_tests_dir(), 'failures/expected/text.html'), 'foo') expectations_dict = OrderedDict() expectations_dict['expectations'] = expectations
diff --git a/third_party/blink/tools/blinkpy/web_tests/models/test_run_results.py b/third_party/blink/tools/blinkpy/web_tests/models/test_run_results.py index fff5ba5..a270136 100644 --- a/third_party/blink/tools/blinkpy/web_tests/models/test_run_results.py +++ b/third_party/blink/tools/blinkpy/web_tests/models/test_run_results.py
@@ -365,7 +365,7 @@ # Does results.html have enough information to compute this itself? (by # checking total number of results vs. total number of tests?) results['interrupted'] = initial_results.interrupted - results['layout_tests_dir'] = port_obj.layout_tests_dir() + results['layout_tests_dir'] = port_obj.web_tests_dir() results['seconds_since_epoch'] = int(time.time()) results['build_number'] = port_obj.get_option('build_number') results['builder_name'] = port_obj.get_option('builder_name')
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/android.py b/third_party/blink/tools/blinkpy/web_tests/port/android.py index a89cfb44..39d20f7 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/android.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/android.py
@@ -101,11 +101,11 @@ # This path is defined in Chromium's base/test/test_support_android.cc. DEVICE_SOURCE_ROOT_DIR = '/data/local/tmp/' -# The layout tests directory on device, which has two usages: +# The web tests directory on device, which has two usages: # 1. as a virtual path in file urls that will be bridged to HTTP. # 2. pointing to some files that are pushed to the device for tests that # don't work on file-over-http (e.g. blob protocol tests). -DEVICE_LAYOUT_TESTS_DIR = DEVICE_SOURCE_ROOT_DIR + RELATIVE_WEB_TESTS +DEVICE_WEB_TESTS_DIR = DEVICE_SOURCE_ROOT_DIR + RELATIVE_WEB_TESTS KPTR_RESTRICT_PATH = '/proc/sys/kernel/kptr_restrict' @@ -143,7 +143,7 @@ ] -# Information required when running layout tests using content_shell as the test runner. +# Information required when running web tests using content_shell as the test runner. class ContentShellDriverDetails(): def device_cache_directory(self): @@ -187,7 +187,7 @@ # instances and whether the device has been set up. class AndroidDevices(object): # Percentage of battery a device needs to have in order for it to be considered - # to participate in running the layout tests. + # to participate in running the web tests. MINIMUM_BATTERY_PERCENTAGE = 30 def __init__(self, default_devices=None, debug_logging=False): @@ -258,7 +258,7 @@ self._dump_reader = DumpReaderAndroid(host, self._build_path()) if self.driver_name() != self.CONTENT_SHELL_NAME: - raise AssertionError('Layout tests on Android only support content_shell as the driver.') + raise AssertionError('Web tests on Android only support content_shell as the driver.') self._driver_details = ContentShellDriverDetails() @@ -404,8 +404,8 @@ # - the test resources host_device_tuples.extend( - (self.host.filesystem.join(self.layout_tests_dir(), resource), - posixpath.join(DEVICE_LAYOUT_TESTS_DIR, resource)) + (self.host.filesystem.join(self.web_tests_dir(), resource), + posixpath.join(DEVICE_WEB_TESTS_DIR, resource)) for resource in TEST_RESOURCES_TO_PUSH) # ... and then push them to the device. @@ -467,13 +467,13 @@ def requires_http_server(self): """Chromium Android runs tests on devices, and uses the HTTP server to - serve the actual layout tests to the test driver. + serve the actual web tests to the test driver. """ return True def start_http_server(self, additional_dirs, number_of_drivers): additional_dirs[PERF_TEST_PATH_PREFIX] = self._perf_tests_dir() - additional_dirs[WEB_TESTS_PATH_PREFIX] = self.layout_tests_dir() + additional_dirs[WEB_TESTS_PATH_PREFIX] = self.web_tests_dir() super(AndroidPort, self).start_http_server(additional_dirs, number_of_drivers) def create_driver(self, worker_number, no_timeout=False):
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/base.py b/third_party/blink/tools/blinkpy/web_tests/port/base.py index 4c559dd..522662e1 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/base.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/base.py
@@ -29,7 +29,7 @@ """Abstract base class for Port classes. The Port classes encapsulate Port-specific (platform-specific) behavior -in the layout test infrastructure. +in the web test infrastructure. """ import collections @@ -106,7 +106,7 @@ SXG_WPT_FINGERPRINT = '0Rt4mT6SJXojEMHTnKnlJ/hBKMBcI4kteBlhR1eTTdk=' class Port(object): - """Abstract class for Port-specific hooks for the layout_test package.""" + """Abstract class for Port-specific hooks for the web_test package.""" # Subclasses override this. This should indicate the basic implementation # part of the port name, e.g., 'mac', 'win', 'gtk'; there is one unique @@ -234,7 +234,7 @@ is the flag in web_tests/additional-driver-flag.setting, if present, otherwise the first flag passed by --additional-driver-flag. """ - flag_file = self._filesystem.join(self.layout_tests_dir(), 'additional-driver-flag.setting') + flag_file = self._filesystem.join(self.web_tests_dir(), 'additional-driver-flag.setting') if self._filesystem.exists(flag_file): flag = self._filesystem.read_text_file(flag_file).strip() if flag: @@ -560,7 +560,7 @@ # If it wasn't found in a platform directory, return the expected # result in the test directory, even if no such file actually exists. - platform_dir = self.layout_tests_dir() + platform_dir = self.web_tests_dir() if self._filesystem.exists(self._filesystem.join(platform_dir, baseline_filename)): baselines.append((platform_dir, baseline_filename)) @@ -609,7 +609,7 @@ return self.expected_filename(actual_test_name, extension, return_default, match=match) if return_default: - return self._filesystem.join(self.layout_tests_dir(), baseline_filename) + return self._filesystem.join(self.web_tests_dir(), baseline_filename) return None def fallback_expected_filename(self, test_name, extension): @@ -698,7 +698,7 @@ return [] path_in_wpt = match.group(1) for expectation, ref_path_in_wpt in self._wpt_manifest().extract_reference_list(path_in_wpt): - ref_absolute_path = self._filesystem.join(self.layout_tests_dir(), 'external/wpt' + ref_path_in_wpt) + ref_absolute_path = self._filesystem.join(self.web_tests_dir(), 'external/wpt' + ref_path_in_wpt) reftest_list.append((expectation, ref_absolute_path)) return reftest_list @@ -738,7 +738,7 @@ self.is_test_file(fs, dirname, filename) and not re.search(r'[/\\]external[/\\]wpt([/\\].*)?$', dirname) ) - files = find_files.find(self._filesystem, self.layout_tests_dir(), paths, skipped_directories, + files = find_files.find(self._filesystem, self.web_tests_dir(), paths, skipped_directories, is_non_wpt_real_test_file, self.test_key) return [self.relative_test_filename(f) for f in files] @@ -796,7 +796,7 @@ @memoized def _wpt_manifest(self): - manifest_path = self._filesystem.join(self.layout_tests_dir(), 'external', 'wpt', 'MANIFEST.json') + manifest_path = self._filesystem.join(self.web_tests_dir(), 'external', 'wpt', 'MANIFEST.json') if not self._filesystem.exists(manifest_path): _log.error('Manifest not found at %s. Remove the --no-manifest-update argument to generate it.', manifest_path) return WPTManifest('{}') @@ -844,9 +844,9 @@ def test_dirs(self): """Returns the list of top-level test directories.""" - layout_tests_dir = self.layout_tests_dir() + web_tests_dir = self.web_tests_dir() fs = self._filesystem - return [d for d in fs.listdir(layout_tests_dir) if fs.isdir(fs.join(layout_tests_dir, d))] + return [d for d in fs.listdir(web_tests_dir) if fs.isdir(fs.join(web_tests_dir, d))] @memoized def test_isfile(self, test_name): @@ -909,11 +909,11 @@ def _perf_tests_dir(self): return self._path_finder.perf_tests_dir() - def layout_tests_dir(self): - custom_layout_tests_dir = self.get_option('layout_tests_directory') - if custom_layout_tests_dir: - return custom_layout_tests_dir - return self._path_finder.layout_tests_dir() + def web_tests_dir(self): + custom_web_tests_dir = self.get_option('layout_tests_directory') + if custom_web_tests_dir: + return custom_web_tests_dir + return self._path_finder.web_tests_dir() def skips_test(self, test): """Checks whether the given test is skipped for this port. @@ -950,7 +950,7 @@ return test not in smoke_tests def path_to_smoke_tests_file(self): - return self._filesystem.join(self.layout_tests_dir(), 'SmokeTests') + return self._filesystem.join(self.web_tests_dir(), 'SmokeTests') def skipped_in_never_fix_tests(self, test): """Checks if the test is marked as WontFix for this port. @@ -974,7 +974,7 @@ return False def path_to_never_fix_tests_file(self): - return self._filesystem.join(self.layout_tests_dir(), 'NeverFixTests') + return self._filesystem.join(self.web_tests_dir(), 'NeverFixTests') def name(self): """Returns a name that uniquely identifies this particular type of port. @@ -1014,8 +1014,8 @@ """ # Ports that run on windows need to override this method to deal with # filenames with backslashes in them. - if filename.startswith(self.layout_tests_dir()): - return self.host.filesystem.relpath(filename, self.layout_tests_dir()) + if filename.startswith(self.web_tests_dir()): + return self.host.filesystem.relpath(filename, self.web_tests_dir()) else: return self.host.filesystem.abspath(filename) @@ -1025,7 +1025,7 @@ This is the inverse of relative_test_filename(). """ - return self._filesystem.join(self.layout_tests_dir(), test_name) + return self._filesystem.join(self.web_tests_dir(), test_name) @memoized def args_for_test(self, test_name): @@ -1286,14 +1286,14 @@ flag = self.primary_driver_flag() if flag: return self._filesystem.join( - self.layout_tests_dir(), self.FLAG_EXPECTATIONS_PREFIX, flag.lstrip('-')) + self.web_tests_dir(), self.FLAG_EXPECTATIONS_PREFIX, flag.lstrip('-')) def _flag_specific_baseline_search_path(self): flag = self.primary_driver_flag() if not flag: return [] flag_dir = self._filesystem.join( - self.layout_tests_dir(), 'flag-specific', flag.lstrip('-')) + self.web_tests_dir(), 'flag-specific', flag.lstrip('-')) platform_dirs = [ self._filesystem.join(flag_dir, 'platform', platform_dir) for platform_dir in self.FALLBACK_PATHS[self.version()]] @@ -1333,7 +1333,7 @@ """Returns an OrderedDict of name -> expectations strings.""" expectations = self.expectations_dict() - flag_path = self._filesystem.join(self.layout_tests_dir(), 'FlagExpectations') + flag_path = self._filesystem.join(self.web_tests_dir(), 'FlagExpectations') if not self._filesystem.exists(flag_path): return expectations @@ -1383,9 +1383,9 @@ """ return filter(None, [ self.path_to_generic_test_expectations_file(), - self._filesystem.join(self.layout_tests_dir(), 'NeverFixTests'), - self._filesystem.join(self.layout_tests_dir(), 'StaleTestExpectations'), - self._filesystem.join(self.layout_tests_dir(), 'SlowTests'), + self._filesystem.join(self.web_tests_dir(), 'NeverFixTests'), + self._filesystem.join(self.web_tests_dir(), 'StaleTestExpectations'), + self._filesystem.join(self.web_tests_dir(), 'SlowTests'), self._flag_specific_expectations_path() ]) @@ -1395,14 +1395,14 @@ These paths are passed via --additional-expectations on some builders. """ return [ - self._filesystem.join(self.layout_tests_dir(), 'ASANExpectations'), - self._filesystem.join(self.layout_tests_dir(), 'LeakExpectations'), - self._filesystem.join(self.layout_tests_dir(), 'MSANExpectations'), + self._filesystem.join(self.web_tests_dir(), 'ASANExpectations'), + self._filesystem.join(self.web_tests_dir(), 'LeakExpectations'), + self._filesystem.join(self.web_tests_dir(), 'MSANExpectations'), ] @memoized def path_to_generic_test_expectations_file(self): - return self._filesystem.join(self.layout_tests_dir(), 'TestExpectations') + return self._filesystem.join(self.web_tests_dir(), 'TestExpectations') def repository_path(self): """Returns the repository path for the chromium code base.""" @@ -1475,7 +1475,7 @@ """Return the absolute path to the top of the baseline tree for a given platform directory. """ - return self._filesystem.join(self.layout_tests_dir(), 'platform', platform_dir) + return self._filesystem.join(self.web_tests_dir(), 'platform', platform_dir) def _driver_class(self): """Returns the port's driver implementation.""" @@ -1564,7 +1564,7 @@ def virtual_test_suites(self): if self._virtual_test_suites is None: - path_to_virtual_test_suites = self._filesystem.join(self.layout_tests_dir(), 'VirtualTestSuites') + path_to_virtual_test_suites = self._filesystem.join(self.web_tests_dir(), 'VirtualTestSuites') assert self._filesystem.exists(path_to_virtual_test_suites), path_to_virtual_test_suites + ' not found' try: test_suite_json = json.loads(self._filesystem.read_text_file(path_to_virtual_test_suites))
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/base_unittest.py b/third_party/blink/tools/blinkpy/web_tests/port/base_unittest.py index 6b7be1ea..60a10f8 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/base_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/base_unittest.py
@@ -42,7 +42,7 @@ from blinkpy.common.system.system_host_mock import MockSystemHost from blinkpy.web_tests.models.test_input import TestInput from blinkpy.web_tests.port.base import Port, VirtualTestSuite -from blinkpy.web_tests.port.test import add_unit_tests_to_mock_filesystem, LAYOUT_TEST_DIR, TestPort +from blinkpy.web_tests.port.test import add_unit_tests_to_mock_filesystem, WEB_TEST_DIR, TestPort MOCK_WEB_TESTS = '/mock-checkout/' + RELATIVE_WEB_TESTS @@ -65,8 +65,8 @@ def test_test_dirs(self): port = self.make_port() - port.host.filesystem.write_text_file(port.layout_tests_dir() + '/canvas/test', '') - port.host.filesystem.write_text_file(port.layout_tests_dir() + '/css2.1/test', '') + port.host.filesystem.write_text_file(port.web_tests_dir() + '/canvas/test', '') + port.host.filesystem.write_text_file(port.web_tests_dir() + '/css2.1/test', '') dirs = port.test_dirs() self.assertIn('canvas', dirs) self.assertIn('css2.1', dirs) @@ -465,7 +465,7 @@ @staticmethod def _add_manifest_to_mock_file_system(filesystem): - filesystem.write_text_file(LAYOUT_TEST_DIR + '/external/wpt/MANIFEST.json', json.dumps({ + filesystem.write_text_file(WEB_TEST_DIR + '/external/wpt/MANIFEST.json', json.dumps({ 'items': { 'testharness': { 'dom/ranges/Range-attributes.html': [ @@ -499,9 +499,9 @@ ], }, }})) - filesystem.write_text_file(LAYOUT_TEST_DIR + '/external/wpt/dom/ranges/Range-attributes.html', '') - filesystem.write_text_file(LAYOUT_TEST_DIR + '/external/wpt/console/console-is-a-namespace.any.js', '') - filesystem.write_text_file(LAYOUT_TEST_DIR + '/external/wpt/common/blank.html', 'foo') + filesystem.write_text_file(WEB_TEST_DIR + '/external/wpt/dom/ranges/Range-attributes.html', '') + filesystem.write_text_file(WEB_TEST_DIR + '/external/wpt/console/console-is-a-namespace.any.js', '') + filesystem.write_text_file(WEB_TEST_DIR + '/external/wpt/common/blank.html', 'foo') def test_find_none_if_not_in_manifest(self): port = self.make_port(with_tests=True) @@ -610,16 +610,16 @@ PortTest._add_manifest_to_mock_file_system(filesystem) # A file not in MANIFEST.json is not a test even if it has .html suffix. - self.assertFalse(port.is_test_file(filesystem, LAYOUT_TEST_DIR + '/external/wpt/common', 'blank.html')) + self.assertFalse(port.is_test_file(filesystem, WEB_TEST_DIR + '/external/wpt/common', 'blank.html')) # .js is not a test in general, but it is if MANIFEST.json contains an # entry for it. - self.assertTrue(port.is_test_file(filesystem, LAYOUT_TEST_DIR + '/external/wpt/console', 'console-is-a-namespace.any.js')) + self.assertTrue(port.is_test_file(filesystem, WEB_TEST_DIR + '/external/wpt/console', 'console-is-a-namespace.any.js')) # A file in external/wpt, not a sub directory. - self.assertFalse(port.is_test_file(filesystem, LAYOUT_TEST_DIR + '/external/wpt', 'testharness_runner.html')) + self.assertFalse(port.is_test_file(filesystem, WEB_TEST_DIR + '/external/wpt', 'testharness_runner.html')) # A file in external/wpt_automation. - self.assertTrue(port.is_test_file(filesystem, LAYOUT_TEST_DIR + '/external/wpt_automation', 'foo.html')) + self.assertTrue(port.is_test_file(filesystem, WEB_TEST_DIR + '/external/wpt_automation', 'foo.html')) def test_is_wpt_test(self): self.assertTrue(Port.is_wpt_test('external/wpt/dom/ranges/Range-attributes.html')) @@ -673,22 +673,22 @@ def test_reference_files(self): port = self.make_port(with_tests=True) self.assertEqual(port.reference_files('passes/svgreftest.svg'), - [('==', port.layout_tests_dir() + '/passes/svgreftest-expected.svg')]) + [('==', port.web_tests_dir() + '/passes/svgreftest-expected.svg')]) self.assertEqual(port.reference_files('passes/xhtreftest.svg'), - [('==', port.layout_tests_dir() + '/passes/xhtreftest-expected.html')]) + [('==', port.web_tests_dir() + '/passes/xhtreftest-expected.html')]) self.assertEqual(port.reference_files('passes/phpreftest.php'), - [('!=', port.layout_tests_dir() + '/passes/phpreftest-expected-mismatch.svg')]) + [('!=', port.web_tests_dir() + '/passes/phpreftest-expected-mismatch.svg')]) def test_reference_files_from_manifest(self): port = self.make_port(with_tests=True) PortTest._add_manifest_to_mock_file_system(port.host.filesystem) self.assertEqual(port.reference_files('external/wpt/html/dom/elements/global-attributes/dir_auto-EN-L.html'), - [('==', port.layout_tests_dir() + + [('==', port.web_tests_dir() + '/external/wpt/html/dom/elements/global-attributes/dir_auto-EN-L-ref.html')]) self.assertEqual(port.reference_files('virtual/layout_ng/' + 'external/wpt/html/dom/elements/global-attributes/dir_auto-EN-L.html'), - [('==', port.layout_tests_dir() + + [('==', port.web_tests_dir() + '/external/wpt/html/dom/elements/global-attributes/dir_auto-EN-L-ref.html')]) def test_operating_system(self): @@ -813,7 +813,7 @@ def test_good_virtual_test_suite_file(self): port = self.make_port() port.host.filesystem.write_text_file( - port.host.filesystem.join(port.layout_tests_dir(), 'VirtualTestSuites'), + port.host.filesystem.join(port.web_tests_dir(), 'VirtualTestSuites'), '[{"prefix": "bar", "base": "fast/bar", "args": ["--bar"]}]') # If this call returns successfully, we found and loaded the web_tests/VirtualTestSuites. @@ -822,7 +822,7 @@ def test_duplicate_virtual_test_suite_in_file(self): port = self.make_port() port.host.filesystem.write_text_file( - port.host.filesystem.join(port.layout_tests_dir(), 'VirtualTestSuites'), + port.host.filesystem.join(port.web_tests_dir(), 'VirtualTestSuites'), '[' '{"prefix": "bar", "base": "fast/bar", "args": ["--bar"]},' '{"prefix": "bar", "base": "fast/bar", "args": ["--bar"]}' @@ -833,7 +833,7 @@ def test_virtual_test_suite_file_is_not_json(self): port = self.make_port() port.host.filesystem.write_text_file( - port.host.filesystem.join(port.layout_tests_dir(), 'VirtualTestSuites'), + port.host.filesystem.join(port.web_tests_dir(), 'VirtualTestSuites'), '{[{[') self.assertRaises(ValueError, port.virtual_test_suites)
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/browser_test.py b/third_party/blink/tools/blinkpy/web_tests/port/browser_test.py index 956cae91..ea77371 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/browser_test.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/browser_test.py
@@ -53,7 +53,7 @@ def _driver_class(self): return browser_test_driver.BrowserTestDriver - def layout_tests_dir(self): + def web_tests_dir(self): """Overridden function from the base port class. Redirects everything to src/chrome/test/data/printing/layout_tests. """
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/browser_test_unittest.py b/third_party/blink/tools/blinkpy/web_tests/port/browser_test_unittest.py index 71e9f80e..b1a4437 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/browser_test_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/browser_test_unittest.py
@@ -51,8 +51,8 @@ self.assertTrue(isinstance(self.make_port(options=optparse.Values({'driver_name': 'browser_tests'}) ).create_driver(1), browser_test_driver.BrowserTestDriver)) - def test_layout_tests_dir(self): - self.assertTrue(self.make_port().layout_tests_dir().endswith('chrome/test/data/printing/layout_tests')) + def test_web_tests_dir(self): + self.assertTrue(self.make_port().web_tests_dir().endswith('chrome/test/data/printing/layout_tests')) def test_virtual_test_suites(self): # The browser_tests port do not use virtual test suites, so we are just testing the stub.
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/driver.py b/third_party/blink/tools/blinkpy/web_tests/port/driver.py index 249d5d7..d966ec8 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/driver.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/driver.py
@@ -329,15 +329,15 @@ 'https://%s:%d/' % (hostname, secure_port)] def uri_to_test(self, uri): - """Return the base layout test name for a given URI. + """Return the base web test name for a given URI. This returns the test name for a given URI, e.g., if you passed in - "file:///src/LayoutTests/fast/html/keygen.html" it would return + "file:///src/web_tests/fast/html/keygen.html" it would return "fast/html/keygen.html". """ if uri.startswith('file:///'): - prefix = path.abspath_to_uri(self._port.host.platform, self._port.layout_tests_dir()) + prefix = path.abspath_to_uri(self._port.host.platform, self._port.web_tests_dir()) if not prefix.endswith('/'): prefix += '/' return uri[len(prefix):]
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/driver_unittest.py b/third_party/blink/tools/blinkpy/web_tests/port/driver_unittest.py index 48e3e4df..45fe2ec 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/driver_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/driver_unittest.py
@@ -57,7 +57,7 @@ def test_test_to_uri(self): port = self.make_port() driver = Driver(port, None) - self.assertEqual(driver.test_to_uri('foo/bar.html'), 'file://%s/foo/bar.html' % port.layout_tests_dir()) + self.assertEqual(driver.test_to_uri('foo/bar.html'), 'file://%s/foo/bar.html' % port.web_tests_dir()) self.assertEqual(driver.test_to_uri('http/tests/foo.html'), 'http://127.0.0.1:8000/foo.html') self.assertEqual(driver.test_to_uri('http/tests/https/bar.html'), 'https://127.0.0.1:8443/https/bar.html') self.assertEqual(driver.test_to_uri('http/tests/bar.https.html'), 'https://127.0.0.1:8443/bar.https.html') @@ -69,7 +69,7 @@ def test_uri_to_test(self): port = self.make_port() driver = Driver(port, None) - self.assertEqual(driver.uri_to_test('file://%s/foo/bar.html' % port.layout_tests_dir()), 'foo/bar.html') + self.assertEqual(driver.uri_to_test('file://%s/foo/bar.html' % port.web_tests_dir()), 'foo/bar.html') self.assertEqual(driver.uri_to_test('http://127.0.0.1:8000/foo.html'), 'http/tests/foo.html') self.assertEqual(driver.uri_to_test('https://127.0.0.1:8443/https/bar.html'), 'http/tests/https/bar.html') self.assertEqual(driver.uri_to_test('https://127.0.0.1:8443/bar.https.html'), 'http/tests/bar.https.html')
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py b/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py index 945d6577..08640e2 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py
@@ -249,7 +249,7 @@ def start_http_server(self, additional_dirs, number_of_drivers): additional_dirs[PERF_TEST_PATH_PREFIX] = self._perf_tests_dir() - additional_dirs[WEB_TESTS_PATH_PREFIX] = self.layout_tests_dir() + additional_dirs[WEB_TESTS_PATH_PREFIX] = self.web_tests_dir() super(FuchsiaPort, self).start_http_server( additional_dirs, number_of_drivers) @@ -279,7 +279,7 @@ driver_input) if command.startswith('/'): relative_test_filename = \ - os.path.relpath(command, self._port.layout_tests_dir()) + os.path.relpath(command, self._port.web_tests_dir()) command = 'http://127.0.0.1:8000' + WEB_TESTS_PATH_PREFIX + \ '/' + relative_test_filename return command
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py b/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py index c68c610..11378b8d 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/port_testcase.py
@@ -249,9 +249,9 @@ port = self.make_port() self.assertEqual(port.expectations_files(), [ port.path_to_generic_test_expectations_file(), - port.host.filesystem.join(port.layout_tests_dir(), 'NeverFixTests'), - port.host.filesystem.join(port.layout_tests_dir(), 'StaleTestExpectations'), - port.host.filesystem.join(port.layout_tests_dir(), 'SlowTests'), + port.host.filesystem.join(port.web_tests_dir(), 'NeverFixTests'), + port.host.filesystem.join(port.web_tests_dir(), 'StaleTestExpectations'), + port.host.filesystem.join(port.web_tests_dir(), 'SlowTests'), ]) def test_expectations_ordering(self):
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/test.py b/third_party/blink/tools/blinkpy/web_tests/port/test.py index d2bb138..f7b6b6de 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/test.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/test.py
@@ -37,10 +37,10 @@ from blinkpy.web_tests.port.driver import DeviceFailure, Driver, DriverOutput -# Here we use a non-standard location for the layout tests, to ensure that +# Here we use a non-standard location for the web tests, to ensure that # this works. The path contains a '.' in the name because we've seen bugs # related to this before. -LAYOUT_TEST_DIR = '/test.checkout/wtests' +WEB_TEST_DIR = '/test.checkout/wtests' PERF_TEST_DIR = '/test.checkout/PerformanceTests' @@ -278,9 +278,9 @@ # we don't need a real filesystem to run the tests. def add_unit_tests_to_mock_filesystem(filesystem): # Add the test_expectations file. - filesystem.maybe_make_directory(LAYOUT_TEST_DIR) - if not filesystem.exists(LAYOUT_TEST_DIR + '/TestExpectations'): - filesystem.write_text_file(LAYOUT_TEST_DIR + '/TestExpectations', """ + filesystem.maybe_make_directory(WEB_TEST_DIR) + if not filesystem.exists(WEB_TEST_DIR + '/TestExpectations'): + filesystem.write_text_file(WEB_TEST_DIR + '/TestExpectations', """ Bug(test) failures/expected/audio.html [ Failure ] Bug(test) failures/expected/crash.html [ Crash ] Bug(test) failures/expected/crash_then_text.html [ Failure ] @@ -305,8 +305,8 @@ Bug(test) virtual/skipped/failures/expected [ Skip ] """) - if not filesystem.exists(LAYOUT_TEST_DIR + '/NeverFixTests'): - filesystem.write_text_file(LAYOUT_TEST_DIR + '/NeverFixTests', """ + if not filesystem.exists(WEB_TEST_DIR + '/NeverFixTests'): + filesystem.write_text_file(WEB_TEST_DIR + '/NeverFixTests', """ Bug(test) failures/expected/keyboard.html [ WontFix ] Bug(test) failures/expected/exception.html [ WontFix ] Bug(test) failures/expected/device_failure.html [ WontFix ] @@ -315,10 +315,10 @@ # FIXME: This test was only being ignored because of missing a leading '/'. # Fixing the typo causes several tests to assert, so disabling the test entirely. # Add in a file should be ignored by port.find_test_files(). - #files[LAYOUT_TEST_DIR + '/userscripts/resources/iframe.html'] = 'iframe' + #files[WEB_TEST_DIR + '/userscripts/resources/iframe.html'] = 'iframe' def add_file(test, suffix, contents): - dirname = filesystem.join(LAYOUT_TEST_DIR, test.name[0:test.name.rfind('/')]) + dirname = filesystem.join(WEB_TEST_DIR, test.name[0:test.name.rfind('/')]) base = test.base filesystem.maybe_make_directory(dirname) filesystem.write_binary_file(filesystem.join(dirname, base + suffix), contents) @@ -334,7 +334,7 @@ if test.expected_image: add_file(test, '-expected.png', test.expected_image) - filesystem.write_text_file(filesystem.join(LAYOUT_TEST_DIR, 'virtual', 'virtual_passes', + filesystem.write_text_file(filesystem.join(WEB_TEST_DIR, 'virtual', 'virtual_passes', 'passes', 'args-expected.txt'), 'args-txt --virtual-arg') # Clear the list of written files so that we can watch what happens during testing. filesystem.clear_written_files() @@ -364,7 +364,7 @@ self._tests = unit_test_list() self._flakes = set() - # FIXME: crbug.com/279494. This needs to be in the "real layout tests + # FIXME: crbug.com/279494. This needs to be in the "real web tests # dir" in a mock filesystem, rather than outside of the checkout, so # that tests that want to write to a TestExpectations file can share # this between "test" ports and "real" ports. This is the result of @@ -373,7 +373,7 @@ # test ports. rebaseline_unittest.py needs to not mix both "real" ports # and "test" ports - self._generic_expectations_path = LAYOUT_TEST_DIR + '/TestExpectations' + self._generic_expectations_path = WEB_TEST_DIR + '/TestExpectations' self._results_directory = None self._operating_system = 'mac' @@ -439,8 +439,8 @@ return ('< %s\n---\n> %s\n' % (expected_contents, actual_contents), None) return (None, None) - def layout_tests_dir(self): - return LAYOUT_TEST_DIR + def web_tests_dir(self): + return WEB_TEST_DIR def _perf_tests_dir(self): return PERF_TEST_DIR
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/win.py b/third_party/blink/tools/blinkpy/web_tests/port/win.py index 063211e..f235d47 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/win.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/win.py
@@ -160,7 +160,7 @@ return 'win' def relative_test_filename(self, filename): - path = filename[len(self.layout_tests_dir()) + 1:] + path = filename[len(self.web_tests_dir()) + 1:] return path.replace('\\', '/') def uses_apache(self):
diff --git a/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests.py b/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests.py index a527fbe6..0e93026c 100644 --- a/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests.py +++ b/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests.py
@@ -574,7 +574,7 @@ if not options.test_list: options.test_list = [] - options.test_list.append(port.host.filesystem.join(port.layout_tests_dir(), 'SmokeTests')) + options.test_list.append(port.host.filesystem.join(port.web_tests_dir(), 'SmokeTests')) if not options.skipped: options.skipped = 'always'
diff --git a/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests_unittest.py b/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests_unittest.py index 9a79bfe4..e85737d 100644 --- a/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/run_webkit_tests_unittest.py
@@ -581,7 +581,7 @@ def test_smoke_test(self): host = MockHost() - smoke_test_filename = test.LAYOUT_TEST_DIR + '/SmokeTests' + smoke_test_filename = test.WEB_TEST_DIR + '/SmokeTests' host.filesystem.write_text_file(smoke_test_filename, 'passes/text.html\n') # Test the default smoke testing. @@ -612,7 +612,7 @@ def test_smoke_test_default_retry(self): host = MockHost() - smoke_test_filename = test.LAYOUT_TEST_DIR + '/SmokeTests' + smoke_test_filename = test.WEB_TEST_DIR + '/SmokeTests' host.filesystem.write_text_file( smoke_test_filename, 'failures/unexpected/text-image-checksum.html\n') @@ -971,7 +971,7 @@ def test_reftest_mismatching_both_text_and_pixel(self): test_name = 'failures/unexpected/reftest.html' host = MockHost() - host.filesystem.write_text_file(test.LAYOUT_TEST_DIR + '/failures/unexpected/reftest-expected.txt', 'mismatch') + host.filesystem.write_text_file(test.WEB_TEST_DIR + '/failures/unexpected/reftest-expected.txt', 'mismatch') run_details, _, _ = logging_run([test_name], tests_included=True, host=host) self.assertNotEqual(run_details.exit_code, 0) self.assertEqual(run_details.initial_results.total, 1) @@ -982,9 +982,9 @@ def test_extra_baselines(self): host = MockHost() - extra_txt = test.LAYOUT_TEST_DIR + '/passes/image-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/passes/image-expected.txt' host.filesystem.write_text_file(extra_txt, 'Extra txt') - extra_wav = test.LAYOUT_TEST_DIR + '/passes/image-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/passes/image-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') test_name = 'passes/image.html' run_details, log_stream, _ = logging_run([test_name], tests_included=True, host=host) @@ -1000,9 +1000,9 @@ def test_empty_overriding_baselines(self): host = MockHost() - base_baseline = test.LAYOUT_TEST_DIR + '/passes/image-expected.txt' + base_baseline = test.WEB_TEST_DIR + '/passes/image-expected.txt' host.filesystem.write_text_file(base_baseline, 'Non-empty') - platform_baseline = test.LAYOUT_TEST_DIR + '/platform/test-mac-mac10.10/passes/image-expected.txt' + platform_baseline = test.WEB_TEST_DIR + '/platform/test-mac-mac10.10/passes/image-expected.txt' host.filesystem.write_text_file(platform_baseline, '') test_name = 'passes/image.html' run_details, log_stream, _ = logging_run([test_name], tests_included=True, host=host) @@ -1015,9 +1015,9 @@ def test_reftest_extra_baselines(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/reftest-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/reftest-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') - extra_wav = test.LAYOUT_TEST_DIR + '/passes/reftest-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/passes/reftest-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') test_name = 'passes/reftest.html' run_details, log_stream, _ = logging_run([test_name], tests_included=True, host=host) @@ -1033,9 +1033,9 @@ def test_reftest_with_text_extra_baselines(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/reftest-with-text-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/reftest-with-text-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') - extra_wav = test.LAYOUT_TEST_DIR + '/passes/reftest-with-text-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/passes/reftest-with-text-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') test_name = 'passes/reftest-with-text.html' run_details, log_stream, _ = logging_run([test_name], tests_included=True, host=host) @@ -1051,7 +1051,7 @@ def test_reftest_extra_png_baseline(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/reftest-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/reftest-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') test_name = 'passes/reftest.html' run_details, log_stream, _ = logging_run([test_name], tests_included=True, host=host) @@ -1061,12 +1061,12 @@ def test_passing_testharness_extra_baselines(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/testharness-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') - extra_txt = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/passes/testharness-expected.txt' host.filesystem.write_text_file(extra_txt, 'This is a testharness.js-based test.\nPASS: bah\nHarness: the test ran to completion.') - extra_wav = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/passes/testharness-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') test_name = 'passes/testharness.html' run_details, log_stream, _ = logging_run([test_name], tests_included=True, host=host) @@ -1084,7 +1084,7 @@ def test_passing_testharness_extra_txt_baseline(self): host = MockHost() - extra_txt = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/passes/testharness-expected.txt' host.filesystem.write_text_file(extra_txt, 'This is a testharness.js-based test.\nPASS: bah\nHarness: the test ran to completion.') test_name = 'passes/testharness.html' @@ -1095,7 +1095,7 @@ def test_passing_testharness_extra_mismatching_txt_baseline(self): host = MockHost() - extra_txt = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/passes/testharness-expected.txt' host.filesystem.write_text_file(extra_txt, 'This is a testharness.js-based test.\nFAIL: bah\nHarness: the test ran to completion.') test_name = 'passes/testharness.html' @@ -1112,9 +1112,9 @@ # An all-pass testharness text baseline is necessary when it overrides a fallback baseline. host = MockHost() # The base baseline expects a failure. - base_baseline = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.txt' + base_baseline = test.WEB_TEST_DIR + '/passes/testharness-expected.txt' host.filesystem.write_text_file(base_baseline, 'Failure') - platform_baseline = test.LAYOUT_TEST_DIR + '/platform/test-mac-mac10.10/passes/testharness-expected.txt' + platform_baseline = test.WEB_TEST_DIR + '/platform/test-mac-mac10.10/passes/testharness-expected.txt' host.filesystem.write_text_file(platform_baseline, 'This is a testharness.js-based test.\nPASS: bah\nHarness: the test ran to completion.') run_details, log_stream, _ = logging_run( @@ -1221,7 +1221,7 @@ class RebaselineTest(unittest.TestCase, StreamTestingMixin): """Tests for flags which cause new baselines to be written. - When running layout tests, there are several flags which write new + When running web tests, there are several flags which write new baselines. This is separate from the "blink_tool.py rebaseline" commands, which fetch new baselines from elsewhere rather than generating them. """ @@ -1233,19 +1233,19 @@ written_files: from FileSystem.written_files. log_stream: The log stream from the run. expected_file_base: Relative path to the baseline, - without the extension, from the layout test directory. + without the extension, from the web test directory. expected_extensions: Expected extensions which should be written. """ for ext in expected_extensions: baseline = '%s-expected%s' % (expected_file_base, ext) - baseline_full_path = '%s/%s' % (test.LAYOUT_TEST_DIR, baseline) + baseline_full_path = '%s/%s' % (test.WEB_TEST_DIR, baseline) self.assertIsNotNone(written_files.get(baseline_full_path)) baseline_message = 'Writing new baseline "%s"\n' % baseline self.assert_contains(log_stream, baseline_message) # Assert that baselines with other extensions were not written. for ext in ({'.png', '.txt', '.wav'} - set(expected_extensions)): baseline = '%s-expected%s' % (expected_file_base, ext) - baseline_full_path = '%s/%s' % (test.LAYOUT_TEST_DIR, baseline) + baseline_full_path = '%s/%s' % (test.WEB_TEST_DIR, baseline) self.assertIsNone(written_files.get(baseline_full_path)) def test_reset_results_basic(self): @@ -1327,7 +1327,7 @@ # Tests that we update existing baseline for a testharness test. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + '/failures/unexpected/testharness-expected.txt', 'foo') + test.WEB_TEST_DIR + '/failures/unexpected/testharness-expected.txt', 'foo') details, log_stream, _ = logging_run( [ '--reset-results', @@ -1358,7 +1358,7 @@ # if the new baseline is different from the fallback baseline. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we also @@ -1385,7 +1385,7 @@ # if the new baseline is different from the fallback baseline. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we also @@ -1434,9 +1434,9 @@ def test_reset_results_remove_extra_baselines(self): host = MockHost() - extra_txt = test.LAYOUT_TEST_DIR + '/failures/unexpected/image-only-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/failures/unexpected/image-only-expected.txt' host.filesystem.write_text_file(extra_txt, 'Extra txt') - extra_wav = test.LAYOUT_TEST_DIR + '/failures/unexpected/image-only-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/failures/unexpected/image-only-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') details, log_stream, _ = logging_run( ['--reset-results', 'failures/unexpected/image-only.html'], @@ -1452,11 +1452,11 @@ def test_reset_results_reftest_remove_extra_baselines(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/reftest-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/reftest-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') - extra_wav = test.LAYOUT_TEST_DIR + '/passes/reftest-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/passes/reftest-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') - extra_txt = test.LAYOUT_TEST_DIR + '/passes/reftest-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/passes/reftest-expected.txt' host.filesystem.write_text_file(extra_txt, 'reftest') details, _, _ = logging_run(['--reset-results', 'passes/reftest.html'], tests_included=True, host=host) @@ -1469,9 +1469,9 @@ def test_reset_results_reftest_with_text_remove_extra_baselines(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/reftest-with-text-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/reftest-with-text-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') - extra_wav = test.LAYOUT_TEST_DIR + '/passes/reftest-with-text-expected.wav' + extra_wav = test.WEB_TEST_DIR + '/passes/reftest-with-text-expected.wav' host.filesystem.write_text_file(extra_wav, 'Extra wav') details, _, _ = logging_run(['--reset-results', 'passes/reftest-with-text.html'], tests_included=True, host=host) @@ -1480,13 +1480,13 @@ self.assertEqual(len(written_files.keys()), 7) self.assertIsNone(written_files[extra_png]) self.assertIsNone(written_files[extra_wav]) - self.assertNotIn(test.LAYOUT_TEST_DIR + '/passes/reftest-with-text-expected.txt', written_files) + self.assertNotIn(test.WEB_TEST_DIR + '/passes/reftest-with-text-expected.txt', written_files) def test_reset_results_passing_testharness_remove_extra_baselines(self): host = MockHost() - extra_png = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.png' + extra_png = test.WEB_TEST_DIR + '/passes/testharness-expected.png' host.filesystem.write_text_file(extra_png, 'Extra png') - extra_txt = test.LAYOUT_TEST_DIR + '/passes/testharness-expected.txt' + extra_txt = test.WEB_TEST_DIR + '/passes/testharness-expected.txt' host.filesystem.write_text_file(extra_txt, 'Extra txt') details, log_stream, _ = logging_run( ['--reset-results', 'passes/testharness.html'], @@ -1517,7 +1517,7 @@ # results are different from the current baselines. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we also @@ -1542,7 +1542,7 @@ # results are different from the current baselines. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we also @@ -1568,7 +1568,7 @@ # actual results are the same as the fallback baselines. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we check @@ -1576,7 +1576,7 @@ # result is the same as this fallback baseline. 'text-image-checksum_fail-txt') flag_specific_baseline_txt = ( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/flag-specific/flag/failures/unexpected/text-image-checksum-expected.txt') host.filesystem.write_text_file( flag_specific_baseline_txt, 'existing-baseline-different-from-fallback') @@ -1601,7 +1601,7 @@ # results are different from the current baselines. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we also @@ -1626,7 +1626,7 @@ # baseline (which should not matter). host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/platform/test-mac-mac10.10/failures/unexpected/text-image-checksum-expected.png', 'wrong-png-baseline') @@ -1651,11 +1651,11 @@ # baseline (which should not matter). host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/platform/test-mac-mac10.10/failures/unexpected/text-image-checksum-expected.png', 'wrong-png-baseline') host.filesystem.remove( - test.LAYOUT_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.png') + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.png') details, log_stream, _ = logging_run( [ @@ -1677,7 +1677,7 @@ # actual results are the same as the fallback baselines. host = MockHost() host.filesystem.write_text_file( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/failures/unexpected/text-image-checksum-expected.txt', # This value is the same as actual text result of the test defined # in blinkpy.web_tests.port.test. This is added so that we check @@ -1685,7 +1685,7 @@ # result is the same as this fallback baseline. 'text-image-checksum_fail-txt') virtual_baseline_txt = ( - test.LAYOUT_TEST_DIR + + test.WEB_TEST_DIR + '/virtual/virtual_failures/failures/unexpected/text-image-checksum-expected.txt') host.filesystem.write_text_file( virtual_baseline_txt, 'existing-baseline-different-from-fallback')
diff --git a/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py b/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py index 991ae4a..d50fd947 100644 --- a/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py +++ b/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py
@@ -26,7 +26,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Start and stop the Apache HTTP server as it is used by the layout tests.""" +"""Start and stop the Apache HTTP server as it is used by the web tests.""" import logging import socket @@ -55,7 +55,7 @@ executable = self._port_obj.path_to_apache() server_root = self._filesystem.dirname(self._filesystem.dirname(executable)) - test_dir = self._port_obj.layout_tests_dir() + test_dir = self._port_obj.web_tests_dir() document_root = self._filesystem.join(test_dir, 'http', 'tests') forms_test_resources_dir = self._filesystem.join(test_dir, 'fast', 'forms', 'resources') media_resources_dir = self._filesystem.join(test_dir, 'media')
diff --git a/third_party/blink/tools/blinkpy/web_tests/servers/pywebsocket.py b/third_party/blink/tools/blinkpy/web_tests/servers/pywebsocket.py index 062ae111..16a9e32 100644 --- a/third_party/blink/tools/blinkpy/web_tests/servers/pywebsocket.py +++ b/third_party/blink/tools/blinkpy/web_tests/servers/pywebsocket.py
@@ -26,7 +26,7 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""A class to help start/stop the PyWebSocket server as used by the layout tests.""" +"""A class to help start/stop the PyWebSocket server as used by the web tests.""" import os import sys @@ -51,8 +51,8 @@ self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name) self._port = _DEFAULT_WS_PORT - self._layout_tests = self._port_obj.layout_tests_dir() - self._web_socket_tests = self._filesystem.join(self._layout_tests, 'http', 'tests', 'websocket') + self._web_tests = self._port_obj.web_tests_dir() + self._web_socket_tests = self._filesystem.join(self._web_tests, 'http', 'tests', 'websocket') time_str = time.strftime('%d%b%Y-%H%M%S') log_file_name = _WS_LOG_PREFIX + time_str self._error_log = self._filesystem.join(self._output_dir, log_file_name + '-err.txt')
diff --git a/third_party/blink/tools/blinkpy/web_tests/servers/wptserve.py b/third_party/blink/tools/blinkpy/web_tests/servers/wptserve.py index e41aeb2..bad7878 100644 --- a/third_party/blink/tools/blinkpy/web_tests/servers/wptserve.py +++ b/third_party/blink/tools/blinkpy/web_tests/servers/wptserve.py
@@ -2,7 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -"""Start and stop the WPTserve servers as they're used by the layout tests.""" +"""Start and stop the WPTserve servers as they're used by the web tests.""" import datetime import json @@ -38,7 +38,7 @@ path_to_pywebsocket = finder.path_from_chromium_base('third_party', 'pywebsocket', 'src') path_to_wpt_support = finder.path_from_blink_tools('blinkpy', 'third_party', 'wpt') path_to_wpt_root = fs.join(path_to_wpt_support, 'wpt') - path_to_wpt_tests = fs.abspath(fs.join(self._port_obj.layout_tests_dir(), 'external', 'wpt')) + path_to_wpt_tests = fs.abspath(fs.join(self._port_obj.web_tests_dir(), 'external', 'wpt')) path_to_ws_handlers = fs.join(path_to_wpt_tests, 'websockets', 'handlers') self._config_file = self._prepare_wptserve_config(path_to_wpt_support) wpt_script = fs.join(path_to_wpt_root, 'wpt')
diff --git a/third_party/blink/tools/blinkpy/web_tests/try_flag.py b/third_party/blink/tools/blinkpy/web_tests/try_flag.py index 805c0ec8..10c692f 100644 --- a/third_party/blink/tools/blinkpy/web_tests/try_flag.py +++ b/third_party/blink/tools/blinkpy/web_tests/try_flag.py
@@ -49,14 +49,14 @@ def _force_flag_for_test_runner(self): flag = self._args.flag - path = self._path_finder.path_from_layout_tests(FLAG_FILE) + path = self._path_finder.path_from_web_tests(FLAG_FILE) self._filesystem.write_text_file(path, flag + '\n') self._git.add_list([path]) self._git.commit_locally_with_message( 'Flag try job: force %s for run_web_tests.py.' % flag) def _flag_expectations_path(self): - return self._path_finder.path_from_layout_tests( + return self._path_finder.path_from_web_tests( 'FlagExpectations', self._args.flag.lstrip('-')) def _clear_expectations(self):
diff --git a/third_party/blink/tools/blinkpy/web_tests/try_flag_unittest.py b/third_party/blink/tools/blinkpy/web_tests/try_flag_unittest.py index 0c58636e..166b1af 100644 --- a/third_party/blink/tools/blinkpy/web_tests/try_flag_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/try_flag_unittest.py
@@ -32,9 +32,9 @@ git_cl = MockGitCL(host) finder = PathFinder(host.filesystem) - flag_file = finder.path_from_layout_tests( + flag_file = finder.path_from_web_tests( 'additional-driver-flag.setting') - flag_expectations_file = finder.path_from_layout_tests( + flag_expectations_file = finder.path_from_web_tests( 'FlagExpectations', 'foo') cmd = ['trigger', '--flag=--foo'] @@ -123,7 +123,7 @@ filesystem = host.filesystem finder = PathFinder(filesystem) - flag_expectations_file = finder.path_from_layout_tests( + flag_expectations_file = finder.path_from_web_tests( 'FlagExpectations', 'foo') filesystem.write_text_file( flag_expectations_file, @@ -161,7 +161,7 @@ host = MockHost() filesystem = host.filesystem finder = PathFinder(filesystem) - flag_expectations_file = finder.path_from_layout_tests( + flag_expectations_file = finder.path_from_web_tests( 'FlagExpectations', 'foo') self._setup_mock_results(host.buildbot) cmd = ['update', '--flag=--foo']
diff --git a/third_party/blink/tools/blinkpy/web_tests/update_expectations_unittest.py b/third_party/blink/tools/blinkpy/web_tests/update_expectations_unittest.py index 3eba707..f490a6b7 100644 --- a/third_party/blink/tools/blinkpy/web_tests/update_expectations_unittest.py +++ b/third_party/blink/tools/blinkpy/web_tests/update_expectations_unittest.py
@@ -12,7 +12,7 @@ from blinkpy.web_tests.update_expectations import ExpectationsRemover from blinkpy.web_tests.builder_list import BuilderList from blinkpy.web_tests.port.factory import PortFactory -from blinkpy.web_tests.port.test import LAYOUT_TEST_DIR +from blinkpy.web_tests.port.test import WEB_TEST_DIR from blinkpy.web_tests.update_expectations import main from blinkpy.tool.commands.flaky_tests import FlakyTests @@ -116,7 +116,7 @@ 'test/f.html', 'test/g.html'] for test in test_list: - path = filesystem.join(LAYOUT_TEST_DIR, test) + path = filesystem.join(WEB_TEST_DIR, test) filesystem.write_binary_file(path, '') def _create_expectations_remover(self, type_flag='all', remove_missing=False):
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint index 685f64c..7238e7d 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint
@@ -205,23 +205,7 @@ Bug(none) fast/webgl/pixelated.html [ Failure ] Bug(none) images/color-profile-reflection.html [ Crash Failure ] Bug(none) images/color-profile-svg-foreign-object.html [ Failure ] -Bug(none) fast/multicol/composited-inner-multicol.html [ Failure ] -Bug(none) fast/multicol/composited-layer-multiple-fragments-translated.html [ Failure ] -Bug(none) fast/multicol/composited-layer-multiple-fragments.html [ Failure ] -Bug(none) fast/multicol/composited-layer-nested.html [ Failure Crash ] -Bug(none) fast/multicol/composited-opacity-2nd-and-3rd-column.html [ Failure ] -Bug(none) fast/multicol/composited-relpos.html [ Failure ] -Bug(none) fast/multicol/composited-relpos-clipped.html [ Failure ] -Bug(none) fast/multicol/composited-relpos-in-clipped.html [ Failure ] -Bug(none) fast/multicol/composited-relpos-overlapping-will-change.html [ Failure ] -Bug(none) fast/multicol/composited-relpos-resize.html [ Failure ] -Bug(none) fast/multicol/composited-with-child-layer-in-next-column.html [ Failure ] -Bug(none) fast/multicol/composited-with-overflow-in-next-column.html [ Failure ] Bug(none) fast/multicol/insane-column-count-and-padding-nested-crash.html [ Crash ] -Bug(none) fast/multicol/mixed-opacity-test.html [ Failure ] -Bug(none) fast/multicol/span/invalid-spanner-in-transform.html [ Failure ] -Bug(none) fast/multicol/vertical-lr/composited-relpos-overlapping-will-change.html [ Failure ] -Bug(none) fast/multicol/vertical-rl/composited-relpos-overlapping-will-change.html [ Failure ] Bug(none) fast/scroll-behavior/ [ Skip ] Bug(none) fast/sub-pixel/repaint-subpixel-layer-in-subpixel-composited-layer.html [ Failure ] Bug(none) fast/sub-pixel/should-not-repaint-subpixel-composited-layer.html [ Failure ] @@ -354,6 +338,8 @@ Bug(none) fast/events/platform-wheelevent-paging-xy-in-scrolling-div.html [ Failure ] Bug(none) fast/events/platform-wheelevent-paging-y-in-scrolling-div.html [ Failure ] Bug(none) fast/events/scrollbar-double-click.html [ Failure ] + +# Not scrollable with scroll wheel Bug(none) fast/forms/suggestion-picker/date-suggestion-picker-mouse-operations.html [ Failure ] Bug(none) fast/forms/suggestion-picker/datetimelocal-suggestion-picker-mouse-operations.html [ Failure ] Bug(none) fast/forms/suggestion-picker/month-suggestion-picker-mouse-operations.html [ Failure ] @@ -473,7 +459,6 @@ # different results. Bug(none) paint/invalidation/compositing/subpixel-offset-scaled-transform-composited.html [ Failure ] -Bug(none) fast/multicol/composited-layer-will-change.html [ Failure ] Bug(none) fast/pagination/multicol.html [ Crash ] Bug(none) fast/pagination/repeating-thead-tfoot-paged-x.html [ Failure ] Bug(none) fast/pagination/repeating-thead-tfoot-paged-y.html [ Failure ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 56e6b7e..651e5369 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -3044,6 +3044,9 @@ crbug.com/893480 external/wpt/infrastructure/testdriver/actions/multiDevice.html [ Failure Timeout ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 external/wpt/infrastructure/testdriver/file_upload.sub.html [ Skip ] +crbug.com/626703 [ Android ] external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html [ Failure Timeout ] +crbug.com/626703 [ Retina ] external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html [ Failure Timeout ] crbug.com/626703 external/wpt/css/css-text/white-space/text-space-collapse-preserve-breaks-001.xht [ Failure ] crbug.com/626703 external/wpt/css/css-text/white-space/text-space-collapse-discard-001.xht [ Failure ] crbug.com/626703 external/wpt/css/css-text/white-space/text-space-trim-trim-inner-001.xht [ Failure ] @@ -5117,11 +5120,6 @@ crbug.com/832274 [ Linux ] fast/forms/search/search-appearance-basic.html [ Pass Failure ] crbug.com/832274 [ Win ] fast/forms/search/search-appearance-basic.html [ Pass Failure ] -crbug.com/840881 external/wpt/service-workers/service-worker/resource-timing.https.html [ Failure ] -crbug.com/840881 virtual/outofblink-cors/external/wpt/service-workers/service-worker/resource-timing.https.html [ Failure ] -crbug.com/840881 virtual/outofblink-cors-ns/external/wpt/service-workers/service-worker/resource-timing.https.html [ Failure ] -crbug.com/840881 virtual/disabled-service-worker-servicification/external/wpt/service-workers/service-worker/resource-timing.https.html [ Failure ] - # Sheriff 2018-04-12 crbug.com/831993 [ Linux ] virtual/gpu-rasterization/images/cross-fade-overflow-position.html [ Pass Timeout ] @@ -5678,7 +5676,7 @@ # Sheriff 2018-10-31 crbug.com/900326 [ Win7 ] http/tests/devtools/network/preview-searchable.js [ Timeout Pass ] crbug.com/900326 [ Mac10.12 ] http/tests/devtools/network/preview-searchable.js [ Timeout Pass ] -crbug.com/900641 [ Linux ] compositing/transitions/transform-on-large-layer.html [ Timeout Pass ] +crbug.com/874695 crbug.com/900641 crbug.com/913865 [ Linux Mac ] compositing/transitions/transform-on-large-layer.html [ Timeout Pass Crash ] crbug.com/900703 external/wpt/cors/origin.htm [ Failure Pass ] crbug.com/900730 [ Mac ] rootscroller/gesture-scroll-document-not-root-scroller.html [ Pass Failure Timeout Crash ]
diff --git a/third_party/blink/web_tests/custom-elements/tentative/form-association.html b/third_party/blink/web_tests/custom-elements/tentative/form-association.html index f529fcf..629d3cb 100644 --- a/third_party/blink/web_tests/custom-elements/tentative/form-association.html +++ b/third_party/blink/web_tests/custom-elements/tentative/form-association.html
@@ -65,9 +65,24 @@ static get formAssociated() { return true; } } assert_throws("TypeMismatchError", () => { customElements.define('my-control', MyControl) }); + assert_throws("TypeMismatchError", () => { customElements.define('my-control2', class extends MyControl {}); }); }, 'define() requires value property setter'); test(() => { + class MyControlBase extends HTMLElement { + static get formAssociated() { return true; } + set value(v) { } + } + class MyControlDerived extends MyControlBase {} + + try { + customElements.define('my-control-derived', MyControlDerived); + } catch (exception) { + assert_unreached('define() should not throw anything'); + } +}, 'define() accepts value property setter on a base class'); + +test(() => { let controls = $('#form1').elements; assert_equals(controls.length, 3); assert_equals(controls[1], $('#pd1'), 'form.elements');
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json index 9c24a94..bb6b7c7 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json
@@ -33887,6 +33887,18 @@ {} ] ], + "css/css-break/block-end-aligned-abspos-with-overflow.html": [ + [ + "/css/css-break/block-end-aligned-abspos-with-overflow.html", + [ + [ + "/css/css-break/block-end-aligned-abspos-with-overflow-ref.html", + "==" + ] + ], + {} + ] + ], "css/css-break/line-after-unbreakable-float-after-padding.html": [ [ "/css/css-break/line-after-unbreakable-float-after-padding.html", @@ -123842,6 +123854,11 @@ {} ] ], + "css/css-break/block-end-aligned-abspos-with-overflow-ref.html": [ + [ + {} + ] + ], "css/css-break/line-after-unbreakable-float-after-padding-ref.html": [ [ {} @@ -135617,11 +135634,6 @@ {} ] ], - "css/css-logical/animation-001-expected.txt": [ - [ - {} - ] - ], "css/css-logical/animation-002-expected.txt": [ [ {} @@ -158067,16 +158079,6 @@ {} ] ], - "html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-2-expected.txt": [ - [ - {} - ] - ], - "html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-expected.txt": [ - [ - {} - ] - ], "html/browsers/browsing-the-web/scroll-to-fragid/navigate-helpers.js": [ [ {} @@ -166572,6 +166574,11 @@ {} ] ], + "html/semantics/forms/the-button-element/button-click-submits-expected.txt": [ + [ + {} + ] + ], "html/semantics/forms/the-button-element/button-validation-expected.txt": [ [ {} @@ -166892,6 +166899,16 @@ {} ] ], + "html/semantics/links/links-created-by-a-and-area-elements/support/target_blank_iplicit_noopener.html": [ + [ + {} + ] + ], + "html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt": [ + [ + {} + ] + ], "html/semantics/links/linktypes/alternate-css-ref.html": [ [ {} @@ -169562,6 +169579,16 @@ {} ] ], + "infrastructure/testdriver/file_upload.py": [ + [ + {} + ] + ], + "infrastructure/testdriver/file_upload_data.txt": [ + [ + {} + ] + ], "infrastructure/testdriver/send_keys-expected.txt": [ [ {} @@ -184417,6 +184444,11 @@ {} ] ], + "webrtc/protocol/msid-parse-expected.txt": [ + [ + {} + ] + ], "webrtc/resources/RTCCertificate-postMessage-iframe.html": [ [ {} @@ -203896,6 +203928,12 @@ {} ] ], + "css/css-break/block-end-aligned-abspos.html": [ + [ + "/css/css-break/block-end-aligned-abspos.html", + {} + ] + ], "css/css-break/hit-test-inline-fragmentation-with-border-radius.html": [ [ "/css/css-break/hit-test-inline-fragmentation-with-border-radius.html", @@ -207950,6 +207988,12 @@ {} ] ], + "css/css-shadow-parts/double-forward.html": [ + [ + "/css/css-shadow-parts/double-forward.html", + {} + ] + ], "css/css-shadow-parts/host-stylesheet.html": [ [ "/css/css-shadow-parts/host-stylesheet.html", @@ -207962,6 +208006,18 @@ {} ] ], + "css/css-shadow-parts/invalidation-change-exportparts-forward.html": [ + [ + "/css/css-shadow-parts/invalidation-change-exportparts-forward.html", + {} + ] + ], + "css/css-shadow-parts/invalidation-change-part-name-forward.html": [ + [ + "/css/css-shadow-parts/invalidation-change-part-name-forward.html", + {} + ] + ], "css/css-shadow-parts/invalidation-change-part-name-idl-domtokenlist.html": [ [ "/css/css-shadow-parts/invalidation-change-part-name-idl-domtokenlist.html", @@ -207980,6 +208036,12 @@ {} ] ], + "css/css-shadow-parts/invalidation-complex-selector-forward.html": [ + [ + "/css/css-shadow-parts/invalidation-complex-selector-forward.html", + {} + ] + ], "css/css-shadow-parts/invalidation-complex-selector.html": [ [ "/css/css-shadow-parts/invalidation-complex-selector.html", @@ -207992,6 +208054,24 @@ {} ] ], + "css/css-shadow-parts/precedence-part-vs-part.html": [ + [ + "/css/css-shadow-parts/precedence-part-vs-part.html", + {} + ] + ], + "css/css-shadow-parts/simple-forward-shorthand.html": [ + [ + "/css/css-shadow-parts/simple-forward-shorthand.html", + {} + ] + ], + "css/css-shadow-parts/simple-forward.html": [ + [ + "/css/css-shadow-parts/simple-forward.html", + {} + ] + ], "css/css-shadow-parts/simple.html": [ [ "/css/css-shadow-parts/simple.html", @@ -229662,6 +229742,12 @@ {} ] ], + "fetch/images/canvas-remote-read-remote-image-redirect.html": [ + [ + "/fetch/images/canvas-remote-read-remote-image-redirect.html", + {} + ] + ], "fetch/nosniff/image.html": [ [ "/fetch/nosniff/image.html", @@ -236532,6 +236618,12 @@ {} ] ], + "html/semantics/embedded-content/the-img-element/available-images-onload.html": [ + [ + "/html/semantics/embedded-content/the-img-element/available-images-onload.html", + {} + ] + ], "html/semantics/embedded-content/the-img-element/current-pixel-density/basic.html": [ [ "/html/semantics/embedded-content/the-img-element/current-pixel-density/basic.html", @@ -238210,6 +238302,12 @@ {} ] ], + "html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html": [ + [ + "/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html", + {} + ] + ], "html/semantics/rellist-feature-detection.html": [ [ "/html/semantics/rellist-feature-detection.html", @@ -243506,6 +243604,14 @@ } ] ], + "infrastructure/testdriver/file_upload.sub.html": [ + [ + "/infrastructure/testdriver/file_upload.sub.html", + { + "testdriver": true + } + ] + ], "infrastructure/testdriver/send_keys.html": [ [ "/infrastructure/testdriver/send_keys.html", @@ -269168,6 +269274,24 @@ {} ] ], + "scroll-animations/current-time-nan.html": [ + [ + "/scroll-animations/current-time-nan.html", + {} + ] + ], + "scroll-animations/current-time-root-scroller.html": [ + [ + "/scroll-animations/current-time-root-scroller.html", + {} + ] + ], + "scroll-animations/current-time-writing-modes.html": [ + [ + "/scroll-animations/current-time-writing-modes.html", + {} + ] + ], "scroll-animations/current-time.html": [ [ "/scroll-animations/current-time.html", @@ -278950,6 +279074,12 @@ {} ] ], + "webrtc/protocol/msid-parse.html": [ + [ + "/webrtc/protocol/msid-parse.html", + {} + ] + ], "webrtc/protocol/video-codecs.https.html": [ [ "/webrtc/protocol/video-codecs.https.html", @@ -298880,7 +299010,7 @@ "testharness" ], "WebCryptoAPI/sign_verify/ecdsa.js": [ - "869fb796517561d7026ab8c215b62a014f72e65b", + "208b81c45ea10fded7f24c7c99b288a914c8fe66", "support" ], "WebCryptoAPI/sign_verify/ecdsa_vectors.js": [ @@ -298892,7 +299022,7 @@ "testharness" ], "WebCryptoAPI/sign_verify/hmac.js": [ - "22a2acf64f5b5e050a9e76ca01d4fb96aaa57b22", + "e8f9ec5815287fc9c2ab0eb039edf806f3a8f613", "support" ], "WebCryptoAPI/sign_verify/hmac_vectors.js": [ @@ -298900,7 +299030,7 @@ "support" ], "WebCryptoAPI/sign_verify/rsa.js": [ - "656c320f78f6a394ceaaf01e50d540f6c5c1a2ed", + "251f57e8bbcfffa179390fc7efab266393a27f3e", "support" ], "WebCryptoAPI/sign_verify/rsa_pkcs.https.worker.js": [ @@ -301464,7 +301594,7 @@ "support" ], "common/performance-timeline-utils.js": [ - "3efce5b5d8b3cbc9ac17171e674d317de8797a55", + "b20241cc6106f93a999b498bbf21426f44ad89fc", "support" ], "common/performance-timeline-utils.js.headers": [ @@ -325707,6 +325837,18 @@ "198e62f8c7d4e020e65dad6ecb7937204aaa8912", "support" ], + "css/css-break/block-end-aligned-abspos-with-overflow-ref.html": [ + "a8470b09a7d67eb3929c0380eaa45779c2b558ad", + "support" + ], + "css/css-break/block-end-aligned-abspos-with-overflow.html": [ + "9000c6351384be8cec767405f7f7aecaf2223173", + "reftest" + ], + "css/css-break/block-end-aligned-abspos.html": [ + "c7acaa977b240ecde638e900d0fec7844cf2b965", + "testharness" + ], "css/css-break/break-before-always-001.xht": [ "e2e7297d1532fba60d2074aa2701600dc7441742", "visual" @@ -332304,7 +332446,7 @@ "support" ], "css/css-fonts/font-variant-alternates-parsing.html": [ - "f00fa53342cfa2eca715ca63ef6cd00a57640aaf", + "216ed0dba04772c28e4436b4c5f70e9ace2faaa2", "testharness" ], "css/css-fonts/font-variant-caps-01-ref.html": [ @@ -342611,10 +342753,6 @@ "9b2e5be0a19c48f73b57fe0ad8bbeea81238a1d1", "support" ], - "css/css-logical/animation-001-expected.txt": [ - "81869ec65d57dfe889403f1ee04463abd898396d", - "support" - ], "css/css-logical/animation-001.html": [ "8135f43275bb1d6b918fd410ec41823ea77961dd", "testharness" @@ -347299,6 +347437,10 @@ "7fe9744af9584c07ffff6c408574002896e8c134", "testharness" ], + "css/css-shadow-parts/double-forward.html": [ + "d23ec775fff830bd3ed2668ec2dc7ab184a6dc37", + "testharness" + ], "css/css-shadow-parts/host-stylesheet.html": [ "2e65c4b1b57bd9959c68e85e11b442c67f2c5a42", "testharness" @@ -347307,18 +347449,30 @@ "2dfd4b0510a758c73bf8ac8291088d39077578d7", "testharness" ], + "css/css-shadow-parts/invalidation-change-exportparts-forward.html": [ + "1e319deb633cdb765ea4613eb7c2b8c6dd0e615a", + "testharness" + ], + "css/css-shadow-parts/invalidation-change-part-name-forward.html": [ + "f8da6d1f543fcfdcfe9c191d5564c9c07af930f3", + "testharness" + ], "css/css-shadow-parts/invalidation-change-part-name-idl-domtokenlist.html": [ "2f9fffb86eacb088365fc592e31c58238e8321dc", "testharness" ], "css/css-shadow-parts/invalidation-change-part-name-idl-setter.html": [ - "52af22af7695157709836e0174655d04dcfccf94", + "0ed46f53bc75916b7ee9b83c4d1c84f9451e76f5", "testharness" ], "css/css-shadow-parts/invalidation-change-part-name.html": [ "47630d956f9bf3053ec3ed8a2d04223bdd8720a9", "testharness" ], + "css/css-shadow-parts/invalidation-complex-selector-forward.html": [ + "7c732b9bdf12467a40b64ebf8a02a10f249a900b", + "testharness" + ], "css/css-shadow-parts/invalidation-complex-selector.html": [ "5b1fd800790c4e14ec8fbc34bd24eb6c2eb31ab0", "testharness" @@ -347327,6 +347481,18 @@ "fc3282a6e944950548eeda66a78d453ec1a552f3", "testharness" ], + "css/css-shadow-parts/precedence-part-vs-part.html": [ + "9905cf8b5e46b51dc21326dc31f8c2bc6d7a39b6", + "testharness" + ], + "css/css-shadow-parts/simple-forward-shorthand.html": [ + "0142967dfdb707a376b86e5347465117033cda01", + "testharness" + ], + "css/css-shadow-parts/simple-forward.html": [ + "a1a19aee4ede175f7e862318105f4625144b6e42", + "testharness" + ], "css/css-shadow-parts/simple.html": [ "a7f17d9670b137995b0dfc6f43221e16b988376d", "testharness" @@ -360340,7 +360506,7 @@ "testharness" ], "css/css-transitions/currentcolor-animation-001.html": [ - "e36e748150680628c150a12f686579da6e99ddcc", + "4fd982a8cc77aa999c947d5c47e0aec8df8b9a92", "testharness" ], "css/css-transitions/detached-container-001.html": [ @@ -361020,7 +361186,7 @@ "testharness" ], "css/css-transitions/transitions-animatable-properties-01.html": [ - "39dd073f929fa59abb52bc7b4b4644a351670ad2", + "48a7d1e2e016ae914dbc9b8c08eadbc0e2a669a2", "testharness" ], "css/css-transitions/zero-duration-multiple-transition.html": [ @@ -365304,7 +365470,7 @@ "testharness" ], "css/css-values/calc-unit-analysis.html": [ - "1520b4d3fa2390c219d637023fc3981dc01ab8ff", + "20eab22bf7cdff8c4fdc7a88b1524f69d4b042fb", "testharness" ], "css/css-values/ch-unit-001.html": [ @@ -365708,7 +365874,7 @@ "support" ], "css/css-variables/test_variable_legal_values.html": [ - "2e074389f7a4ff38f7cbdac8f865f8cffde9663a", + "1d86c0834ccb1da7965edf56f9a4aefc0a041421", "testharness" ], "css/css-variables/variable-animation-from-to.html": [ @@ -372336,7 +372502,7 @@ "testharness" ], "css/cssom-view/offsetParent_element_test.html": [ - "bb5686d41daebaa6cff5b023cbab5211248b7aac", + "c88b616986511b3220449c03421e827be0d2e534", "testharness" ], "css/cssom-view/offsetTopLeftInScrollableParent.html": [ @@ -372776,7 +372942,7 @@ "testharness" ], "css/cssom/computed-style-001.html": [ - "80bf06c300ec7a693ca74dc98dbf2b62df721aaa", + "d637b066b03a71283ad89315a5c346a1715900f1", "testharness" ], "css/cssom/computed-style-002.html": [ @@ -372792,7 +372958,7 @@ "testharness" ], "css/cssom/computed-style-005.html": [ - "998f70eb97836575c0135ff5311a43b6ee09ab94", + "49a5977acdb999be701ecc6da3c10eb433237621", "testharness" ], "css/cssom/computed-style-set-property.html": [ @@ -372972,7 +373138,7 @@ "testharness" ], "css/cssom/inline-style-001.html": [ - "51f36f250e5c10cec7f08f5aa1a2de989d90bfd8", + "d4bf3b92ab2c9a45614754807cdd5f2af79c1fa5", "testharness" ], "css/cssom/insertRule-charset-no-index.html": [ @@ -373012,19 +373178,19 @@ "reftest" ], "css/cssom/medialist-interfaces-001.html": [ - "19c661e1b3dffa1f30d9886346317879063ae0d4", + "f436177fb8ec210d878418883d7876f64d1c45df", "testharness" ], "css/cssom/medialist-interfaces-002.html": [ - "2b6bba2a661ed257fcb775b3a2884f3dfb630c3e", + "9820015f5e02642ea4c544184811f9f243ee83c5", "testharness" ], "css/cssom/medialist-interfaces-003.html": [ - "649f9485f44f800b7685d604ac31c88ce43e4d81", + "1778c4a7ae98904460054157c2cc44ae264e0e70", "testharness" ], "css/cssom/medialist-interfaces-004.html": [ - "cf9befb8ffb628f59508d5d74ec6ed4db9e4e09e", + "7cbea37cba421bbf13887322cc48b72a8e04cdc8", "testharness" ], "css/cssom/overflow-serialization.html": [ @@ -373100,11 +373266,11 @@ "testharness" ], "css/cssom/style-sheet-interfaces-001.html": [ - "20dc9713e58b05a159ef731164889fc37b4b02aa", + "1f6c9e249357df597ecdf270bf9820be8254f40a", "testharness" ], "css/cssom/style-sheet-interfaces-002.html": [ - "51b0eb336be7abb33b7b0b29523b1eafd3d9b93e", + "e86a9a16e3bc9c0a22277996ad1fbb5f273d4bdd", "testharness" ], "css/cssom/stylesheet-replacedata-dynamic-ref.html": [ @@ -374312,7 +374478,7 @@ "support" ], "css/mediaqueries/test_media_queries.html": [ - "a239efdc1168f69471f5d0a88e4f9027fc00ae17", + "250f9524adeadeb2684196ccac8843cfed1567c2", "testharness" ], "css/mediaqueries/viewport-script-dynamic-ref.html": [ @@ -389011,6 +389177,10 @@ "721d6e79b5248ed7a4334d754b8039c366090051", "testharness" ], + "fetch/images/canvas-remote-read-remote-image-redirect.html": [ + "bfcb7537651f285d0aa5d60a41032c534ff39b95", + "testharness" + ], "fetch/nosniff/image.html": [ "9dfdb94cf62a4cde91e44f6d4299ca26c15ba9db", "testharness" @@ -390296,7 +390466,7 @@ "testharness" ], "hr-time/monotonic-clock.any.js": [ - "f7f254557f4296f8e69757eb9ed3ac11a05d3a33", + "c53b04d844e4f587891595c09c56e336f3893f9b", "testharness" ], "hr-time/performance-tojson.html": [ @@ -390979,18 +391149,10 @@ "45f7e38ba3e8419e592e8fee51d95447d09e7173", "testharness" ], - "html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-2-expected.txt": [ - "cc68c1805546aae5685de826578e7cf87aede63f", - "support" - ], "html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-2.html": [ "cd2502ab1cba09430b3422fa1f1542f3cd37e15c", "testharness" ], - "html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-expected.txt": [ - "4d8f637290790a1d59685ba16d156b77039b0624", - "support" - ], "html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding.html": [ "21fbd4618da539e7bc7b9939bf8193337cd59e29", "testharness" @@ -402723,6 +402885,10 @@ "15e02bcf51535d45a702b0977f919eff8ce5ba9c", "testharness" ], + "html/semantics/embedded-content/the-img-element/available-images-onload.html": [ + "5fc5cb8b61986a020b52a16dd765a88459399165", + "testharness" + ], "html/semantics/embedded-content/the-img-element/available-images-ref.html": [ "8061abae50899a2befe286723d8bd5c285b356ab", "support" @@ -403443,8 +403609,12 @@ "55d3091a0aec33b78a95c2784e5ca2ff60de3504", "testharness" ], + "html/semantics/forms/the-button-element/button-click-submits-expected.txt": [ + "a95568a81ac896b6c5ea79df4de246220b122c5a", + "support" + ], "html/semantics/forms/the-button-element/button-click-submits.html": [ - "e6f02d3e21caf3a4f53f3698f69c17f64aad069f", + "f09d06080fbe83feb401f575e7d78b0a741009f1", "testharness" ], "html/semantics/forms/the-button-element/button-events.html": [ @@ -404543,6 +404713,18 @@ "dd2d719134fd7573e85c9a696350cffa1705b661", "support" ], + "html/semantics/links/links-created-by-a-and-area-elements/support/target_blank_iplicit_noopener.html": [ + "bf6a1ae5bfe16e4fd50296636894859a0ee25ec1", + "support" + ], + "html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt": [ + "f6a44d6bfb0ac1777716ca9ea90561f33fc7a587", + "support" + ], + "html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html": [ + "39903dcd520c52669f7ab15494777a63c6e7c1b1", + "testharness" + ], "html/semantics/links/linktypes/alternate-css-ref.html": [ "ec961eac157152db3f3428392d93cb7f74f366ed", "support" @@ -406280,7 +406462,7 @@ "support" ], "html/semantics/scripting-1/the-script-element/muted-errors.sub.html": [ - "a42179dc85d35f328a69f12bbfd2b2f6211b7151", + "1b255faf7e1286f9379e825403de2b069c452747", "testharness" ], "html/semantics/scripting-1/the-script-element/nomodule-reflect.html": [ @@ -409228,7 +409410,7 @@ "testharness" ], "html/webappapis/system-state-and-capabilities/the-navigator-object/protocol.https.html": [ - "d090aad609dcaaf93d7479134f3eda15c82d2653", + "006827f186eb4e47d387a3b0c9fae404e41e1d37", "testharness" ], "html/webappapis/the-windoworworkerglobalscope-mixin/Worker_Self_Origin.html": [ @@ -409704,11 +409886,11 @@ "support" ], "infrastructure/metadata/infrastructure/testdriver/actions/elementPosition.html.ini": [ - "f751532cee7e7a558c85011986aa72a65b79ce7c", + "750dd055dbd80030672572bc51f6dce2f5757698", "support" ], "infrastructure/metadata/infrastructure/testdriver/actions/elementTiming.html.ini": [ - "a1e9ea86844e78c00282a32a5a64c6365c04ffa2", + "7a6cf82bbd3aad03ac3367e8a9b5e20e5aab1c25", "support" ], "infrastructure/metadata/infrastructure/testdriver/actions/eventOrder.html.ini": [ @@ -409891,6 +410073,18 @@ "37721ad9ef3df10f8cdc1da74c27a2259d4601f6", "testharness" ], + "infrastructure/testdriver/file_upload.py": [ + "32633679a9f33d516398f811d888cabf9b062b90", + "support" + ], + "infrastructure/testdriver/file_upload.sub.html": [ + "29c42b49f1716200ef6b68eda4fefd716441fcd8", + "testharness" + ], + "infrastructure/testdriver/file_upload_data.txt": [ + "097d2a3a3f31dbd8f14cff73974cf042b6ebfcd2", + "support" + ], "infrastructure/testdriver/send_keys-expected.txt": [ "fbd705a2a1403a1c6e14a3fdfb6f7cd6a7af0193", "support" @@ -410528,7 +410722,7 @@ "support" ], "interfaces/webxr.idl": [ - "7f7b43c222bd3bc4dcab0c618402ff8ff61ae470", + "27ee27493aaa98869c9fe3adc0f4f19ec99e85e2", "support" ], "interfaces/worklets.idl": [ @@ -414988,7 +415182,7 @@ "support" ], "navigation-timing/resources/webperftestharness.js": [ - "afdfa2a768b1065f05f61de77d6528aee658d7dc", + "3efb52783f1e5dcb0d42aad11aec2a9e47257d33", "support" ], "navigation-timing/test_document_open.html": [ @@ -415008,7 +415202,7 @@ "testharness" ], "navigation-timing/test_navigation_redirectCount_none.html": [ - "eaaef4b514c7f44aaeb64b9f0d9307fa50ad068a", + "da94d24c746212e0fdf60872f3dc81cc10f2db9a", "testharness" ], "navigation-timing/test_navigation_type_backforward.html": [ @@ -415024,7 +415218,7 @@ "testharness" ], "navigation-timing/test_no_previous_document.html": [ - "0b9eb4b2224a70c6c75c9d35fe1871a52cc7d7b2", + "0bce16525caa65d666e2bb061227c277478237bc", "testharness" ], "navigation-timing/test_performance_attributes.sub.html": [ @@ -415048,15 +415242,15 @@ "testharness" ], "navigation-timing/test_timing_attributes_order.html": [ - "03c2619cb3e4ad4916bcdf9cf51174b61416e546", + "5e885ea7ec3f360d6fd6ba060d49773713fef228", "testharness" ], "navigation-timing/test_timing_client_redirect.html": [ - "3bc369234a03fe081f55a4ded8d85bd0fa6b86c0", + "bebf39eb98a6f26dd9623dff2b31cec28f101d87", "testharness" ], "navigation-timing/test_timing_reload.html": [ - "0e28a6479b10c3610dc18687dcb0a92e1fd95e3a", + "a660caf4ef9fffc32dfbc9da4a76c590689cf4aa", "testharness" ], "navigation-timing/test_timing_server_redirect.html": [ @@ -415064,7 +415258,7 @@ "testharness" ], "navigation-timing/test_timing_xserver_redirect.html": [ - "93db8699f879e54e4ffb8440b4b28ab7dcc65905", + "a39f7c2642cd0c091267af6f151ff8b45f56be09", "testharness" ], "navigation-timing/test_unique_performance_objects.html": [ @@ -433160,7 +433354,7 @@ "support" ], "requestidlecallback/basic.html": [ - "e481a6bd3bd1f936d06b93a6d31d839442776981", + "429134ec4360f1bbbae4db608a93a6ba25930604", "testharness" ], "requestidlecallback/callback-exception.html": [ @@ -433344,7 +433538,7 @@ "testharness" ], "resource-timing/resource_connection_reuse.html": [ - "d2bcab912ed79a58ff48c5f01287423e1a1b1638", + "74c7c10821e899fc8cfcb4d6b958281966557b4f", "testharness" ], "resource-timing/resource_dedicated_worker.html": [ @@ -433560,7 +433754,7 @@ "support" ], "resource-timing/resources/webperftestharness.js": [ - "98b2954bad3765c94d6c7c3faf1128b47bf032b4", + "203eb0d16b4f3ad8d22877ff7afc7064fe252892", "support" ], "resource-timing/resources/webperftestharnessextension.js": [ @@ -433947,8 +434141,20 @@ "a449b32d2be4bfe9e825ff3b3637a5ddb609b93e", "testharness" ], + "scroll-animations/current-time-nan.html": [ + "356f0a606826377aa20c6750cad7230fdc17c450", + "testharness" + ], + "scroll-animations/current-time-root-scroller.html": [ + "8e600e6ef05e17e0b1d93ce3fa12f6dbe8fe50c6", + "testharness" + ], + "scroll-animations/current-time-writing-modes.html": [ + "a7e55513eec655ba51d5d7ad680cab9c7f977946", + "testharness" + ], "scroll-animations/current-time.html": [ - "8c70594612ac758f7934d8f30818cb0150925e5e", + "0dc2a6fd4ad9702b5664df69fd015e3880106a47", "testharness" ], "scroll-animations/idlharness-expected.txt": [ @@ -438340,7 +438546,7 @@ "support" ], "signed-exchange/resources/generate-test-certs.sh": [ - "e1d2ea9e3cb5f5ecb63e50747d53212276c1c4f2", + "01330e46d8f6aad6baab7b1bdb7c228a627eac21", "support" ], "signed-exchange/resources/generate-test-sxgs.sh": [ @@ -441888,7 +442094,7 @@ "testharness" ], "user-timing/resources/webperftestharness.js": [ - "79c218f336fb0e7a08ae145dae39aac9517892ce", + "4a8e2de69fc803c7fd06d7372a0de395aceec670", "support" ], "user-timing/resources/webperftestharnessextension.js": [ @@ -445879,6 +446085,14 @@ "88bdfcfc2867335ca53c30f5637b38b3d12c64ca", "testharness" ], + "webrtc/protocol/msid-parse-expected.txt": [ + "e6f3f372122735b12d75a4f108cc38fe766fe718", + "support" + ], + "webrtc/protocol/msid-parse.html": [ + "e0d3eb76a3a98497e1bcfed36d2ce0e6d4cb0e75", + "testharness" + ], "webrtc/protocol/video-codecs.https.html": [ "e728effbeb94de865df9f8860cd45c8de1f601c1", "testharness"
diff --git a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/ecdsa.js b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/ecdsa.js index 869fb79..208b81c4 100644 --- a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/ecdsa.js +++ b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/ecdsa.js
@@ -1,5 +1,7 @@ function run_test() { + setup({explicit_done: true}); + var subtle = self.crypto.subtle; // Change to test prefixed implementations // When are all these tests really done? When all the promises they use have resolved.
diff --git a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/hmac.js b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/hmac.js index 22a2acf..e8f9ec5 100644 --- a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/hmac.js +++ b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/hmac.js
@@ -1,5 +1,7 @@ function run_test() { + setup({explicit_done: true}); + var subtle = self.crypto.subtle; // Change to test prefixed implementations // When are all these tests really done? When all the promises they use have resolved.
diff --git a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/rsa.js b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/rsa.js index 656c320f7..251f57e 100644 --- a/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/rsa.js +++ b/third_party/blink/web_tests/external/wpt/WebCryptoAPI/sign_verify/rsa.js
@@ -1,5 +1,7 @@ function run_test() { + setup({explicit_done: true}); + var subtle = self.crypto.subtle; // Change to test prefixed implementations // When are all these tests really done? When all the promises they use have resolved.
diff --git a/third_party/blink/web_tests/external/wpt/common/performance-timeline-utils.js b/third_party/blink/web_tests/external/wpt/common/performance-timeline-utils.js index 3efce5b..b20241c 100644 --- a/third_party/blink/web_tests/external/wpt/common/performance-timeline-utils.js +++ b/third_party/blink/web_tests/external/wpt/common/performance-timeline-utils.js
@@ -1,3 +1,7 @@ +/* +author: W3C http://www.w3.org/ +help: http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute +*/ var performanceNamespace = window.performance; var namespace_check = false; function wp_test(func, msg, properties) @@ -10,7 +14,8 @@ if (performanceNamespace === undefined || performanceNamespace == null) { // show a single error that window.performance is undefined - test(function() { assert_true(performanceNamespace !== undefined && performanceNamespace != null, "window.performance is defined and not null"); }, "window.performance is defined and not null.", {author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + // The window.performance attribute provides a hosting area for performance related attributes. + test(function() { assert_true(performanceNamespace !== undefined && performanceNamespace != null, "window.performance is defined and not null"); }, "window.performance is defined and not null."); } }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-fonts/font-variant-alternates-parsing.html b/third_party/blink/web_tests/external/wpt/css/css-fonts/font-variant-alternates-parsing.html index f00fa53..216ed0d 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-fonts/font-variant-alternates-parsing.html +++ b/third_party/blink/web_tests/external/wpt/css/css-fonts/font-variant-alternates-parsing.html
@@ -5,9 +5,10 @@ <link rel="help" href="https://www.w3.org/TR/css-fonts-4/#font-variant-alternates-prop"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> +<div></div> <script> test(function() { - let div = document.createElement('div'); + let div = document.querySelector('div'); div.style.fontVariantAlternates = "Historical-Forms"; assert_equals( getComputedStyle(div).fontVariantAlternates,
diff --git a/third_party/blink/web_tests/external/wpt/css/css-shadow-parts/invalidation-change-part-name-idl-setter.html b/third_party/blink/web_tests/external/wpt/css/css-shadow-parts/invalidation-change-part-name-idl-setter.html index 52af22a..0ed46f53 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-shadow-parts/invalidation-change-part-name-idl-setter.html +++ b/third_party/blink/web_tests/external/wpt/css/css-shadow-parts/invalidation-change-part-name-idl-setter.html
@@ -11,9 +11,10 @@ </head> <body> <style>#c-e::part(partp) { color: red; }</style> + <style>#c-e::part(new-partp) { color: green; }</style> <script>installCustomElement("custom-element", "custom-element-template");</script> <template id="custom-element-template"> - <style>span { color: green; }</style> + <style>span { color: blue; }</style> <span id="part" part="partp">This text</span> </template> The following text should be green:
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transitions/currentcolor-animation-001.html b/third_party/blink/web_tests/external/wpt/css/css-transitions/currentcolor-animation-001.html index e36e748..4fd982a8 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transitions/currentcolor-animation-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transitions/currentcolor-animation-001.html
@@ -15,6 +15,7 @@ <div id="test"></div> <script> + // Transition does not occur when the value is currentColor and color changes test(function() { var div = document.getElementById("test"); var cs = getComputedStyle(div, ""); @@ -32,8 +33,7 @@ assert_true(quarter_interpolated != quarter_reference && quarter_interpolated == final_reference); }, - "currentcolortransition", - { assert: "Transition does not occur when the value is currentColor and color changes" }); + "currentcolortransition"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-transitions/transitions-animatable-properties-01.html b/third_party/blink/web_tests/external/wpt/css/css-transitions/transitions-animatable-properties-01.html index 39dd073..48a7d1e 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-transitions/transitions-animatable-properties-01.html +++ b/third_party/blink/web_tests/external/wpt/css/css-transitions/transitions-animatable-properties-01.html
@@ -100,10 +100,8 @@ // create all the tests we need for (var i = 0; i < kANIMATABLE_CSS_PROPERTIES.length; i++) { - testsIntermediate.push(async_test(kANIMATABLE_CSS_PROPERTIES[i][0] + " intermediate", - { assert: "property " + kANIMATABLE_CSS_PROPERTIES[i][0] + " is animatable" })); - testsEnd.push(async_test(kANIMATABLE_CSS_PROPERTIES[i][0] + " end", - { assert: "property " + kANIMATABLE_CSS_PROPERTIES[i][0] + " has correct value after transition's end" })); + testsIntermediate.push(async_test(kANIMATABLE_CSS_PROPERTIES[i][0] + " intermediate")); + testsEnd.push(async_test(kANIMATABLE_CSS_PROPERTIES[i][0] + " end")); } // getComputedStyle helper
diff --git a/third_party/blink/web_tests/external/wpt/css/css-values/calc-unit-analysis.html b/third_party/blink/web_tests/external/wpt/css/css-values/calc-unit-analysis.html index 1520b4d..20eab22 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-values/calc-unit-analysis.html +++ b/third_party/blink/web_tests/external/wpt/css/css-values/calc-unit-analysis.html
@@ -32,8 +32,7 @@ test_elt.style.setProperty(property, value); test_elt.style.removeProperty(property); }, - description_to_name(description), - { assert: "invalid calc expression: " + description }); + description_to_name(description)); } function assert_valid_value(property, value, computes_to, description) { @@ -46,27 +45,26 @@ computes_to); test_elt.style.removeProperty(property); }, - description_to_name(description), - { assert: "valid calc expression: " + description }); + description_to_name(description)); } - assert_invalid_value("margin-left", "calc(0)", + assert_invalid_value("margin-left", "calc(0)", // invalid calc expression "unitless zero in calc() is a numeric type, not length"); assert_valid_value("margin-left", "calc(0px)", "0px", "0px in calc()"); - assert_invalid_value("margin-left", "calc(1px + 2)", + assert_invalid_value("margin-left", "calc(1px + 2)", // invalid calc expression "addition of length and number"); - assert_invalid_value("margin-left", "calc(2 + 1px)", + assert_invalid_value("margin-left", "calc(2 + 1px)", // invalid calc expression "addition of number and length"); - assert_invalid_value("margin-left", "calc(1px - 2)", + assert_invalid_value("margin-left", "calc(1px - 2)", // invalid calc expression "subtraction of length and number"); - assert_invalid_value("margin-left", "calc(2 - 1px)", + assert_invalid_value("margin-left", "calc(2 - 1px)", // invalid calc expression "subtraction of number and length"); assert_valid_value("margin-left", "calc(2px * 2)", "4px", "multiplication of length and number"); assert_valid_value("margin-left", "calc(2 * 2px)", "4px", "multiplication of number and length"); - assert_invalid_value("margin-left", "calc(2px * 1px)", + assert_invalid_value("margin-left", "calc(2px * 1px)", // invalid calc expression "multiplication of length and length"); }
diff --git a/third_party/blink/web_tests/external/wpt/css/css-variables/test_variable_legal_values.html b/third_party/blink/web_tests/external/wpt/css/css-variables/test_variable_legal_values.html index 2e07438..1d86c08 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-variables/test_variable_legal_values.html +++ b/third_party/blink/web_tests/external/wpt/css/css-variables/test_variable_legal_values.html
@@ -44,8 +44,7 @@ assert_not_equals(initial_cs, red_cs); assert_equals(initial_cs, test_cs.backgroundColor); }, - description_to_name(description), - { assert: "Value allowed within variable: " + description }); + description_to_name(description)); } function assert_disallowed_balanced_variable_value(value, description) { @@ -59,8 +58,7 @@ assert_not_equals(green_cs, red_cs); assert_equals(green_cs, test_cs.backgroundColor); }, - description_to_name(description), - { assert: "Value not allowed within variable: " + description }); + description_to_name(description)); } assert_allowed_variable_value("25%", "percentage");
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom-view/offsetParent_element_test.html b/third_party/blink/web_tests/external/wpt/css/cssom-view/offsetParent_element_test.html index bb5686d..c88b6169 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom-view/offsetParent_element_test.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom-view/offsetParent_element_test.html
@@ -93,6 +93,7 @@ var table_element_tr = document.getElementById('table-element-tr'); var table_element = document.getElementById('table-element'); +// The offsetParent attribute algorithm rule checking passed! test(function() { assert_equals(html.offsetParent,null); assert_equals(body.offsetParent,null); @@ -104,10 +105,9 @@ assert_equals(none_element_child_audio.offsetParent,null); assert_equals(none_element_child_canvas.offsetParent,null); assert_equals(none_element_child_svg.offsetParent,undefined); -}, "Valid the algorithm rule of offsetParent check step 1", -{ assert: "The offsetParent attribute algorithm rule checking passed!" } -); +}, "Valid the algorithm rule of offsetParent check step 1"); +// The offsetParent attribute algorithm rule checking passed! test(function() { assert_equals(body_element_child.offsetParent,body); assert_equals(window.getComputedStyle(relative_element).position,'relative'); @@ -122,9 +122,7 @@ assert_equals(caption_element_child.offsetParent,table_element); assert_equals(window.getComputedStyle(td_element).position,'static'); assert_equals(td_element.offsetParent,table_element); -}, "Valid the algorithm rule of offsetParent check step 2", -{ assert: "The offsetParent attribute algorithm rule checking passed!" } -); +}, "Valid the algorithm rule of offsetParent check step 2"); </script>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-001.html b/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-001.html index 80bf06c..d637b066 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-001.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-001.html
@@ -33,6 +33,7 @@ var inner = document.getElementById("inside"); var innerStyle; + // do not allow modifications to a computed CSSStyleDeclaration test(function() { innerStyle = window.getComputedStyle(inner); assert_throws( "NO_MODIFICATION_ALLOWED_ERR", @@ -44,27 +45,22 @@ assert_throws( "NO_MODIFICATION_ALLOWED_ERR", function() { innerStyle.color = "blue"; }, "do not allow setting a property on a readonly CSSStyleDeclaration"); - }, "read_only", { - assert: "do not allow modifications to a computed CSSStyleDeclaration" - }); + }, "read_only"); + // Directly set properties are resolved test(function() { assert_equals(innerStyle.getPropertyValue("height"), "100px"); - }, "property_values", { - assert: "Directly set properties are resolved" - }); + }, "property_values"); + // Inherited properties are resolved test(function() { assert_equals(innerStyle.getPropertyValue("font-size"), "100px"); - }, "inherited_property_values", { - assert: "Inherited properties are resolved" - }); + }, "inherited_property_values"); + // Relative properties are resolved test(function() { assert_equals(innerStyle.getPropertyValue("width"), "100px"); - }, "relative_property_values", { - assert: "Relative properties are resolved" - }); + }, "relative_property_values"); </script> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-005.html b/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-005.html index 998f70eb..49a5977 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-005.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/computed-style-005.html
@@ -47,19 +47,17 @@ let elem = document.getElementById(id); let elemStyle = window.getComputedStyle(elem); + // positioned element's auto margins should be resolved to 10px. test(function() { assert_equals(elemStyle.getPropertyValue("margin-left"), "10px"); assert_equals(elemStyle.getPropertyValue("margin-right"), "10px"); - }, id + "_computed_margins", { - assert: id + "-positioned element's auto margins should be resolved to 10px." - }); + }, id + "_computed_margins"); + // positioned element should have a left and right of 0px (as authored). test(function() { assert_equals(elemStyle.getPropertyValue("left"), "0px"); assert_equals(elemStyle.getPropertyValue("right"), "0px"); - }, id + "_computed_left_and_right", { - assert: id + "-positioned element should have a left and right of 0px (as authored)." - }); + }, id + "_computed_left_and_right"); } </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/inline-style-001.html b/third_party/blink/web_tests/external/wpt/css/cssom/inline-style-001.html index 51f36f2..d4bf3b9 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/inline-style-001.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/inline-style-001.html
@@ -14,21 +14,22 @@ <div id="log"></div> <div id="test" style="margin-left: 5px;"></div> <script type="text/javascript"> + // Can access CSSStyleDeclaration through style property test(function() { var test = document.getElementById("test"); assert_idl_attribute(test, "style"); declaration = test.style; - }, "CSSStyleDeclaration_accessible", { - assert: "Can access CSSStyleDeclaration through style property" - }); + }, "CSSStyleDeclaration_accessible"); + // initial property values are correct test(function() { assert_equals(declaration.cssText, "margin-left: 5px;"); assert_equals(declaration.getPropertyValue("margin-left"), "5px"); - }, "read", { - assert: "initial property values are correct" - }); + }, "read"); + // setting cssText adds new properties + // setting cssText removes existing properties + // properties set through cssText are reflected in the computed style test(function() { declaration.cssText = "margin-left: 10px; padding-left: 10px;"; assert_equals(declaration.cssText, "margin-left: 10px; padding-left: 10px;"); @@ -41,12 +42,10 @@ var computedStyle = window.getComputedStyle(document.getElementById("test")); assert_equals(computedStyle.getPropertyValue("margin-left"), "10px"); assert_equals(computedStyle.getPropertyValue("padding-left"), "10px"); - }, "csstext_write", { - assert: [ "setting cssText adds new properties", - "setting cssText removes existing properties", - "properties set through cssText are reflected in the computed style"] - }); + }, "csstext_write"); + // setProperty adds new properties + // properties set through setProperty are reflected in the computed style test(function() { while(declaration.length > 0) declaration.removeProperty(declaration.item(0)); @@ -62,11 +61,9 @@ var computedStyle = window.getComputedStyle(document.getElementById("test")); assert_equals(computedStyle.getPropertyValue("margin-left"), "15px"); assert_equals(computedStyle.getPropertyValue("padding-left"), "15px"); - }, "property_write", { - assert: [ "setProperty adds new properties", - "properties set through setProperty are reflected in the computed style"] - }); + }, "property_write"); + // shorthand property is expanded test(function() { while(declaration.length > 0) declaration.removeProperty(declaration.item(0)); @@ -75,9 +72,7 @@ assert_equals(declaration.getPropertyValue("margin-right"), "20px"); assert_equals(declaration.getPropertyValue("margin-bottom"), "20px"); assert_equals(declaration.getPropertyValue("margin-left"), "20px"); - }, "shorthand_properties", { - assert: "shorthand property is expanded" - }); + }, "shorthand_properties"); </script> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/interfaces-expected.txt b/third_party/blink/web_tests/external/wpt/css/cssom/interfaces-expected.txt index a83ae3f..f66a1fe1 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/interfaces-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/cssom/interfaces-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 376 tests; 321 PASS, 55 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 376 tests; 320 PASS, 56 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Partial interface Document: original interface defined PASS Partial interface Window: original interface defined @@ -38,7 +38,9 @@ PASS StyleSheet interface: attribute title PASS StyleSheet interface: attribute media PASS StyleSheet interface: attribute disabled -PASS CSSStyleSheet interface: existence and properties of interface object +FAIL CSSStyleSheet interface: existence and properties of interface object assert_throws: interface object didn't throw TypeError when called as a constructor function "function() { + new interface_object(); + }" did not throw PASS CSSStyleSheet interface object length PASS CSSStyleSheet interface object name PASS CSSStyleSheet interface: existence and properties of interface prototype object
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-001.html b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-001.html index 19c661e1..f436177f 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-001.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-001.html
@@ -5,6 +5,8 @@ <link rel="author" title="Ben Sheldon" href="mailto:ben@codeforamerica.org"> <link rel="author" title="Chapman Shoop" href="mailto:chapman.shoop@gmail.com"> <link rel="help" href="http://www.w3.org/TR/cssom-1/#the-medialist-interface"> + <link rel="help" href="http://www.w3.org/TR/cssom-1/#serializing-media-queries"> + <link rel="help" href="http://www.w3.org/TR/cssom-1/#serialize-a-media-query-list"> <meta name="flags" content="dom"> <meta name="assert" content="MediaLists are serialized according to the specification"> <script src="/resources/testharness.js" type="text/javascript"></script> @@ -40,36 +42,33 @@ mediaList = styleSheet.media; } - + // MediaList.mediaText equals the 'media' value of the initial 'style' element. test(function() { setup(); assert_equals(mediaList.mediaText, "all"); - }, "mediatest_medialist_serialize_element", - { help: ["http://www.w3.org/TR/cssom-1/#the-medialist-interface", "http://www.w3.org/TR/cssom-1/#serializing-media-queries"], - assert: ["MediaList.mediaText equals the 'media' value of the initial 'style' element."] }); + }, "mediatest_medialist_serialize_element"); + // To serialize a comma-separated list concatenate all items of the list in list order while separating them by \",\" (U+002C), followed by a space (U+0020). test(function() { setup(); mediaList.appendMedium('screen'); assert_equals(mediaList.mediaText, "all, screen"); - }, "mediatest_medialist_serialize_comma", - { help: ["http://www.w3.org/TR/cssom-1/#the-medialist-interface", "http://www.w3.org/TR/cssom-1/#serialize-a-media-query-list"], - assert: ["To serialize a comma-separated list concatenate all items of the list in list order while separating them by \",\" (U+002C), followed by a space (U+0020)."] }); + }, "mediatest_medialist_serialize_comma"); + // If the media query list is empty return the empty string. test(function() { setup(); mediaList.deleteMedium('all'); assert_equals(mediaList.mediaText, ""); - }, "mediatest_medialist_serialize_empty", - { help: ["http://www.w3.org/TR/cssom-1/#the-medialist-interface", "http://www.w3.org/TR/cssom-1/#serializing-media-queries"], - assert: ["If the media query list is empty return the empty string."] }); + }, "mediatest_medialist_serialize_empty"); + // Each media query should be sorted in the same order as they appear in the list of media queries. test(function() { setup(); @@ -77,9 +76,7 @@ mediaList.appendMedium('print'); assert_equals(mediaList.mediaText, "all, screen, print"); - }, "mediatest_medialist_serialize_order", - { help: ["http://www.w3.org/TR/cssom-1/#the-medialist-interface", "http://www.w3.org/TR/cssom-1/#serialize-a-media-query-list"], - assert: ["Each media query should be sorted in the same order as they appear in the list of media queries."] }); + }, "mediatest_medialist_serialize_order"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-002.html b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-002.html index 2b6bba2..9820015 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-002.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-002.html
@@ -33,12 +33,13 @@ <script type="text/javascript"> + // MediaList.deleteMedium called without argument throws error. test(function() { media_list = setup(); assert_throws(new TypeError, function() { media_list.deleteMedium(); }); - }, "deleteMedium_called_without_argument", - { assert: "MediaList.deleteMedium called without argument throws error." }); + }, "deleteMedium_called_without_argument"); + // MediaList.deleteMedium removes correct medium and updates corresponding properties. test(function() { media_list = setup(); @@ -50,9 +51,9 @@ assert_equals(media_list.length, 1); assert_equals(media_list.item(0), "all"); assert_equals(media_list.mediaText, "all"); - }, "deleteMedium_removes_correct_medium", - { assert: "MediaList.deleteMedium removes correct medium and updates corresponding properties." }); + }, "deleteMedium_removes_correct_medium"); + // MediaList.deleteMedium doesn't modify MediaList when medium is not found. test(function() { media_list = setup(); @@ -63,8 +64,7 @@ assert_equals(media_list.length, 1); assert_equals(media_list.item(0), "all"); assert_equals(media_list.mediaText, "all"); - }, "deleteMedium_no_matching_medium_to_remove", - { assert: "MediaList.deleteMedium doesn't modify MediaList when medium is not found." }); + }, "deleteMedium_no_matching_medium_to_remove"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-003.html b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-003.html index 649f948..1778c4a 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-003.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-003.html
@@ -40,22 +40,21 @@ mediaList = styleSheet.media; } - + // First explicit example input (first column) and output (second column) in specification. test(function() { setupMedia('not screen and (min-WIDTH:5px) AND (max-width:40px )'); assert_equals(mediaList.mediaText, "not screen and (max-width: 40px) and (min-width: 5px)"); - }, "mediatest_mediaquery_serialize_1", - { assert: ["First explicit example input (first column) and output (second column) in specification."] }); + }, "mediatest_mediaquery_serialize_1"); + // Second explicit example input (first column) and output (second column) in specification. test(function() { setupMedia('all and (color) and (color) '); assert_equals(mediaList.mediaText, "(color)"); - }, "mediatest_mediaquery_serialize_2", - { assert: ["Second explicit example input (first column) and output (second column) in specification."] }); + }, "mediatest_mediaquery_serialize_2"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-004.html b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-004.html index cf9befb8..7cbea37c 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-004.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/medialist-interfaces-004.html
@@ -32,6 +32,7 @@ <script type="text/javascript"> + // MediaList.appendMedium correctly adds medium to empty MediaList. test(function() { media_list = setup(); @@ -40,9 +41,9 @@ assert_equals(media_list.length, 1); assert_equals(media_list.item(0), "all"); assert_equals(media_list.mediaText, "all"); - }, "appendMedium_correctly_appends_medium_to_empty_MediaList", - { assert: "MediaList.appendMedium correctly adds medium to empty MediaList." }); + }, "appendMedium_correctly_appends_medium_to_empty_MediaList"); + // MediaList.appendMedium correctly adds medium to a MediaList that already has a medium. test(function() { media_list = setup(); @@ -56,8 +57,7 @@ assert_equals(media_list.item(0), "screen"); assert_equals(media_list.item(1), "all"); assert_equals(media_list.mediaText, "screen, all"); - }, "appendMedium_correctly_appends_medium_to_nonempty_MediaList", - { assert: "MediaList.appendMedium correctly adds medium to a MediaList that already has a medium." }); + }, "appendMedium_correctly_appends_medium_to_nonempty_MediaList"); </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-001.html b/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-001.html index 20dc971..1f6c9e2 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-001.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-001.html
@@ -3,7 +3,9 @@ <head> <title>CSS Test: CSSOM StyleSheet Initial Values</title> <link rel="author" title="Bear Travis" href="mailto:betravis@adobe.com"> - <link rel="help" href="http://www.w3.org/TR/cssom-1/#css-style-sheets"> + <link rel="help" href="https://www.w3.org/TR/cssom-1/#css-style-sheets"> + <link rel="help" href="https://www.w3.org/TR/cssom-1/#the-cssimportrule-interface"> + <link rel="help" href="https://www.w3.org/TR/cssom-1/#the-linkstyle-interface"> <meta name="flags" content="dom"> <meta name="assert" content="StyleSheet and CSSStyleSheet objects have the properties specified in their interfaces"> <script src="/resources/testharness.js" type="text/javascript"></script> @@ -23,6 +25,9 @@ var styleSheet; var linkSheet; + + // styleElement.sheet exists and is a CSSStyleSheet + // linkElement.sheet exists and is a CSSStyleSheet test(function() { assert_idl_attribute(styleElement, "sheet"); assert_readonly(styleElement, "sheet"); @@ -31,11 +36,9 @@ assert_idl_attribute(linkElement, "sheet"); linkSheet = linkElement.sheet; assert_true(linkSheet instanceof CSSStyleSheet); - }, "sheet_property", - { help: "http://www.w3.org/TR/cssom-1/#the-linkstyle-interface", - assert: [ "styleElement.sheet exists", "styleElement.sheet is a CSSStyleSheet", - "linkElement.sheet exists", "linkElement.sheet is a CSSStyleSheet"] }); + }, "sheet_property"); + // The sheet property on LinkStyle should always return the current associated style sheet. test(function () { var style = document.createElement("style"); document.querySelector("head").appendChild(style); @@ -43,10 +46,10 @@ assert_equals(sheet1.cssRules.length, 0); style.appendChild(document.createTextNode("a { color: green; }")); assert_equals(style.sheet.cssRules.length, 1); - }, "sheet_property_updates", - { help: "https://www.w3.org/TR/cssom-1/#the-linkstyle-interface", - assert: "The sheet property on LinkStyle should always return the current associated style sheet." }); + }, "sheet_property_updates"); + // ownerRule, cssRules, insertRule and deleteRule properties exist on CSSStyleSheet + // ownerRule, cssRules are read only test(function() { assert_idl_attribute(styleSheet, "ownerRule"); assert_idl_attribute(styleSheet, "cssRules"); @@ -55,21 +58,19 @@ assert_readonly(styleSheet, "ownerRule"); assert_readonly(styleSheet, "cssRules"); - }, "CSSStyleSheet_properties", - { assert: [ "ownerRule, cssRules, insertRule and deleteRule properties exist on CSSStyleSheet", - "ownerRule, cssRules are read only"] }); + }, "CSSStyleSheet_properties"); var importSheet; + // CSSStyleSheet initial property values are correct test(function() { assert_equals(styleSheet.ownerRule, null); assert_true(styleSheet.cssRules.length > 0); assert_true(styleSheet.cssRules.item(0) instanceof CSSImportRule); importSheet = styleSheet.cssRules.item(0).styleSheet; - }, "CSSStyleSheet_property_values", - { help: [ "http://www.w3.org/TR/cssom-1/#css-style-sheets", - "http://www.w3.org/TR/cssom-1/#cssimportrule" ], - assert: "CSSStyleSheet initial property values are correct" }); + }, "CSSStyleSheet_property_values"); + // type, disabled, ownerNode, parentStyleSheet, href, title, and media properties exist on StyleSheet + // type, ownerNode, parentStyleSheet, href, and title properties are read only test(function() { assert_idl_attribute(styleSheet, "type"); assert_idl_attribute(styleSheet, "disabled"); @@ -84,10 +85,9 @@ assert_readonly(styleSheet, "parentStyleSheet"); assert_readonly(styleSheet, "href"); assert_readonly(styleSheet, "title"); - }, "StyleSheet_properties", - { assert: [ "type, disabled, ownerNode, parentStyleSheet, href, title, and media properties exist on StyleSheet", - "type, ownerNode, parentStyleSheet, href, and title properties are read only" ] }); + }, "StyleSheet_properties"); + // StyleSheet initial property values are correct test(function() { assert_equals(styleSheet.type, "text/css"); assert_equals(styleSheet.disabled, false); @@ -106,8 +106,7 @@ assert_equals(styleSheet.title, "internal style sheet"); assert_equals(styleSheet.media.item(0), "all"); - }, "StyleSheet_property_values", - { assert: "StyleSheet initial property values are correct" }); + }, "StyleSheet_property_values"); </script> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-002.html b/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-002.html index 51b0eb3..e86a9a1 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-002.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/style-sheet-interfaces-002.html
@@ -19,24 +19,22 @@ <div id="log"></div> <script type="text/javascript"> var sheet = document.getElementById("styleElement").sheet; + // Initial rule list is of size 1 + // Can add a rule at first index test(function() { assert_equals(sheet.cssRules.length, 1); sheet.insertRule("p { color: green; }", 0); assert_equals(sheet.cssRules.length, 2); assert_equals(sheet.cssRules.item(0).cssText, "p { color: green; }"); - }, "add_rule", { - assert: [ "Initial rule list is of size 1", - "Can add a rule at first index" ] - }); + }, "add_rule"); + // Can delete rules until rule list is empty test(function() { sheet.deleteRule(0); assert_equals(sheet.cssRules.length, 1); sheet.deleteRule(0); assert_equals(sheet.cssRules.length, 0); - }, "delete_rule", { - assert: "Can delete rules until rule list is empty" - }); + }, "delete_rule"); </script> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt b/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt new file mode 100644 index 0000000..bbbc413e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub-expected.txt
@@ -0,0 +1,13 @@ +This is a testharness.js-based test. +PASS Origin-clean check in cross-origin CSSOM Stylesheets +PASS Origin-clean check in cross-origin CSSOM Stylesheets (redirect from same-origin to cross-origin) +FAIL Origin-clean check in cross-origin CSSOM Stylesheets (redirect from cross-origin to same-origin) assert_throws: stylesheet.cssRules should throw SecurityError. function "function () { + sheet.cssRules; + }" did not throw +FAIL Origin-clean check in loading error CSSOM Stylesheets assert_throws: stylesheet.cssRules should throw SecurityError. function "function () { + sheet.cssRules; + }" did not throw +PASS Origin-clean check in same-origin CSSOM Stylesheets +PASS Origin-clean check in data:css CSSOM Stylesheets +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub.html b/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub.html index ccfbf7ce..ef71467 100644 --- a/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub.html +++ b/third_party/blink/web_tests/external/wpt/css/cssom/stylesheet-same-origin.sub.html
@@ -7,34 +7,25 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> - <link id="crossorigin" href="http://www1.{{host}}:{{ports[http][1]}}/stylesheet-same-origin.css" rel="stylesheet"> + <link id="crossorigin" href="http://www1.{{host}}:{{ports[http][1]}}/css/cssom/stylesheet-same-origin.css" rel="stylesheet"> <link id="sameorigin" href="stylesheet-same-origin.css" rel="stylesheet"> <link id="sameorigindata" href="data:text/css,.green-text{color:rgb(0, 255, 0)}" rel="stylesheet"> + <link id="redirect-sameorigin-to-crossorigin" + href="/common/redirect.py?location=http://www1.{{host}}:{{ports[http][1]}}/css/cssom/stylesheet-same-origin.css" + rel="stylesheet"> + <link id="redirect-crossorigin-to-sameorigin" + href="http://www1.{{host}}:{{ports[http][1]}}/common/redirect.py?location=http://{{host}}:{{ports[http][0]}}/css/cssom/stylesheet-same-origin.css" + rel="stylesheet"> + <link id="loaderror" href="support/malformed-http-response.asis" rel="stylesheet"> <script> var crossorigin = document.getElementById("crossorigin").sheet; + var redirectSameOriginToCrossOrigin = document.getElementById("redirect-sameorigin-to-crossorigin").sheet; + var redirectCrossOriginToSameOrigin = document.getElementById("redirect-crossorigin-to-sameorigin").sheet; + var loadError = document.getElementById("loaderror").sheet; var sameorigin = document.getElementById("sameorigin").sheet; var sameorigindata = document.getElementById("sameorigindata").sheet; - test(function() { - assert_throws("SecurityError", - function () { - crossorigin.cssRules; - }, - "Cross origin stylesheet.cssRules should throw SecurityError."); - assert_throws("SecurityError", - function () { - crossorigin.insertRule("#test { margin: 10px; }", 1); - }, - "Cross origin stylesheet.insertRule should throw SecurityError."); - - assert_throws("SecurityError", - function () { - crossorigin.deleteRule(0); - }, - "Cross origin stylesheet.deleteRule should throw SecurityError."); - }, "Origin-clean check in cross-origin CSSOM Stylesheets"); - function doOriginCleanCheck(sheet, name) { assert_equals(sheet.cssRules.length, 1, name + " stylesheet.cssRules should be accessible."); sheet.insertRule("#test { margin: 10px; }", 1); @@ -43,6 +34,41 @@ assert_equals(sheet.cssRules.length, 1, name + " stylesheet.deleteRule should be accessible."); } + function doOriginDirtyCheck(sheet) { + assert_throws("SecurityError", + function () { + sheet.cssRules; + }, + 'stylesheet.cssRules should throw SecurityError.'); + assert_throws("SecurityError", + function () { + sheet.insertRule("#test { margin: 10px; }", 1); + }, + 'stylesheet.insertRule should throw SecurityError.'); + + assert_throws("SecurityError", + function () { + sheet.deleteRule(0); + }, + 'stylesheet.deleteRule should throw SecurityError.'); + } + + test(function() { + doOriginDirtyCheck(crossorigin); + }, "Origin-clean check in cross-origin CSSOM Stylesheets"); + + test(function() { + doOriginDirtyCheck(redirectSameOriginToCrossOrigin); + }, "Origin-clean check in cross-origin CSSOM Stylesheets (redirect from same-origin to cross-origin)"); + + test(function() { + doOriginDirtyCheck(redirectCrossOriginToSameOrigin); + }, "Origin-clean check in cross-origin CSSOM Stylesheets (redirect from cross-origin to same-origin)"); + + test(function() { + doOriginDirtyCheck(loadError); + }, "Origin-clean check in loading error CSSOM Stylesheets"); + test(function() { doOriginCleanCheck(sameorigin, "Same-origin"); }, "Origin-clean check in same-origin CSSOM Stylesheets");
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom/support/malformed-http-response.asis b/third_party/blink/web_tests/external/wpt/css/cssom/support/malformed-http-response.asis new file mode 100644 index 0000000..bc3c68d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/cssom/support/malformed-http-response.asis
@@ -0,0 +1 @@ +HAHAHA THIS IS NOT HTTP AND THE BROWSER SHOULD CONSIDER IT A NETWORK ERROR
diff --git a/third_party/blink/web_tests/external/wpt/css/mediaqueries/test_media_queries.html b/third_party/blink/web_tests/external/wpt/css/mediaqueries/test_media_queries.html index a239efd..250f952 100644 --- a/third_party/blink/web_tests/external/wpt/css/mediaqueries/test_media_queries.html +++ b/third_party/blink/web_tests/external/wpt/css/mediaqueries/test_media_queries.html
@@ -33,13 +33,13 @@ function should_apply(q) { test(function() { assert_true(query_applies(q)); - }, "subtest_" + ++testNum, {assert: q + " should apply"}); + }, "subtest_" + ++testNum); } function should_not_apply(q) { test(function() { assert_false(query_applies(q)); - }, "subtest_" + ++testNum, {assert: q + " should not apply"}); + }, "subtest_" + ++testNum); } /* @@ -68,13 +68,13 @@ function query_should_be_parseable(q) { test(function() { assert_true(query_is_parseable(q)) - }, "subtest_" + ++testNum, {assert: "query " + q + " should be parseable"}); + }, "subtest_" + ++testNum); } function query_should_not_be_parseable(q) { test(function() { assert_false(query_is_parseable(q)) - }, "subtest_" + ++testNum, {assert: "query " + q + " should not be parseable"}); + }, "subtest_" + ++testNum); } /* @@ -88,13 +88,13 @@ function expression_should_be_parseable(e) { test(function() { assert_true(expression_is_parseable(e)); - }, "subtest_" + ++testNum, {assert: "expression " + e + " should be parseable"}); + }, "subtest_" + ++testNum); } function expression_should_not_be_parseable(e) { test(function() { assert_false(expression_is_parseable(e)); - }, "subtest_" + ++testNum, {assert: "expression " + e + " should not be parseable"}); + }, "subtest_" + ++testNum); } // The no-type syntax doesn't mix with the not and only keywords.
diff --git a/third_party/blink/web_tests/external/wpt/fetch/images/canvas-remote-read-remote-image-redirect.html b/third_party/blink/web_tests/external/wpt/fetch/images/canvas-remote-read-remote-image-redirect.html new file mode 100644 index 0000000..bfcb753 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/fetch/images/canvas-remote-read-remote-image-redirect.html
@@ -0,0 +1,27 @@ +<!doctype html> +<meta charset=utf-8> +<title>Load a no-cors image from a same-origin URL that redirects to a cross-origin URL that redirects to the initial origin</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/common/get-host-info.sub.js"></script> +<script> +var image = new Image(); +image.onload = function() { + const canvas = document.createElement("canvas"); + canvas.width = 100; + canvas.height = 100; + + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, 100, 100); + + assert_throws("SecurityError", () => { + context.getImageData(0, 0, 100, 100); + }); + done(); +} + +const info = get_host_info(); +const finalURL = get_host_info().HTTP_ORIGIN + "/images/apng.png"; +const intermediateURL = get_host_info().HTTP_REMOTE_ORIGIN + "/fetch/api/resources/redirect.py?location=" + finalURL; +image.src = "/fetch/api/resources/redirect.py?location=" + encodeURIComponent(intermediateURL); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/hr-time/monotonic-clock.any.js b/third_party/blink/web_tests/external/wpt/hr-time/monotonic-clock.any.js index f7f2545..c53b04d 100644 --- a/third_party/blink/web_tests/external/wpt/hr-time/monotonic-clock.any.js +++ b/third_party/blink/web_tests/external/wpt/hr-time/monotonic-clock.any.js
@@ -1,14 +1,13 @@ +// The time values returned when calling the now method MUST be monotonically increasing and not subject to system clock adjustments or system clock skew. test(function() { assert_true(self.performance.now() > 0, "self.performance.now() returns positive numbers"); -}, "self.performance.now() returns a positive number", {assert: "The time values returned when calling the now method MUST be monotonically increasing and not subject to system clock adjustments or system clock skew."}); +}, "self.performance.now() returns a positive number"); +// The difference between any two chronologically recorded time values returned from the now method MUST never be negative. test(function() { var now1 = self.performance.now(); var now2 = self.performance.now(); assert_true((now2-now1) >= 0, "self.performance.now() difference is not negative"); }, - "self.performance.now() difference is not negative", - { - assert: "The difference between any two chronologically recorded time values returned from the now method MUST never be negative." - } + "self.performance.now() difference is not negative" );
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-2-expected.txt b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-2-expected.txt deleted file mode 100644 index cc68c18..0000000 --- a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-2-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -This is a testharness.js-based test. -FAIL Invalid percent-encoded UTF-8 byte should decode as U+FFFD assert_greater_than: #%C2 expected a number greater than 1000 but got 0 -FAIL Percent-encoded UTF-8 BOM followed by invalid UTF-8 byte should decode as U+FEFF U+FFFD assert_greater_than: #%EF%BB%BF%C2 expected a number greater than 1000 but got 0 -PASS Percent-encoded UTF-8 byte sequence for U+FFFD should decode as U+FFFD -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-expected.txt b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-expected.txt deleted file mode 100644 index 4d8f637..0000000 --- a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/fragment-and-encoding-expected.txt +++ /dev/null
@@ -1,7 +0,0 @@ -This is a testharness.js-based test. -PASS U+00FF should find U+00FF -PASS Percent-encoded UTF-8 BOM should find U+FEFF as BOM is not stripped when decoding -FAIL %FF should not find U+00FF as decoding it gives U+FFFD assert_equals: #%FF expected 0 but got 9416 -PASS Valid UTF-8 + invalid UTF-8 should not be matched to the utf8-decoded former + the isomorphic-decoded latter -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-img-element/available-images-onload.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-img-element/available-images-onload.html new file mode 100644 index 0000000..5fc5cb8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-img-element/available-images-onload.html
@@ -0,0 +1,33 @@ +<!doctype html> +<html> +<title>Ensure images from available images list can be drawn to a canvas</title> +<link rel="help" href="https://html.spec.whatwg.org/multipage/#the-list-of-available-images"> +<meta charset="utf-8"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<div id="log"></div> +<script> + async_test(function(t) { + var i = new Image(); + i.onerror = t.unreached_func(); + i.onload = t.step_func(function() { + var i2 = new Image(); + // Potentially start multiple image loading tasks by performing several + // relevant mutations. This could lead to an invalid state later in an + // erroneous implementation. + i2.crossOrigin = true; + // Start an image loading task that is expected to short-circuit since + // the requested image is present in the list of available images. + i2.src = "3.jpg"; + i2.onerror = t.unreached_func(); + // Ensure the loaded image is in a state that is usable by a 2d canvas. + i2.onload = t.step_func_done(function() { + var c = document.createElement('canvas'); + var ctx = c.getContext('2d'); + ctx.drawImage(i2, 0, 0); + }); + }); + // Request an image which should be added to the list of available images. + i.src = "3.jpg"; + }); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits-expected.txt new file mode 100644 index 0000000..a95568a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits-expected.txt
@@ -0,0 +1,14 @@ +This is a testharness.js-based test. +PASS clicking a button with .click() should trigger a submit (form connected) +PASS clicking a button with .click() should not trigger a submit (form disconnected) +PASS clicking a button by dispatching an event should trigger a submit (form connected) +PASS clicking a button by dispatching an event should not trigger a submit (form disconnected) +PASS clicking a button that cancels the event should not trigger a submit +PASS clicking a disabled button (via disabled attribute) should not trigger submit +PASS clicking a disabled button (via ancestor fieldset) should not trigger submit +PASS clicking a button inside a disabled fieldset's legend *should* trigger submit +PASS clicking the child of a button with .click() should trigger a submit +PASS clicking the child of a button by dispatching a bubbling event should trigger a submit +FAIL clicking the child of a button by dispatching a non-bubbling event should not trigger submit assert_unreached: Form should not be submitted Reached unreachable code +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits.html index e6f02d3..f09d0608 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-click-submits.html
@@ -146,4 +146,65 @@ }, "clicking a button inside a disabled fieldset's legend *should* trigger submit"); +async_test(t => { + + const form = document.createElement("form"); + const button = document.createElement("button"); + const span = document.createElement("span"); + button.appendChild(span); + form.appendChild(button); + document.body.appendChild(form); + + form.addEventListener("submit", t.step_func_done(ev => { + ev.preventDefault(); + assert_equals(ev.target, form); + })); + + span.click(); + +}, "clicking the child of a button with .click() should trigger a submit"); + +async_test(t => { + + const form = document.createElement("form"); + const button = document.createElement("button"); + const span = document.createElement("span"); + button.appendChild(span); + form.appendChild(button); + document.body.appendChild(form); + + form.addEventListener("submit", t.step_func_done(ev => { + ev.preventDefault(); + assert_equals(ev.target, form); + })); + + const e = new MouseEvent("click", { bubbles: true }); + span.dispatchEvent(e); + +}, "clicking the child of a button by dispatching a bubbling event should trigger a submit"); + +async_test(t => { + + const form = document.createElement("form"); + const button = document.createElement("button"); + const span = document.createElement("span"); + button.appendChild(span); + form.appendChild(button); + document.body.appendChild(form); + + form.addEventListener("submit", t.step_func_done(ev => { + ev.preventDefault(); + assert_unreached("Form should not be submitted"); + })); + + span.addEventListener("click", t.step_func(ev => { + ev.preventDefault(); + t.step_timeout(() => t.done(), 500); + })); + + const e = new MouseEvent("click", { bubbles: false }); + span.dispatchEvent(e); + +}, "clicking the child of a button by dispatching a non-bubbling event should not trigger submit"); + </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/support/target_blank_iplicit_noopener.html b/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/support/target_blank_iplicit_noopener.html new file mode 100644 index 0000000..bf6a1ae5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/support/target_blank_iplicit_noopener.html
@@ -0,0 +1,6 @@ +<!DOCTYPE html> +<script> + let bc = new BroadcastChannel(window.location.search.substring(1)); + bc.postMessage({ hasOpener: opener !== null }); + window.close(); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt new file mode 100644 index 0000000..f6a44d6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt
@@ -0,0 +1,13 @@ +This is a testharness.js-based test. +PASS Anchor element with target=_blank with rel=noopener +PASS Anchor element with target=_blank with rel=opener +FAIL Anchor element with target=_blank with implicit rel=noopener assert_equals: expected false but got true +PASS Anchor element with target=_blank with rel=opener+noopener +PASS Anchor element with target=_blank with rel=noopener+opener +PASS Area element with target=_blank with rel=noopener +PASS Area element with target=_blank with rel=opener +FAIL Area element with target=_blank with implicit rel=noopener assert_equals: expected false but got true +PASS Area element with target=_blank with rel=opener+noopener +PASS Area element with target=_blank with rel=noopener+opener +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html b/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html new file mode 100644 index 0000000..39903dc --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative.html
@@ -0,0 +1,60 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset=utf-8> + <title>Test behavior of rel="noopener" links</title> + <script src=/resources/testharness.js></script> + <script src=/resources/testharnessreport.js></script> +</head> +<body> + <a href="support/target_blank_iplicit_noopener.html?a1" id="a1" rel="noopener" target="_blank">Click me</a> + <a href="support/target_blank_iplicit_noopener.html?a2" id="a2" rel="opener" target="_blank">Click me</a> + <a href="support/target_blank_iplicit_noopener.html?a3" id="a3" target="_blank">Click me</a> + <a href="support/target_blank_iplicit_noopener.html?a4" id="a4" rel="opener noopener" target="_blank">Click me</a> + <a href="support/target_blank_iplicit_noopener.html?a5" id="a5" rel="noopener opener" target="_blank">Click me</a> + + <img src="/images/threecolors.png" /> + <area shape="rect" coords="0,0,99,50" href="support/target_blank_iplicit_noopener.html?area1" id="area1" rel="noopener" target="_blank" /> + </img> + <img src="/images/threecolors.png" /> + <area shape="rect" coords="0,0,99,50" href="support/target_blank_iplicit_noopener.html?area2" id="area2" rel="opener" target="_blank" /> + </img> + <img src="/images/threecolors.png" /> + <area shape="rect" coords="0,0,99,50" href="support/target_blank_iplicit_noopener.html?area3" id="area3" target="_blank" /> + </img> + <img src="/images/threecolors.png" /> + <area shape="rect" coords="0,0,99,50" href="support/target_blank_iplicit_noopener.html?area4" id="area4" rel="opener noopener" target="_blank" /> + </img> + <img src="/images/threecolors.png" /> + <area shape="rect" coords="0,0,99,50" href="support/target_blank_iplicit_noopener.html?area5" id="area5" rel="noopener opener" target="_blank" /> + </img> + + <script> + + let tests = [ + { id: "a1", hasOpener: false, name: "Anchor element with target=_blank with rel=noopener" }, + { id: "a2", hasOpener: true, name: "Anchor element with target=_blank with rel=opener" }, + { id: "a3", hasOpener: false, name: "Anchor element with target=_blank with implicit rel=noopener" }, + { id: "a4", hasOpener: false, name: "Anchor element with target=_blank with rel=opener+noopener" }, + { id: "a5", hasOpener: false, name: "Anchor element with target=_blank with rel=noopener+opener" }, + { id: "area1", hasOpener: false, name: "Area element with target=_blank with rel=noopener" }, + { id: "area2", hasOpener: true, name: "Area element with target=_blank with rel=opener" }, + { id: "area3", hasOpener: false, name: "Area element with target=_blank with implicit rel=noopener" }, + { id: "area4", hasOpener: false, name: "Area element with target=_blank with rel=opener+noopener" }, + { id: "area5", hasOpener: false, name: "Area element with target=_blank with rel=noopener+opener" }, + ]; + + tests.forEach(data => { + async_test( + test => { + let bc = new BroadcastChannel(data.id); + bc.addEventListener("message", test.step_func_done(e => { + assert_equals(e.data.hasOpener, data.hasOpener); + }), {once: true}); + + document.getElementById(data.id).click(); + }, data.name); + }); + </script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/muted-errors.sub.html b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/muted-errors.sub.html index a42179d..1b255fa 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/muted-errors.sub.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/scripting-1/the-script-element/muted-errors.sub.html
@@ -4,7 +4,7 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> -// https://html.spec.whatwg.org/#report-the-error +// https://html.spec.whatwg.org/multipage/webappapis.html#report-the-error // If script's muted errors is true, then set message to "Script error.", // urlString to the empty string, line and col to 0, and errorValue to null. setup({allow_uncaught_exception: true}); @@ -43,6 +43,16 @@ script.onload = test3.step_func_done(() => check(true)); document.body.appendChild(script); } + + var test4 = async_test("Errors for same-origin scripts redirected to a " + + "cross-origin url and redirected back to " + + "same-origin should be muted"); + var check4 = test4.step_func_done(() => check(true)); + + var test5 = async_test("Errors for cross-origin scripts redirected to a " + + "same-origin url should be muted"); + var check5 = test5.step_func_done(() => check(true)); + function unreachable() { log.push("unexpected"); } </script> <script src="cacheable-script-throw.py" onerror="test1.unreached_func()()" onload="check1()"></script> @@ -50,3 +60,10 @@ onerror="test2.unreached_func()()" onload="check2()"></script> <iframe src="//{{domains[www2]}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/muted-errors-iframe.html" onerror="test3.unreached_func()()" onload="step3()"></iframe> +<script src="/fetch/api/resources/redirect.py?location= +//{{domains[www2]}}:{{ports[http][0]}}/fetch/api/resources/redirect.py?location= +//{{host}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/cacheable-script-throw.py?same-cross-same" +onerror="test4.unreached_func()()" onload="check4()"></script> +<script src="//{{domains[www2]}}:{{ports[http][0]}}/fetch/api/resources/redirect.py?location= +//{{host}}:{{ports[http][0]}}/html/semantics/scripting-1/the-script-element/cacheable-script-throw.py?cross-same" +onerror="test5.unreached_func()()" onload="check5()"></script>
diff --git a/third_party/blink/web_tests/external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/protocol.https.html b/third_party/blink/web_tests/external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/protocol.https.html index d090aad..006827f1 100644 --- a/third_party/blink/web_tests/external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/protocol.https.html +++ b/third_party/blink/web_tests/external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/protocol.https.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <meta charset='utf-8'> -<title>registerProtocolHandler()</title> +<title>protocol handlers</title> <script src='/resources/testharness.js'></script> <script src='/resources/testharnessreport.js'></script> @@ -11,141 +11,80 @@ registration requests on a page, you might need to disable or significantly increase that limit for the tests below to run.</p> -<div id='log'></div> - <script type='text/javascript'> - -test(function () { +test(() => { assert_idl_attribute(navigator, 'registerProtocolHandler'); }, 'the registerProtocolHandler method should exist on the navigator object'); -test(function () { - navigator.registerProtocolHandler('tel', location.href + '/%s', 'foo'); -}, 'a handler with valid arguments should work'); - +test(() => { + assert_idl_attribute(navigator, 'unregisterProtocolHandler'); +}, 'the unregisterProtocolHandler method should exist on the navigator object'); /* URL argument */ -test(function () { - navigator.registerProtocolHandler('tel', '%s', 'foo'); -}, 'a relative URL should work'); +const vaild_urls = [ + '%s', + location.href + '/%s', + location.href + '#%s', + location.href + '?foo=%s', + location.href + '?foo=%s&bar', + location.href + '/%s/bar/baz/', + location.href + '/%s/bar/baz/?foo=1337&bar#baz', + location.href + '/%s/foo/%s/', +]; +for (const url of vaild_urls) { + test(() => { + navigator.registerProtocolHandler('tel', url, 'foo'); + }, 'registerProtocolHandler: Valid URL "' + url + '" should work.'); -test(function () { - navigator.registerProtocolHandler('tel', location.href + '#%s', 'foo'); -}, 'a URL with a fragment identifier should work'); + test(() => { + navigator.unregisterProtocolHandler('tel', url); + }, 'unregisterProtocolHandler: Valid URL "' + url + '" should work.'); +} -test(function () { - navigator.registerProtocolHandler('tel', location.href + '?foo=%s', 'foo'); -}, 'a URL with a query string should work'); +const invalid_urls1 = [ + '', + '%S', + location.href + '', + location.href + '/%', + location.href + '/%a', + 'http://example.com', + 'http://[v8.:::]//url=%s', +]; -test(function () { - navigator.registerProtocolHandler('tel', location.href + '?foo=%s&bar', 'foo'); -}, 'a URL with a multi-argument query string should work'); +for (const url of invalid_urls1) { + test(() => { + assert_throws('SYNTAX_ERR', () => { navigator.registerProtocolHandler('mailto', url, 'foo'); }); + }, 'registerProtocolHandler: Invalid URL "' + url + '" should throw SYNTAX_ERR.'); -test(function () { - navigator.registerProtocolHandler('tel', location.href + '/%s/bar/baz/', 'foo'); -}, 'a URL with the passed string as a directory name should work'); + test(() => { + assert_throws('SYNTAX_ERR', () => { navigator.unregisterProtocolHandler('mailto', url); }); + }, 'unregisterProtocolHandler: Invalid URL "' + url + '" should throw SYNTAX_ERR.'); +} -test(function () { - navigator.registerProtocolHandler('tel', location.href + '/%s/bar/baz/?foo=1337&bar#baz', 'foo'); -}, 'a URL with the passed string as a directory name followed by a query string and fragment identifier should work'); +const invaild_urls2 = [ + 'http://%s.com', + 'http://%s.example.com', + 'http://example.com/%s', + 'https://example.com/%s', + 'http://foobar.example.com/%s', + 'mailto:%s@example.com', + 'mailto:%s', +]; +for (const url of invaild_urls2) { + test(() => { + assert_throws('SECURITY_ERR', () => { navigator.registerProtocolHandler('mailto', url, 'foo'); }); + }, 'registerProtocolHandler: Invalid URL "' + url + '" should throw SECURITY_ERR.'); -test(function () { - navigator.registerProtocolHandler('tel', location.href + '/%s/foo/%s/', 'foo'); -}, 'a URL with the passed string included twice should work'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto', '', 'foo') } ); -}, 'an empty url argument should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('mailto', 'http://%s.com', 'foo') } ); -}, '%s instead of domain name should throw SECURITY_ERR'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('mailto', 'http://%s.example.com', 'foo') } ); -}, '%s instead of subdomain name should throw SECURITY_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto', location.href + '', 'foo') } ); -}, 'a url argument without %s should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto', 'http://example.com', 'foo') } ); -}, 'a url argument pointing to a different domain name, without %s should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto', location.href + '/%', 'foo') } ); -}, 'a url argument without %s (but with %) should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto', location.href + '/%a', 'foo') } ); -}, 'a url argument without %s (but with %a) should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('mailto', 'http://example.com/%s', 'foo') } ); -}, 'a url argument pointing to a different domain name should throw SECURITY_ERR'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('mailto', 'https://example.com/%s', 'foo') } ); -}, 'a url argument pointing to a different domain name should throw SECURITY_ERR (2)'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('mailto', 'http://foobar.example.com/%s', 'foo') } ); -}, 'a url argument pointing to a different domain name should throw SECURITY_ERR (3)'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('mailto', 'mailto:%s@example.com', 'foo') } ); -}, 'looping handlers should throw SECURITY_ERR'); - -test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler('sms', 'tel:%s', 'foo') } ); -}, 'a url argument pointing to a non-http[s] scheme should throw SECURITY_ERR due to not being of the same origin'); + test(() => { + assert_throws('SECURITY_ERR', () => { navigator.unregisterProtocolHandler('mailto', url); }); + }, 'unregisterProtocolHandler: Invalid URL "' + url + '" should throw SECURITY_ERR.'); +} /* Protocol argument */ -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('unrecognized', location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing an unrecognized scheme should throw SECURITY_ERR'); /* This is a whitelist, not a blacklist. */ - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto:', location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing : should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto://', location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing :// should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('http://', location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing http:// should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto' + String.fromCharCode(0), location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing a null character should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailtoo' + String.fromCharCode(8), location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing a backspace character should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mailto' + String.fromCharCode(10), location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing a LF character should throw SYNTAX_ERR'); - -test(function () { - assert_throws('SYNTAX_ERR', function () { navigator.registerProtocolHandler('mаilto', location.href + '/%a', 'foo') } ); -}, 'a protocol argument containing non-alphanumeric characters (like a cyrillic “а”) should throw SYNTAX_ERR'); - -test(function () { - navigator.registerProtocolHandler('TEL', location.href + '/%s', 'foo'); -}, 'a protocol argument of “TEL” should be equivalent to “tel”'); - -test(function () { - navigator.registerProtocolHandler('teL', location.href + '/%s', 'foo'); -}, 'a protocol argument of “teL” should be equivalent to “tel”'); - /* Overriding any of the following protocols must never be allowed. That would * break the browser. */ -var blacklist = new Array( +const blacklist = [ 'about', 'attachment', 'blob', @@ -170,45 +109,76 @@ 'view-source', 'ws', 'wss', - 'wyciwyg'); + 'wyciwyg', + /*other invalid schemes*/ + 'unrecognized', + 'mаilto', /*a cyrillic "а"*/ + 'mailto:', + 'mailto://', + 'mailto' + String.fromCharCode(0), + 'mailtoo' + String.fromCharCode(8), + 'mailto' + String.fromCharCode(10), + 'http://', + 'ssh:/', + 'magnet:+', + 'tel:sip', + 'web+', +]; +for (const scheme of blacklist) { + test(() => { + assert_throws('SECURITY_ERR', () => { navigator.registerProtocolHandler(scheme, location.href + '/%s', 'foo'); }); + }, 'registerProtocolHandler: Attempting to override the "' + scheme + '" protocol should throw SECURITY_ERR.'); -for ( var bi=0, bl=blacklist.length; bi<bl; ++bi ){ - - test(function () { - assert_throws('SECURITY_ERR', function () { navigator.registerProtocolHandler(blacklist[bi], location.href + '/%s', 'foo') } ); - }, 'attempting to override the ' + blacklist[bi] + ' protocol should throw SECURITY_ERR'); - + test(() => { + assert_throws('SECURITY_ERR', () => { navigator.unregisterProtocolHandler(scheme, location.href + '/%s', 'foo'); }); + }, 'unregisterProtocolHandler: Attempting to override the "' + scheme + '" protocol should throw SECURITY_ERR.'); } /* The following protocols must be possible to override. * We're just testing that the call goes through here. Whether or not they * actually work as handlers is covered by the interactive tests. */ -var whitelist = new Array( + +const safelist = [ + /* safelisted schemes listed in + * https://html.spec.whatwg.org/multipage/system-state.html#safelisted-scheme */ + 'bitcoin', 'geo', 'im', 'irc', 'ircs', + 'magnet', 'mailto', 'mms', 'news', 'nntp', + 'openpgp4fpr', + 'sip', 'sms', 'smsto', + 'ssh', 'tel', 'urn', 'webcal', 'wtai', - 'xmpp'); + 'xmpp', + /*other vaild schemes*/ + 'BitcoIn', + 'Irc', + 'MagneT', + 'SmsTo', + 'TEL', + 'teL', + 'WebCAL', + 'WTAI', + 'web+myprotocol', +]; +for (const scheme of safelist) { + test(() => { + navigator.registerProtocolHandler(scheme, location.href + '/%s', "foo"); + }, 'registerProtocolHandler: overriding the "' + scheme + '" protocol should work'); -for ( var wi=0, wl=whitelist.length; wi<wl; ++wi ){ - - test(function () { - navigator.registerProtocolHandler(whitelist[wi], location.href + '/%s', 'foo'); - assert_true(true); - }, 'overriding the ' + whitelist[wi] + ' protocol should work'); - + test(() => { + navigator.unregisterProtocolHandler(scheme, location.href + '/%s'); + }, 'unregisterProtocolHandler: overriding the "' + scheme + '" protocol should work'); } </script> - -</body> -</html>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementPosition.html.ini b/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementPosition.html.ini index 649c1709..750dd05 100644 --- a/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementPosition.html.ini +++ b/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementPosition.html.ini
@@ -1,3 +1,7 @@ [elementPosition.html] expected: - if product == "safari": ERROR + if product == "chrome": ERROR + + [TestDriver actions: element position] + expected: + if product == "safari": FAIL
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementTiming.html.ini b/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementTiming.html.ini index a1e9ea8..7a6cf82 100644 --- a/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementTiming.html.ini +++ b/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/elementTiming.html.ini
@@ -1,3 +1,3 @@ [elementTiming.html] expected: - if product == "chrome" or product == "safari": ERROR + if product == "chrome": ERROR
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload.py b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload.py new file mode 100644 index 0000000..3263367 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload.py
@@ -0,0 +1,2 @@ +def main(request, response): + return "PASS" if request.POST["file_input"].file.read() == b"File to upload\n" else "FAIL"
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload.sub.html b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload.sub.html new file mode 100644 index 0000000..29c42b4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload.sub.html
@@ -0,0 +1,26 @@ +<!doctype html> +<meta charset=utf8> +<title>File upload using testdriver</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/resources/testdriver.js"></script> +<script src="/resources/testdriver-vendor.js"></script> +<form id="form"> + <input id="file_input" name="file_input" type="file"> +</form> +<script> +let form = document.getElementById("form"); +let input = document.getElementById("file_input"); +test_driver + .send_keys(input, "{{fs_path(file_upload_data.txt)}}") + .then(() => + fetch("file_upload.py", + {method: "POST", + body: new FormData(form)})) + .then(response => response.text()) + .then(data => { + assert_equals(data, "PASS"); + done(); + }) + .catch(() => assert_unreached("File upload failed")); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload_data.txt b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload_data.txt new file mode 100644 index 0000000..097d2a3a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/infrastructure/testdriver/file_upload_data.txt
@@ -0,0 +1 @@ +File to upload
diff --git a/third_party/blink/web_tests/external/wpt/interfaces/webxr.idl b/third_party/blink/web_tests/external/wpt/interfaces/webxr.idl index 7f7b43c..27ee274 100644 --- a/third_party/blink/web_tests/external/wpt/interfaces/webxr.idl +++ b/third_party/blink/web_tests/external/wpt/interfaces/webxr.idl
@@ -17,17 +17,6 @@ [SameObject] readonly attribute XR xr; }; -enum XRSessionMode { - "inline", - "immersive-vr", - "immersive-ar" -}; - -dictionary XRSessionCreationOptions { - XRSessionMode mode = "inline"; - XRPresentationContext outputContext; -}; - enum XREnvironmentBlendMode { "opaque", "additive", @@ -64,6 +53,17 @@ attribute EventHandler onselectend; }; +enum XRSessionMode { + "inline", + "immersive-vr", + "immersive-ar" +}; + +dictionary XRSessionCreationOptions { + XRSessionMode mode = "inline"; + XRPresentationContext outputContext; +}; + callback XRFrameRequestCallback = void (DOMHighResTimeStamp time, XRFrame frame); [SecureContext, Exposed=Window] interface XRFrame {
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/resources/webperftestharness.js b/third_party/blink/web_tests/external/wpt/navigation-timing/resources/webperftestharness.js index afdfa2a7..3efb527 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/resources/webperftestharness.js +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/resources/webperftestharness.js
@@ -6,6 +6,9 @@ [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license [3] http://www.w3.org/2004/10/27-testcases + +author: W3C http://www.w3.org/ +help: http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute */ // @@ -39,12 +42,12 @@ { if (skip_root === undefined) { var msg = 'window.performance is defined'; - wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg); } if (child_name !== undefined) { var msg2 = 'window.performance.' + child_name + ' is defined'; - wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2); } }
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/test_navigation_redirectCount_none.html b/third_party/blink/web_tests/external/wpt/navigation-timing/test_navigation_redirectCount_none.html index eaaef4b..da94d24c 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/test_navigation_redirectCount_none.html +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/test_navigation_redirectCount_none.html
@@ -5,6 +5,7 @@ <title>window.performance.navigation.redirectCount on a non-redirected navigation</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-timing-interface"/> + <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/performance-timeline-utils.js"></script> @@ -23,7 +24,7 @@ { test_equals(performanceNamespace.timing.redirectStart, 0, 'timing.redirectStart on an non-redirected navigation'); test_equals(performanceNamespace.timing.redirectEnd, 0, 'timing.redirectEnd on an non-redirected navigation'); - test_equals(performanceNamespace.navigation.redirectCount, 0, 'navigation.redirectCount on an non-redirected navigation',{help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + test_equals(performanceNamespace.navigation.redirectCount, 0, 'navigation.redirectCount on an non-redirected navigation'); } </script> </body>
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/test_no_previous_document.html b/third_party/blink/web_tests/external/wpt/navigation-timing/test_no_previous_document.html index 0b9eb4b..0bce1652 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/test_no_previous_document.html +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/test_no_previous_document.html
@@ -5,6 +5,7 @@ <title>window.performance.timing attributes on an initial navigation</title> <link rel="author" title="Google" href="http://www.google.com/" /> <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-timing-interface"/> + <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/performance-timeline-utils.js"></script> @@ -21,7 +22,7 @@ if (performanceNamespace) { test_true(frame.contentWindow.performance.navigation.type == performanceNamespace.navigation.TYPE_NAVIGATE, - 'timing.navigation.type is TYPE_NAVIGATE',{help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + 'timing.navigation.type is TYPE_NAVIGATE'); test_equals(frame.contentWindow.performance.timing.unloadEventStart, 0, 'timing.unloadEventStart == 0 on navigation with no previous document'); test_equals(frame.contentWindow.performance.timing.unloadEventEnd, 0, 'timing.unloadEventEnd == 0 navigation with no previous document');
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_attributes_order.html b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_attributes_order.html index 03c2619..5e885ea 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_attributes_order.html +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_attributes_order.html
@@ -5,6 +5,7 @@ <title>window.performance.timing attribute ordering on a simple navigation</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-timing-interface"/> + <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/performance-timeline-utils.js"></script> @@ -43,7 +44,7 @@ // test_equals(performanceNamespace.navigation.type, performanceNamespace.navigation.TYPE_NAVIGATE, - 'window.performance.navigation.type == TYPE_NAVIGATE',{help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + 'window.performance.navigation.type == TYPE_NAVIGATE'); // navigiation must be non-0 test_timing_greater_than('navigationStart', 0);
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_client_redirect.html b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_client_redirect.html index 3bc3692..bebf39eb9 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_client_redirect.html +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_client_redirect.html
@@ -5,6 +5,7 @@ <title>window.performance.timing.redirect attributes on a client redirect navigation</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-timing-interface"/> + <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/performance-timeline-utils.js"></script> @@ -33,9 +34,9 @@ { redirect_frame.onload = ""; test_true(redirect_frame.contentWindow.performance.navigation.type == performanceNamespace.navigation.TYPE_NAVIGATE, - 'timing.navigation.type is TYPE_NAVIGATE',{help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + 'timing.navigation.type is TYPE_NAVIGATE'); - test_equals(redirect_frame.contentWindow.performance.navigation.redirectCount, 0, 'navigation.redirectCount == 0 on an client redirected navigation',{help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + test_equals(redirect_frame.contentWindow.performance.navigation.redirectCount, 0, 'navigation.redirectCount == 0 on an client redirected navigation'); test_equals(redirect_frame.contentWindow.performance.timing.redirectStart, 0, 'timing.redirectStart == 0 on an client redirected navigation'); test_equals(redirect_frame.contentWindow.performance.timing.redirectEnd, 0, 'timing.redirectEnd == 0 on an client redirected navigation');
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_reload.html b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_reload.html index 0e28a64..a660caf4 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_reload.html +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_reload.html
@@ -5,6 +5,7 @@ <title>window.performance.timing attributes after a reloaded navigation</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-timing-interface"/> + <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/performance-timeline-utils.js"></script> @@ -56,7 +57,7 @@ // ensure the frame reloaded test_equals(reload_frame.contentWindow.performance.navigation.type, performanceNamespace.navigation.TYPE_RELOAD, - "window.performance.navigation.type == TYPE_RELOAD", {help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + "window.performance.navigation.type == TYPE_RELOAD"); // ensure reload timings changed var timing = reload_frame.contentWindow.performance.timing;
diff --git a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_xserver_redirect.html b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_xserver_redirect.html index 93db8699..a39f7c2 100644 --- a/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_xserver_redirect.html +++ b/third_party/blink/web_tests/external/wpt/navigation-timing/test_timing_xserver_redirect.html
@@ -5,6 +5,7 @@ <title>window.performance.timing.redirect attributes on a cross-origin server redirected navigation</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-timing-interface"/> + <link rel="help" href="http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"/> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/performance-timeline-utils.js"></script> @@ -35,8 +36,8 @@ performanceNamespace = document.getElementById("frameContext").contentWindow.performance; test_equals(performanceNamespace.navigation.type, performanceNamespace.navigation.TYPE_NAVIGATE, - 'timing.navigation.type is TYPE_NAVIGATE',{help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); - test_equals(performanceNamespace.navigation.redirectCount, 0, 'navigation.redirectCount == 0 on a cross-origin server redirected navigation', {help:"http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface"}); + 'timing.navigation.type is TYPE_NAVIGATE'); + test_equals(performanceNamespace.navigation.redirectCount, 0, 'navigation.redirectCount == 0 on a cross-origin server redirected navigation'); test_timing_greater_than('navigationStart', 0);
diff --git a/third_party/blink/web_tests/external/wpt/requestidlecallback/basic.html b/third_party/blink/web_tests/external/wpt/requestidlecallback/basic.html index e481a6b..429134ec 100644 --- a/third_party/blink/web_tests/external/wpt/requestidlecallback/basic.html +++ b/third_party/blink/web_tests/external/wpt/requestidlecallback/basic.html
@@ -4,21 +4,25 @@ <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> +// The window.requestIdleCallback function is used to request callbacks during browser-defined idle time. test(function() { assert_equals(typeof window.requestIdleCallback, "function"); -}, "window.requestIdleCallback is defined", {assert: "The window.requestIdleCallback function is used to request callbacks during browser-defined idle time."}); +}, "window.requestIdleCallback is defined"); +// The window.cancelIdleCallback function is used to cancel callbacks scheduled via requestIdleCallback. test(function() { assert_equals(typeof window.cancelIdleCallback, "function"); -}, "window.cancelIdleCallback is defined", {assert: "The window.cancelIdleCallback function is used to cancel callbacks scheduled via requestIdleCallback."}); +}, "window.cancelIdleCallback is defined"); +// The requestIdleCallback method MUST return a long test(function() { assert_equals(typeof window.requestIdleCallback(function() {}), "number"); -}, "window.requestIdleCallback() returns a number", {assert: "The requestIdleCallback method MUST return a long"}); +}, "window.requestIdleCallback() returns a number"); +// The cancelIdleCallback method MUST return void test(function() { assert_equals(typeof window.cancelIdleCallback(1), "undefined"); -}, "window.cancelIdleCallback() returns undefined", {assert: "The cancelIdleCallback method MUST return void"}); +}, "window.cancelIdleCallback() returns undefined"); async_test(function() { // Check whether requestIdleCallback schedules a callback which gets executed
diff --git a/third_party/blink/web_tests/external/wpt/resource-timing/resources/webperftestharness.js b/third_party/blink/web_tests/external/wpt/resource-timing/resources/webperftestharness.js index 98b2954b..203eb0d1 100644 --- a/third_party/blink/web_tests/external/wpt/resource-timing/resources/webperftestharness.js +++ b/third_party/blink/web_tests/external/wpt/resource-timing/resources/webperftestharness.js
@@ -1,4 +1,8 @@ -// +/* +author: W3C http://www.w3.org/ +help: http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute +*/ +// // Helper Functions for NavigationTiming W3C tests // @@ -45,7 +49,8 @@ if (performanceNamespace === undefined || performanceNamespace == null) { // show a single error that window.performance is undefined - test(function() { assert_true(performanceNamespace !== undefined && performanceNamespace != null, "window.performance is defined and not null"); }, "window.performance is defined and not null.", {author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + // The window.performance attribute provides a hosting area for performance related attributes. + test(function() { assert_true(performanceNamespace !== undefined && performanceNamespace != null, "window.performance is defined and not null"); }, "window.performance is defined and not null."); } } @@ -56,12 +61,14 @@ { if (skip_root === undefined) { var msg = 'window.performance is defined'; - wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + // The window.performance attribute provides a hosting area for performance related attributes. + wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg); } if (child_name !== undefined) { var msg2 = 'window.performance.' + child_name + ' is defined'; - wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + // The window.performance attribute provides a hosting area for performance related attributes. + wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2); } }
diff --git a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-certs.sh b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-certs.sh index e1d2ea9..01330e4 100755 --- a/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-certs.sh +++ b/third_party/blink/web_tests/external/wpt/signed-exchange/resources/generate-test-certs.sh
@@ -10,7 +10,7 @@ openssl req -new -sha256 \ -key 127.0.0.1.sxg.key \ -out 127.0.0.1.sxg.csr \ - --subj '/CN=127.0.0.1/O=Test/C=US' + -subj '/CN=127.0.0.1/O=Test/C=US' openssl x509 -req -days 3650 \ -in 127.0.0.1.sxg.csr \
diff --git a/third_party/blink/web_tests/external/wpt/user-timing/resources/webperftestharness.js b/third_party/blink/web_tests/external/wpt/user-timing/resources/webperftestharness.js index 79c218f..4a8e2de 100644 --- a/third_party/blink/web_tests/external/wpt/user-timing/resources/webperftestharness.js +++ b/third_party/blink/web_tests/external/wpt/user-timing/resources/webperftestharness.js
@@ -6,6 +6,9 @@ [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license [3] http://www.w3.org/2004/10/27-testcases + +author: W3C http://www.w3.org/ +help: http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute */ // @@ -55,12 +58,12 @@ { if (skip_root === undefined) { var msg = 'window.performance is defined'; - wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + wp_test(function () { assert_true(performanceNamespace !== undefined, msg); }, msg); } if (child_name !== undefined) { var msg2 = 'window.performance.' + child_name + ' is defined'; - wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2,{author:"W3C http://www.w3.org/",help:"http://www.w3.org/TR/navigation-timing/#sec-window.performance-attribute",assert:"The window.performance attribute provides a hosting area for performance related attributes. "}); + wp_test(function() { assert_true(performanceNamespace[child_name] !== undefined, msg2); }, msg2); } }
diff --git a/third_party/blink/web_tests/fast/css/CSSStyleSheet-constructable.html b/third_party/blink/web_tests/fast/css/CSSStyleSheet-constructable.html index bc47187..aa9546e8 100644 --- a/third_party/blink/web_tests/fast/css/CSSStyleSheet-constructable.html +++ b/third_party/blink/web_tests/fast/css/CSSStyleSheet-constructable.html
@@ -13,6 +13,7 @@ </div> </section> <section id="secondSection"></section> +<section id="thirdSection"></section> <script> 'use strict'; @@ -43,7 +44,7 @@ }, "document.adoptedStyleSheets should initially have length 0."); test(() => { - const sheet = document.createEmptyCSSStyleSheet({title: "Red", disabled: true, media: "screen, print"}); + const sheet = new CSSStyleSheet({title: "Red", disabled: true, media: "screen, print"}); assert_equals(sheet.title, "Red"); assert_equals(sheet.ownerNode, null); assert_equals(sheet.ownerRule, null); @@ -61,7 +62,7 @@ assert_equals(sheet.cssRules.length, 2); assert_equals(sheet.cssRules[0].cssText, redStyleTexts[1]); - const sheet2 = document.createEmptyCSSStyleSheet({}); + const sheet2 = new CSSStyleSheet({}); assert_equals(sheet2.title, "") assert_equals(sheet2.ownerNode, null); assert_equals(sheet2.ownerRule, null); @@ -76,7 +77,7 @@ sheet2.deleteRule(0); assert_equals(sheet2.cssRules.length, 0); -const sheet3 = document.createEmptyCSSStyleSheet(); +const sheet3 = new CSSStyleSheet(); assert_equals(sheet3.title, "") assert_equals(sheet3.ownerNode, null); assert_equals(sheet3.ownerRule, null); @@ -90,10 +91,11 @@ sheet3.deleteRule(0); assert_equals(sheet3.cssRules.length, 0); -}, 'Document.createEmptyCSSStyleSheet produces empty CSSStyleSheet'); +}, 'new CSSStyleSheet produces empty CSSStyleSheet'); promise_test(() => { - const promise_sheet = document.createCSSStyleSheet(redStyleTexts[0], {title: "Red", disabled: true, media: "screen, print"}); + const sheet = new CSSStyleSheet({title: "Red", disabled: true, media: "screen, print"}); + const promise_sheet = sheet.replace(redStyleTexts[0]); return promise_sheet.then(function(sheet) { assert_equals(sheet.title, "Red"); assert_equals(sheet.ownerNode, null); @@ -109,21 +111,31 @@ assert_equals(sheet.cssRules.length, 2); assert_equals(sheet.cssRules[0].cssText, redStyleTexts[1]); }); -}, 'Document.createCSSStyleSheet produces Promise<CSSStyleSheet>'); +}, 'CSSStyleSheet.replace produces Promise<CSSStyleSheet>'); + +function createAllSheetsPromise() { + const greenSheet = new CSSStyleSheet(); + const redSheet = new CSSStyleSheet({media: "screen, print"}); + const blueSheet = new CSSStyleSheet({title: "Blue", disabled: true}); + const whiteSheet = new CSSStyleSheet({title: "White", alternate: true}); + const yellowSheet = new CSSStyleSheet({disabled: false}); + + const greenPromise = greenSheet.replace(greenStyleText); + const redPromise = redSheet.replace(redStyleTexts[0] + redStyleTexts[1]); + const bluePromise = blueSheet.replace(blueStyleTexts[0] + blueStyleTexts[1]); + const whitePromise = whiteSheet.replace(whiteStyleText); + const yellowPromise = yellowSheet.replace(yellowStyleText); + return [greenPromise, redPromise, bluePromise, whitePromise, yellowPromise]; +} promise_test(() => { - const green = document.createCSSStyleSheet(greenStyleText); - const red = document.createCSSStyleSheet(redStyleTexts[0] + redStyleTexts[1], {media: "screen, print"}); - const blue = document.createCSSStyleSheet(blueStyleTexts[0] + blueStyleTexts[1], {title: "Blue", disabled: true}); - const white = document.createCSSStyleSheet(whiteStyleText, {title: "White", alternate: true}); - const yellow = document.createCSSStyleSheet(yellowStyleText, {disabled: false}); - - return Promise.all([green, red, blue, white, yellow]).then(values => { + return Promise.all(createAllSheetsPromise()).then(values => { const greenStyleSheet = values[0]; const redStyleSheet = values[1]; const blueStyleSheet = values[2]; const whiteStyleSheet = values[3]; const yellowStyleSheet = values[4]; + // Lists of style sheets can be created, assigned and read. const whiteList = new StyleSheetList([whiteStyleSheet]); document.adoptedStyleSheets = whiteList; @@ -161,13 +173,7 @@ }, 'Constructed style sheets can be applied on document'); promise_test(() => { - const green = document.createCSSStyleSheet(greenStyleText); - const red = document.createCSSStyleSheet(redStyleTexts[0] + redStyleTexts[1], {media: "screen, print"}); - const blue = document.createCSSStyleSheet(blueStyleTexts[0] + blueStyleTexts[1], {title: "Blue", disabled: true}); - const white = document.createCSSStyleSheet(whiteStyleText, {title: "White", alternate: true}); - const yellow = document.createCSSStyleSheet(yellowStyleText, {disabled: false}); - - return Promise.all([green, red, blue, white, yellow]).then(values => { + return Promise.all(createAllSheetsPromise()).then(values => { const greenStyleSheet = values[0]; const redStyleSheet = values[1]; const blueStyleSheet = values[2]; @@ -205,7 +211,8 @@ }, 'Constructed style sheets can be applied on shadow root'); promise_test(() => { - const redStyleSheetPromise = document.createCSSStyleSheet(redStyleTexts[0]); + const plainSheet = new CSSStyleSheet(); + const redStyleSheetPromise = plainSheet.replace(redStyleTexts[0]); return redStyleSheetPromise.then(function(redStyleSheet) { document.adoptedStyleSheets = new StyleSheetList([redStyleSheet]); assert_equals(getComputedStyle(greenSpan).color, "rgb(0, 0, 0)"); @@ -238,7 +245,8 @@ }, 'Changes to constructed stylesheets through CSSOM is reflected'); promise_test(() => { - const redStyleSheetPromise = document.createCSSStyleSheet(redStyleTexts[0]); + const plainSheet = new CSSStyleSheet(); + const redStyleSheetPromise = plainSheet.replace(redStyleTexts[0]); return redStyleSheetPromise.then(function(redStyleSheet) { document.adoptedStyleSheets = new StyleSheetList([redStyleSheet]); shadowRoot.adoptedStyleSheets = new StyleSheetList([redStyleSheet]); @@ -280,7 +288,8 @@ const whiteIframeSpan = thirdDiv.children[3]; const yellowIframeSpan = thirdDiv.children[4]; - const redStyleSheetPromise = document.createCSSStyleSheet(redStyleTexts[0]); + const plainSheet = new CSSStyleSheet(); + const redStyleSheetPromise = plainSheet.replace(redStyleTexts[0]); return redStyleSheetPromise.then(function(redStyleSheet) { assert_throws('NotAllowedError', () => { iframe.contentDocument.adoptedStyleSheets = new StyleSheetList([redStyleSheet]); }); assert_equals(getComputedStyle(greenIframeSpan).color, "rgb(0, 0, 0)"); @@ -317,7 +326,7 @@ const yellowIframeSpan = thirdDiv.children[4]; // Make sure both the main Document and the iframe are not styled - const emptyStyleSheet = document.createEmptyCSSStyleSheet(); + const emptyStyleSheet = new CSSStyleSheet(); document.adoptedStyleSheets = new StyleSheetList([emptyStyleSheet]); assert_equals(getComputedStyle(greenSpan).color, "rgb(0, 0, 0)"); assert_equals(getComputedStyle(redSpan).color, "rgb(0, 0, 0)"); @@ -331,7 +340,8 @@ assert_equals(getComputedStyle(whiteIframeSpan).color, "rgb(0, 0, 0)"); assert_equals(getComputedStyle(yellowIframeSpan).color, "rgb(0, 0, 0)"); - const iframeRedStyleSheetPromise = iframe.contentDocument.createCSSStyleSheet(redStyleTexts[0]); + const iframePlainSheet = new iframe.contentWindow.CSSStyleSheet(); + const iframeRedStyleSheetPromise = iframePlainSheet.replace(redStyleTexts[0]); return iframeRedStyleSheetPromise.then(function(iframeRedStyleSheet) { assert_throws('NotAllowedError', () => { document.adoptedStyleSheets = new StyleSheetList([iframeRedStyleSheet]); }); assert_equals(getComputedStyle(greenSpan).color, "rgb(0, 0, 0)"); @@ -370,9 +380,8 @@ test(() => { assert_equals(getComputedStyle(divNonConstructed).color, "rgb(0, 0, 0)"); - document.adoptedStyleSheets = new StyleSheetList([nonConstructedStyleSheet]); - assert_equals(getComputedStyle(divNonConstructed).color, "rgb(255, 0, 0)"); -}, 'Adding non-constructed stylesheet to AdoptedStyleSheets is allowed when the owner document of the stylesheet is in the same document tree as the AdoptedStyleSheets'); + assert_throws('NotAllowedError', () => { document.adoptedStyleSheets = new StyleSheetList([nonConstructedStyleSheet]); }); +}, 'Adding non-constructed stylesheet to AdoptedStyleSheets is not allowed when the owner document of the stylesheet is in the same document tree as the AdoptedStyleSheets'); test(() => { const iframe = document.createElement("iframe"); @@ -398,37 +407,65 @@ assert_equals(getComputedStyle(iframeDiv).color, "rgb(0, 0, 0)"); }, 'Adding non-constructed stylesheet to AdoptedStyleSheets is not allowed when the owner document of the stylesheet and the AdoptedStyleSheets are in different document trees'); +function attachShadowDiv(host) { + const shadowRoot = host.attachShadow({mode: 'open'}); + const shadowDiv = document.createElement("div"); + shadowRoot.appendChild(shadowDiv); + return shadowDiv; +} test(() => { - const sheet = document.createCSSStyleSheetSync(redStyleTexts[0], {title: "Red", disabled: true, media: "screen, print"}); - assert_equals(sheet.title, "Red"); - assert_equals(sheet.ownerNode, null); - assert_equals(sheet.ownerRule, null); - assert_equals(sheet.media.length, 2); - assert_equals(sheet.media.item(0), "screen"); - assert_equals(sheet.media.item(1), "print"); - assert_true(sheet.disabled); + // Attach a div inside a shadow root with the class ".red". + const span = document.createElement("span"); + thirdSection.appendChild(span); + const shadowDiv = attachShadowDiv(span); + shadowDiv.classList.add("red"); + // Create empty stylesheet. + const sheet = new CSSStyleSheet(); + span.shadowRoot.adoptedStyleSheets = new StyleSheetList([sheet]); + assert_equals(getComputedStyle(shadowDiv).color, "rgb(0, 0, 0)"); + // Replace the stylesheet text that will color it red. + sheet.replaceSync(redStyleTexts[0]); + assert_equals(getComputedStyle(shadowDiv).color, "rgb(255, 0, 0)"); assert_equals(sheet.cssRules.length, 1); assert_equals(sheet.cssRules[0].cssText, redStyleTexts[0]); - sheet.insertRule(redStyleTexts[1]); assert_equals(sheet.cssRules.length, 2); assert_equals(sheet.cssRules[0].cssText, redStyleTexts[1]); -}, "Document.createCSSStyleSheetSync creates stylesheets synchronously"); +}, 'CSSStyleSheet.replaceSync replaces stylesheet text synchronously'); const import_text = '@import url("constructable-import.css");'; -test(() => { - assert_throws("NotAllowedError", () => { document.createCSSStyleSheetSync(import_text) }); -}, "Document.createCSSStyleSheetSync throws exception when there is import rule inside"); +test(() => { + assert_throws("NotAllowedError", () => { (new CSSStyleSheet).replaceSync(import_text) }); +}, 'CSSStyleSheet.replaceSync throws exception when there is import rule inside'); + +test(() => { + assert_throws("NotAllowedError", () => { (new CSSStyleSheet).insertRule(import_text) }); +}, 'Inserting an @import rule through insertRule on a constructed stylesheet throws an exception'); promise_test(() => { - const sheet_promise = document.createCSSStyleSheet(import_text); - return sheet_promise.then(function(sheet) { + const span = document.createElement("span"); + thirdSection.appendChild(span); + const shadowDiv = attachShadowDiv(span); + const sheet = new CSSStyleSheet(); + span.shadowRoot.adoptedStyleSheets = new StyleSheetList([sheet]); + assert_equals(getComputedStyle(shadowDiv).color, "rgb(0, 0, 0)"); + // Replace and assert that the imported rule is applied. + const sheet_promise = sheet.replace(import_text); + return sheet_promise.then((sheet) => { assert_equals(sheet.cssRules.length, 1); assert_equals(sheet.cssRules[0].cssText, import_text); + assert_equals(getComputedStyle(shadowDiv).color, "rgb(255, 0, 0)"); }); -}, "Document.createCSSStyleSheet throws allows import rule inside"); +}, 'CSSStyleSheet.replace allows import rule inside'); +promise_test(() => { + const sheet = new CSSStyleSheet(); + const sheet_promise = sheet.replace("import url('not-there.css');"); + return sheet_promise.catch((reason) => { + assert_equals(reason.name, "NotAllowedError"); + }); +}, 'CSSStyleSheet.replace returns rejected promise on failed imports'); </script>
diff --git a/third_party/blink/web_tests/fast/css/constructable-import.css b/third_party/blink/web_tests/fast/css/constructable-import.css index 60f1eab9..d8ccc9d 100644 --- a/third_party/blink/web_tests/fast/css/constructable-import.css +++ b/third_party/blink/web_tests/fast/css/constructable-import.css
@@ -1,3 +1,3 @@ -body { +* { color: red; }
diff --git a/third_party/blink/web_tests/fast/dom/custom/define-with-default-style.html b/third_party/blink/web_tests/fast/dom/custom/define-with-default-style.html index 2459aba0..e50762c 100644 --- a/third_party/blink/web_tests/fast/dom/custom/define-with-default-style.html +++ b/third_party/blink/web_tests/fast/dom/custom/define-with-default-style.html
@@ -361,7 +361,7 @@ }, "CSSOM changes to non-constructed stylesheet should affect default style"); test (() => { - const constructedStyleSheet = document.createEmptyCSSStyleSheet(); + const constructedStyleSheet = new CSSStyleSheet(); const redStyleText = "* { color: red; }"; constructedStyleSheet.insertRule(redStyleText); window.customElements.define("element-constructed", class extends HTMLElement {
diff --git a/third_party/blink/web_tests/fast/dom/dom-constructors-expected.txt b/third_party/blink/web_tests/fast/dom/dom-constructors-expected.txt index 2555343..e041752 100644 --- a/third_party/blink/web_tests/fast/dom/dom-constructors-expected.txt +++ b/third_party/blink/web_tests/fast/dom/dom-constructors-expected.txt
@@ -73,7 +73,6 @@ PASS TryAllocate('CSSRuleList') is 'exception' PASS TryAllocate('CSSStyleDeclaration') is 'exception' PASS TryAllocate('CSSStyleRule') is 'exception' -PASS TryAllocate('CSSStyleSheet') is 'exception' PASS TryAllocate('DOMImplementation') is 'exception' PASS TryAllocate('HTMLCollection') is 'exception' PASS TryAllocate('MediaList') is 'exception' @@ -111,6 +110,9 @@ PASS TryAllocate('Comment') is '[object Comment]' PASS TryAllocate('Comment') is '[object Comment]' PASS TryAllocate('Comment') is '[object Comment]' +PASS TryAllocate('CSSStyleSheet') is '[object CSSStyleSheet]' +PASS TryAllocate('CSSStyleSheet') is '[object CSSStyleSheet]' +PASS TryAllocate('CSSStyleSheet') is '[object CSSStyleSheet]' PASS TryAllocate('DataTransfer') is '[object DataTransfer]' PASS TryAllocate('DataTransfer') is '[object DataTransfer]' PASS TryAllocate('DataTransfer') is '[object DataTransfer]'
diff --git a/third_party/blink/web_tests/fast/dom/dom-constructors.html b/third_party/blink/web_tests/fast/dom/dom-constructors.html index 4db983a..10bc18e 100644 --- a/third_party/blink/web_tests/fast/dom/dom-constructors.html +++ b/third_party/blink/web_tests/fast/dom/dom-constructors.html
@@ -84,7 +84,6 @@ 'CSSRuleList', 'CSSStyleDeclaration', 'CSSStyleRule', - 'CSSStyleSheet', 'DOMImplementation', 'HTMLCollection', 'MediaList', @@ -119,6 +118,7 @@ // These objects should have a working constructor. var objects_constructor = [ 'Comment', + 'CSSStyleSheet', 'DataTransfer', 'DOMParser', 'Document',
diff --git a/third_party/blink/web_tests/fast/text/absolute-in-inline-block-change-crash.html b/third_party/blink/web_tests/fast/text/absolute-in-inline-block-change-crash.html index dd4d5c9..43ffa69 100644 --- a/third_party/blink/web_tests/fast/text/absolute-in-inline-block-change-crash.html +++ b/third_party/blink/web_tests/fast/text/absolute-in-inline-block-change-crash.html
@@ -10,7 +10,6 @@ testRunner.dumpAsText(); document.body.offsetTop; -//abs.appendChild(document.createTextNode('abs')); abs.style.top = '0'; </script> </body>
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-inner-multicol-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-inner-multicol-expected.png new file mode 100644 index 0000000..9d5e71e5 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-inner-multicol-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-multiple-fragments-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-multiple-fragments-expected.png new file mode 100644 index 0000000..a13e3e93 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-multiple-fragments-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-multiple-fragments-translated-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-multiple-fragments-translated-expected.png new file mode 100644 index 0000000..996b8f8 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-multiple-fragments-translated-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-nested-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-nested-expected.png new file mode 100644 index 0000000..a13e3e93 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-nested-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-will-change-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-will-change-expected.png new file mode 100644 index 0000000..3a09e761 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-will-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png new file mode 100644 index 0000000..23ad64c2 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-opacity-2nd-and-3rd-column-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-clipped-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-clipped-expected.png new file mode 100644 index 0000000..b1ec5fe --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-clipped-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-expected.png new file mode 100644 index 0000000..58e2d6f1 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-in-clipped-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-in-clipped-expected.png new file mode 100644 index 0000000..07712fbe8 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-in-clipped-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-overlapping-will-change-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-overlapping-will-change-expected.png new file mode 100644 index 0000000..f582966 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-overlapping-will-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-resize-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-resize-expected.png new file mode 100644 index 0000000..3b8b08d --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-relpos-resize-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-with-child-layer-in-next-column-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-with-child-layer-in-next-column-expected.png new file mode 100644 index 0000000..a08106f --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-with-child-layer-in-next-column-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-with-overflow-in-next-column-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-with-overflow-in-next-column-expected.png new file mode 100644 index 0000000..98de5cc --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-with-overflow-in-next-column-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/span/invalid-spanner-in-transform-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/span/invalid-spanner-in-transform-expected.png new file mode 100644 index 0000000..4263f303 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/span/invalid-spanner-in-transform-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/vertical-lr/composited-relpos-overlapping-will-change-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/vertical-lr/composited-relpos-overlapping-will-change-expected.png new file mode 100644 index 0000000..9eafea09 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/vertical-lr/composited-relpos-overlapping-will-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/vertical-rl/composited-relpos-overlapping-will-change-expected.png b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/vertical-rl/composited-relpos-overlapping-will-change-expected.png new file mode 100644 index 0000000..9bad00d2 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/vertical-rl/composited-relpos-overlapping-will-change-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js b/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js index ca6b1b9e..bfe902e7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js +++ b/third_party/blink/web_tests/http/tests/devtools/tracing/timeline-misc/timeline-filtering.js
@@ -298,11 +298,11 @@ dumpRecords(); TestRunner.addResult(`Filtered by 'bar':`); - view._textFilterUI._internalSetValue('bar', true); + view._textFilterUI.setValue('bar', true); dumpRecords(); TestRunner.addResult(`Filtered by 'foo':`); - view._textFilterUI._internalSetValue('foo', true); + view._textFilterUI.setValue('foo', true); dumpRecords(); TestRunner.completeTest();
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/fetch-canvas-tainting.html b/third_party/blink/web_tests/http/tests/serviceworker/fetch-canvas-tainting.html deleted file mode 100644 index efdf42a..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/fetch-canvas-tainting.html +++ /dev/null
@@ -1,44 +0,0 @@ -<!DOCTYPE html> -<!-- This test cannot be upstreamed to WPT because the equivalent version - available in Web Platform Tests is known to cause timeout errors in the - Chromium automated build system. They should be maintained only to preserve - test converage until the corresponding versions in Web Platform Tests can be - made to pass consistently. See - https://codereview.chromium.org/2805313003/ --> -<title>Service Worker: canvas tainting of the fetched image</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/resources/get-host-info.js?pipe=sub"></script> -<script src="resources/test-helpers.js"></script> -<body> -<script> -async_test(function(t) { - var SCOPE = 'resources/fetch-canvas-tainting-iframe.html'; - var SCRIPT = 'resources/fetch-rewrite-worker.js'; - var host_info = get_host_info(); - - login(t, host_info.HTTP_ORIGIN, host_info.HTTP_REMOTE_ORIGIN) - .then(function() { - return service_worker_unregister_and_register(t, SCRIPT, SCOPE); - }) - .then(function(registration) { - return wait_for_state(t, registration.installing, 'activated'); - }) - .then(function() { return with_iframe(SCOPE); }) - .then(function(frame) { - return new Promise(function(resolve, reject) { - var channel = new MessageChannel(); - channel.port1.onmessage = t.step_func(function(e) { - assert_equals(e.data.results, 'finish'); - frame.remove(); - service_worker_unregister_and_done(t, SCOPE); - }); - frame.contentWindow.postMessage({}, - host_info['HTTP_ORIGIN'], - [channel.port2]); - }); - }) - .catch(unreached_rejection(t)); - }, 'Verify canvas tainting of fetched image in a Service Worker'); -</script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/fetch-cors-xhr.html b/third_party/blink/web_tests/http/tests/serviceworker/fetch-cors-xhr.html deleted file mode 100644 index cbe11b9..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/fetch-cors-xhr.html +++ /dev/null
@@ -1,44 +0,0 @@ -<!DOCTYPE html> -<!-- This test cannot be upstreamed to WPT because the equivalent version - available in Web Platform Tests is known to cause timeout errors in the - Chromium automated build system. They should be maintained only to preserve - test converage until the corresponding versions in Web Platform Tests can be - made to pass consistently. See - https://codereview.chromium.org/2805313003/ --> -<title>Service Worker: CORS XHR of fetch()</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/resources/get-host-info.js?pipe=sub"></script> -<script src="resources/test-helpers.js"></script> -<body> -<script> -async_test(function(t) { - var SCOPE = 'resources/fetch-cors-xhr-iframe.html'; - var SCRIPT = 'resources/fetch-rewrite-worker.js'; - var host_info = get_host_info(); - - login(t, host_info.HTTP_ORIGIN, host_info.HTTP_REMOTE_ORIGIN) - .then(function() { - return service_worker_unregister_and_register(t, SCRIPT, SCOPE); - }) - .then(function(registration) { - return wait_for_state(t, registration.installing, 'activated'); - }) - .then(function() { return with_iframe(SCOPE); }) - .then(function(frame) { - return new Promise(function(resolve, reject) { - var channel = new MessageChannel(); - channel.port1.onmessage = t.step_func(function(e) { - assert_equals(e.data.results, 'finish'); - frame.remove(); - service_worker_unregister_and_done(t, SCOPE); - }); - frame.contentWindow.postMessage({}, - host_info['HTTP_ORIGIN'], - [channel.port2]); - }); - }) - .catch(unreached_rejection(t)); - }, 'Verify CORS XHR of fetch() in a Service Worker'); -</script> -</body>
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/fetch-csp-expected.txt b/third_party/blink/web_tests/http/tests/serviceworker/fetch-csp-expected.txt deleted file mode 100644 index 01e5e59..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/fetch-csp-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -CONSOLE ERROR: Refused to load the image 'http://localhost:8000/serviceworker/resources/fetch-access-control.php?PNGIMAGE' because it violates the following Content Security Policy directive: "img-src http://127.0.0.1:8000". - -CONSOLE ERROR: Refused to load the image 'http://localhost:8000/serviceworker/resources/fetch-access-control.php?PNGIMAGE' because it violates the following Content Security Policy directive: "img-src http://127.0.0.1:8000". - -This is a testharness.js-based test. -PASS Verify CSP control of fetch() in a Service Worker -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/fetch-csp.html b/third_party/blink/web_tests/http/tests/serviceworker/fetch-csp.html deleted file mode 100644 index 8f0f965..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/fetch-csp.html +++ /dev/null
@@ -1,117 +0,0 @@ -<!DOCTYPE html> -<!-- This test cannot be upstreamed to WPT because the equivalent version - available in Web Platform Tests is known to cause timeout errors in the - Chromium automated build system. They should be maintained only to preserve - test converage until the corresponding versions in Web Platform Tests can be - made to pass consistently. See - https://codereview.chromium.org/2805313003/ --> -<title>Service Worker: CSP control of fetch()</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/resources/get-host-info.js?pipe=sub"></script> -<script src="resources/test-helpers.js"></script> -<script> - -function assert_resolves(promise, description) { - return promise.catch(function(reason) { - throw new Error(description + ' - ' + reason.message); - }); -} - -function assert_rejects(promise, description) { - return promise.then( - function() { throw new Error(description); }, - function() {}); -} - -promise_test(function(t) { - var SCOPE = 'resources/fetch-csp-iframe.html'; - var SCRIPT = 'resources/fetch-rewrite-worker.js'; - var host_info = get_host_info(); - var IMAGE_PATH = - base_path() + 'resources/fetch-access-control.php?PNGIMAGE'; - var IMAGE_URL = host_info['HTTP_ORIGIN'] + IMAGE_PATH; - var REMOTE_IMAGE_URL = host_info['HTTP_REMOTE_ORIGIN'] + IMAGE_PATH; - var REDIRECT_URL = - host_info['HTTP_ORIGIN'] + base_path() + 'resources/redirect.php'; - var frame; - - return service_worker_unregister_and_register(t, SCRIPT, SCOPE) - .then(function(registration) { - return wait_for_state(t, registration.installing, 'activated'); - }) - .then(function() { - return with_iframe( - SCOPE + '?' + - encodeURIComponent('img-src ' + host_info['HTTP_ORIGIN'] + - '; script-src \'unsafe-inline\'')); - }) - .then(function(f) { - frame = f; - return assert_resolves( - frame.contentWindow.load_image(IMAGE_URL), - 'Allowed scope image resource should be loaded.'); - }) - .then(function() { - return assert_rejects( - frame.contentWindow.load_image(REMOTE_IMAGE_URL), - 'Disallowed scope image resource should not be loaded.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - // The request for IMAGE_URL will be fetched in SW. - './dummy?url=' + encodeURIComponent(IMAGE_URL)), - 'Allowed scope image resource which was fetched via SW should ' + - 'be loaded.'); - }) - .then(function() { - return assert_rejects( - frame.contentWindow.load_image( - // The request for REMOTE_IMAGE_URL will be fetched in SW. - './dummy?mode=no-cors&url=' + - encodeURIComponent(REMOTE_IMAGE_URL)), - 'Disallowed scope image resource which was fetched via SW ' + - 'should not be loaded.'); - }) - .then(function() { - frame.remove(); - return with_iframe( - SCOPE + '?' + - encodeURIComponent( - 'img-src ' + REDIRECT_URL + - '; script-src \'unsafe-inline\'')); - }) - .then(function(f) { - frame = f; - return assert_resolves( - frame.contentWindow.load_image( - // Set 'ignore' not to call respondWith() in the SW. - REDIRECT_URL + '?ignore&Redirect=' + - encodeURIComponent(IMAGE_URL)), - 'When the request was redirected, CSP match algorithm should ' + - 'ignore the path component of the URL.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - // This request will be fetched via SW and redirected by - // redirect.php. - REDIRECT_URL + '?Redirect=' + encodeURIComponent(IMAGE_URL)), - 'When the request was redirected via SW, CSP match algorithm ' + - 'should ignore the path component of the URL.'); - }) - .then(function() { - return assert_resolves( - frame.contentWindow.load_image( - // The request for IMAGE_URL will be fetched in SW. - REDIRECT_URL + '?url=' + encodeURIComponent(IMAGE_URL)), - 'When the request was fetched via SW, CSP match algorithm ' + - 'should ignore the path component of the URL.'); - }) - .then(function() { - frame.remove(); - service_worker_unregister_and_done(t, SCOPE); - }); - }, 'Verify CSP control of fetch() in a Service Worker'); -</script>
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-canvas-tainting-iframe.html b/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-canvas-tainting-iframe.html deleted file mode 100644 index fb45ddf..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-canvas-tainting-iframe.html +++ /dev/null
@@ -1,254 +0,0 @@ -<script src="/resources/get-host-info.js?pipe=sub"></script> -<script src="test-helpers.js"></script> -<script> -var image_path = base_path() + 'fetch-access-control.php?PNGIMAGE'; -var host_info = get_host_info(); - -var NOT_TAINTED = 'NOT_TAINTED'; -var TAINTED = 'TAINTED'; -var LOAD_ERROR = 'LOAD_ERROR'; - -function create_test_case_promise(url, cross_origin) { - return new Promise(function(resolve) { - var img = new Image(); - if (cross_origin != '') { - img.crossOrigin = cross_origin; - } - img.onload = function() { - try { - var canvas = document.createElement('canvas'); - canvas.width = 100; - canvas.height = 100; - var context = canvas.getContext('2d'); - context.drawImage(img, 0, 0); - context.getImageData(0, 0, 100, 100); - resolve(NOT_TAINTED); - } catch (e) { - resolve(TAINTED); - } - }; - img.onerror = function() { - resolve(LOAD_ERROR); - } - img.src = url; - }); -} - -function create_test_promise(url, cross_origin, expected_result) { - return new Promise(function(resolve, reject) { - create_test_case_promise(url, cross_origin) - .then(function(result) { - if (result == expected_result) { - resolve(); - } else { - reject('Result of url:' + url + ' ' + - ' cross_origin: ' + cross_origin + ' must be ' + - expected_result + ' but ' + result); - } - }) - }); -} - -window.addEventListener('message', function(evt) { - var port = evt.ports[0]; - var image_url = host_info['HTTP_ORIGIN'] + image_path; - var remote_image_url = host_info['HTTP_REMOTE_ORIGIN'] + image_path; - Promise.all([ - // Reject tests - create_test_promise(image_url + '&reject', '', LOAD_ERROR), - create_test_promise(image_url + '&reject', 'anonymous', LOAD_ERROR), - create_test_promise( - image_url + '&reject', 'use-credentials', LOAD_ERROR), - // Fallback tests - create_test_promise( - image_url + '&ignore', - '', - NOT_TAINTED), - create_test_promise( - remote_image_url + '&ignore', - '', - TAINTED), - create_test_promise( - remote_image_url + '&ignore', - 'anonymous', - LOAD_ERROR), - create_test_promise( - remote_image_url + '&ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ignore', - 'anonymous', - NOT_TAINTED), - create_test_promise( - remote_image_url + '&ignore', - 'use-credentials', - LOAD_ERROR), - create_test_promise( - remote_image_url + '&ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ignore', - 'use-credentials', - LOAD_ERROR), - create_test_promise( - remote_image_url + '&ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ACACredentials=true&ignore', - 'use-credentials', - NOT_TAINTED), - - // Credential test (fallback) - create_test_promise( - image_url + '&Auth&ignore', - '', - NOT_TAINTED), - create_test_promise( - remote_image_url + '&Auth&ignore', - '', - TAINTED), - create_test_promise( - remote_image_url + '&Auth&ignore', - 'anonymous', - LOAD_ERROR), - create_test_promise( - remote_image_url + '&Auth&ignore', - 'use-credentials', - LOAD_ERROR), - create_test_promise( - remote_image_url + '&Auth&ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ignore', - 'use-credentials', - LOAD_ERROR), - create_test_promise( - remote_image_url + '&Auth&ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ACACredentials=true&ignore', - 'use-credentials', - NOT_TAINTED), - - // Basic response - create_test_promise( - image_url + - '&mode=same-origin&url=' + encodeURIComponent(image_url), - '', - NOT_TAINTED), - create_test_promise( - image_url + - '&mode=same-origin&url=' + encodeURIComponent(image_url), - 'anonymous', - NOT_TAINTED), - create_test_promise( - image_url + - '&mode=same-origin&url=' + encodeURIComponent(image_url), - 'use-credentials', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=same-origin&url=' + encodeURIComponent(image_url), - '', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=same-origin&url=' + encodeURIComponent(image_url), - 'anonymous', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=same-origin&url=' + encodeURIComponent(image_url), - 'use-credentials', - NOT_TAINTED), - - // Opaque response - create_test_promise( - image_url + - '&mode=no-cors&url=' + encodeURIComponent(remote_image_url), - '', - TAINTED), - create_test_promise( - image_url + - '&mode=no-cors&url=' + encodeURIComponent(remote_image_url), - 'anonymous', - LOAD_ERROR), - create_test_promise( - image_url + - '&mode=no-cors&url=' + encodeURIComponent(remote_image_url), - 'use-credentials', - LOAD_ERROR), - create_test_promise( - remote_image_url + - '&mode=no-cors&url=' + encodeURIComponent(remote_image_url), - '', - TAINTED), - create_test_promise( - remote_image_url + - '&mode=no-cors&url=' + encodeURIComponent(remote_image_url), - 'anonymous', - LOAD_ERROR), - create_test_promise( - remote_image_url + - '&mode=no-cors&url=' + encodeURIComponent(remote_image_url), - 'use-credentials', - LOAD_ERROR), - - // CORS response - create_test_promise( - image_url + - '&mode=cors&url=' + - encodeURIComponent(remote_image_url + - '&ACAOrigin=' + host_info['HTTP_ORIGIN']), - '', - NOT_TAINTED), - create_test_promise( - image_url + - '&mode=cors&url=' + - encodeURIComponent(remote_image_url + - '&ACAOrigin=' + host_info['HTTP_ORIGIN']), - 'anonymous', - NOT_TAINTED), - create_test_promise( - image_url + - '&mode=cors&url=' + - encodeURIComponent(remote_image_url + - '&ACAOrigin=' + host_info['HTTP_ORIGIN']), - 'use-credentials', - NOT_TAINTED), - create_test_promise( - image_url + - '&mode=cors&url=' + - encodeURIComponent( - remote_image_url + - '&ACACredentials=true&ACAOrigin=' + host_info['HTTP_ORIGIN']), - 'use-credentials', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=cors&url=' + - encodeURIComponent(remote_image_url + - '&ACAOrigin=' + host_info['HTTP_ORIGIN']), - '', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=cors&url=' + - encodeURIComponent(remote_image_url + - '&ACAOrigin=' + host_info['HTTP_ORIGIN']), - 'anonymous', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=cors&url=' + - encodeURIComponent(remote_image_url + - '&ACAOrigin=' + host_info['HTTP_ORIGIN']), - 'use-credentials', - NOT_TAINTED), - create_test_promise( - remote_image_url + - '&mode=cors&url=' + - encodeURIComponent( - remote_image_url + - '&ACACredentials=true&ACAOrigin=' + host_info['HTTP_ORIGIN']), - 'use-credentials', - NOT_TAINTED) - ]) - .then(function() { - port.postMessage({results: 'finish'}); - }) - .catch(function(e) { - port.postMessage({results: 'failure:' + e}); - }); - }, false); -</script>
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-cors-xhr-iframe.html b/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-cors-xhr-iframe.html deleted file mode 100644 index 4a2dfcbe..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-cors-xhr-iframe.html +++ /dev/null
@@ -1,190 +0,0 @@ -<script src="/resources/get-host-info.js?pipe=sub"></script> -<script src="test-helpers.js"></script> -<script> -var path = base_path() + 'fetch-access-control.php'; -var host_info = get_host_info(); -var SUCCESS = 'SUCCESS'; -var FAIL = 'FAIL'; - -function create_test_case_promise(url, with_credentials) { - return new Promise(function(resolve) { - var xhr = new XMLHttpRequest(); - xhr.onload = function() { - if (xhr.status == 200) { - resolve(SUCCESS); - } else { - resolve("STATUS" + xhr.status); - } - } - xhr.onerror = function() { - resolve(FAIL); - } - xhr.responseType = 'text'; - xhr.withCredentials = with_credentials; - xhr.open('GET', url, true); - xhr.send(); - }); -} - - -function create_test_promise(url, with_credentials, expected_result) { - return new Promise(function(resolve, reject) { - create_test_case_promise(url, with_credentials) - .then(function(result) { - if (result == expected_result) { - resolve(); - } else { - reject('Result of url:' + url + ' ' + - ' with_credentials: ' + with_credentials + ' must be ' + - expected_result + ' but ' + result); - } - }) - }); -} - -function create_serial_promise(test_cases) { - var promise = Promise.resolve(); - test_cases.forEach(function(test_case) { - promise = promise.then(function() { - return create_test_promise(test_case[0], test_case[1], test_case[2]); - }); - }); - return promise; -} - -window.addEventListener('message', function(evt) { - var port = evt.ports[0]; - var url = host_info['HTTP_ORIGIN'] + path; - var remote_url = host_info['HTTP_REMOTE_ORIGIN'] + path; - // If the 4th value of the item of TEST_CASES is true, the test case outputs - // warning messages. So such tests must be executed in serial to match the - // expected output text. - var TEST_CASES = [ - // Reject tests - [url + '?reject', false, FAIL], - [url + '?reject', true, FAIL], - [remote_url + '?reject', false, FAIL], - [remote_url + '?reject', true, FAIL], - // Reject(resolve-null) tests - [url + '?resolve-null', false, FAIL], - [url + '?resolve-null', true, FAIL], - [remote_url + '?resolve-null', false, FAIL], - [remote_url + '?resolve-null', true, FAIL], - // Fallback tests - [url + '?ignore', false, SUCCESS], - [url + '?ignore', true, SUCCESS], - [remote_url + '?ignore', false, FAIL, true], // Executed in serial. - [remote_url + '?ignore', true, FAIL, true], // Executed in serial. - [ - remote_url + '?ACAOrigin=' + host_info['HTTP_ORIGIN'] + '&ignore', - false, SUCCESS - ], - [ - remote_url + '?ACAOrigin=' + host_info['HTTP_ORIGIN'] + '&ignore', - true, FAIL, true // Executed in serial. - ], - [ - remote_url + '?ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ACACredentials=true&ignore', - true, SUCCESS - ], - // Credential test (fallback) - [url + '?Auth&ignore', false, SUCCESS], - [url + '?Auth&ignore', true, SUCCESS], - [remote_url + '?Auth&ignore', false, FAIL, true], // Executed in serial. - [remote_url + '?Auth&ignore', true, FAIL, true], // Executed in serial. - [ - remote_url + '?Auth&ACAOrigin=' + host_info['HTTP_ORIGIN'] + '&ignore', - false, 'STATUS401' - ], - [ - remote_url + '?Auth&ACAOrigin=' + host_info['HTTP_ORIGIN'] + '&ignore', - true, FAIL, true // Executed in serial. - ], - [ - remote_url + '?Auth&ACAOrigin=' + host_info['HTTP_ORIGIN'] + - '&ACACredentials=true&ignore', - true, SUCCESS - ], - // Basic response - [ - url + '?mode=same-origin&url=' + encodeURIComponent(url), - false, SUCCESS - ], - [ - url + '?mode=same-origin&url=' + encodeURIComponent(url), - false, SUCCESS - ], - [ - remote_url + '?mode=same-origin&url=' + encodeURIComponent(url), - false, SUCCESS - ], - [ - remote_url + '?mode=same-origin&url=' + encodeURIComponent(url), - false, SUCCESS - ], - // Opaque response - [ - url + '?mode=no-cors&url=' + encodeURIComponent(remote_url), - false, FAIL - ], - [ - url + '?mode=no-cors&url=' + encodeURIComponent(remote_url), - false, FAIL - ], - [ - remote_url + '?mode=no-cors&url=' + encodeURIComponent(remote_url), - false, FAIL - ], - [ - remote_url + '?mode=no-cors&url=' + encodeURIComponent(remote_url), - false, FAIL - ], - // CORS response - [ - url + '?mode=cors&url=' + - encodeURIComponent(remote_url + '?ACAOrigin=' + - host_info['HTTP_ORIGIN']), - false, SUCCESS - ], - [ - url + '?mode=cors&url=' + - encodeURIComponent(remote_url + '?ACAOrigin=' + - host_info['HTTP_ORIGIN']), - true, SUCCESS - ], - [ - remote_url + '?mode=cors&url=' + - encodeURIComponent(remote_url + '?ACAOrigin=' + - host_info['HTTP_ORIGIN']), - false, SUCCESS - ], - [ - remote_url + - '?mode=cors&url=' + - encodeURIComponent(remote_url + '?ACAOrigin=' + - host_info['HTTP_ORIGIN']), - true, SUCCESS - ] - ]; - var promises = []; - var serial_tests = []; - for (var i = 0; i < TEST_CASES.length ; ++i) { - if (!TEST_CASES[i][3]) { - promises.push(create_test_promise(TEST_CASES[i][0], - TEST_CASES[i][1], - TEST_CASES[i][2])); - } else { - serial_tests.push(TEST_CASES[i]); - } - } - promises.push(create_serial_promise(serial_tests)); - Promise.all(promises) - .then(function() { - port.postMessage({results: 'finish'}); - }) - .catch(function(e) { - port.postMessage({results: 'failure:' + e}); - }); - }, false); -</script>
diff --git a/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-csp-iframe.html b/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-csp-iframe.html deleted file mode 100644 index 33bf041..0000000 --- a/third_party/blink/web_tests/http/tests/serviceworker/resources/fetch-csp-iframe.html +++ /dev/null
@@ -1,16 +0,0 @@ -<script> -var meta = document.createElement('meta'); -meta.setAttribute('http-equiv', 'Content-Security-Policy'); -meta.setAttribute('content', decodeURIComponent(location.search.substring(1))); -document.head.appendChild(meta); - -function load_image(url) { - return new Promise(function(resolve, reject) { - var img = document.createElement('img'); - document.body.appendChild(img); - img.onload = resolve; - img.onerror = reject; - img.src = url; - }); -} -</script>
diff --git a/third_party/blink/web_tests/platform/mac-retina/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt b/third_party/blink/web_tests/platform/mac-retina/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/third_party/blink/web_tests/platform/mac-retina/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/target_blank_implicit_noopener.tentative-expected.txt
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 57aeb0c..b8d4e26 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -812,6 +812,8 @@ method deleteRule method insertRule method removeRule + method replace + method replaceSync interface CSSStyleValue static method parse static method parseAll @@ -1646,13 +1648,10 @@ method createAttribute method createAttributeNS method createCDATASection - method createCSSStyleSheet - method createCSSStyleSheetSync method createComment method createDocumentFragment method createElement method createElementNS - method createEmptyCSSStyleSheet method createEvent method createExpression method createNSResolver
diff --git a/tools/code_coverage/run_fuzz_target.py b/tools/code_coverage/run_fuzz_target.py index 98adcd5..2b092d3a 100755 --- a/tools/code_coverage/run_fuzz_target.py +++ b/tools/code_coverage/run_fuzz_target.py
@@ -5,6 +5,7 @@ """Run a single fuzz target built with code coverage instrumentation.""" import argparse +import json import os import shutil import signal @@ -137,6 +138,21 @@ required=True, help='Timeout value for running a single fuzz target.') + # Ignored. Used to comply with isolated script contract, see chromium_tests + # and swarming recipe modules for more details. + arg_parser.add_argument( + '--isolated-script-test-output', + type=str, + required=False, + help=argparse.SUPPRESS) + + # Ditto. + arg_parser.add_argument( + '--isolated-script-test-perf-output', + type=str, + required=False, + help=argparse.SUPPRESS) + if len(sys.argv) == 1: arg_parser.print_help() sys.exit(1) @@ -212,8 +228,27 @@ args = _ParseCommandArguments() fuzzer_name = os.path.splitext(os.path.basename(args.fuzzer))[0] corpus_dir = _PrepareCorpus(fuzzer_name, args.output_dir) + start_time = time.time() _RunFuzzTarget(args.fuzzer, fuzzer_name, args.output_dir, corpus_dir, args.timeout) + if args.isolated_script_test_output: + # TODO(crbug.com/913827): Actually comply with the isolated script contract + # on src/testing/scripts/common. + with open(args.isolated_script_test_output, 'w') as f: + json.dump({ + fuzzer_name: { + 'expected': 'PASS', + 'actual': 'PASS', + }, + "interrupted": False, + "path_delimiter": ".", + "version": 3, + "seconds_since_epoch": start_time, + "num_failures_by_type": { + "FAIL": 0, + "PASS": 1 + }, + }, f) return 0
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 6ea737f..b7c0138 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -299,6 +299,7 @@ 'Chromium Mac Goma RBE Staging': 'release_bot', 'Chromium Mac Goma RBE Staging (dbg)': 'debug_bot', 'Chromium Android ARM 32-bit Goma RBE Staging': 'android_release_bot_minimal_symbols', + 'Chromium Linux Goma RBE Prod': 'release_bot', }, 'chromium.gpu': { @@ -1122,12 +1123,12 @@ ], 'clang_code_coverage': [ - 'release_bot', 'clang', 'use_clang_coverage', 'no_symbols', + 'release_bot', 'clang', 'use_clang_coverage', 'no_symbols', 'libfuzzer', ], 'clang_code_coverage_trybot': [ 'gpu_tests', 'use_dummy_lastchange', 'release_trybot', 'clang', 'use_clang_coverage', 'no_symbols', - 'partial_clang_instrumentation' + 'libfuzzer', 'partial_clang_instrumentation' ], 'clang_release_bot_minimal_symbols_x86': [
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index cb28fdd..46167a9 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -10718,7 +10718,7 @@ </action> <action name="MediaContextMenu_EnterPictureInPicture"> - <owner>apacible@chromium.org</owner> + <owner>mlamouri@chromium.org</owner> <owner>media-dev@chromium.org</owner> <description> User clicked on the contextual menu of a video player to enter @@ -10727,7 +10727,7 @@ </action> <action name="MediaContextMenu_ExitPictureInPicture"> - <owner>apacible@chromium.org</owner> + <owner>mlamouri@chromium.org</owner> <owner>media-dev@chromium.org</owner> <description> User clicked on the contextual menu of a video player to exit
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 365fbba..91a0188 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -16109,6 +16109,9 @@ <int value="427" label="AUTOMATION_INTERNAL_ON_GET_TEXT_LOCATION_RESULT"/> <int value="428" label="INPUT_METHOD_PRIVATE_ON_SETTINGS_CHANGED"/> <int value="429" label="INPUT_METHOD_PRIVATE_ON_SCREEN_PROJECTION_CHANGED"/> + <int value="430" label="STORAGE_LOCAL_ON_CHANGE"/> + <int value="431" label="STORAGE_SYNC_ON_CHANGE"/> + <int value="432" label="STORAGE_MANAGED_ON_CHANGE"/> </enum> <enum name="ExtensionFileWriteResult"> @@ -17469,6 +17472,10 @@ <int value="1298" label="PASSWORDSPRIVATE_RECORDPASSWORDSPAGEACCESSINSETTINGS"/> <int value="1299" label="AUTOFILLPRIVATE_SERVERCARDLINKCLICKED"/> + <int value="1300" label="AUTOTESTPRIVATE_GETARCAPP"/> + <int value="1301" label="AUTOTESTPRIVATE_GETARCPACKAGE"/> + <int value="1302" label="AUTOTESTPRIVATE_LAUNCHARCAPP"/> + <int value="1303" label="AUTOTESTPRIVATE_CLOSEAPP"/> </enum> <enum name="ExtensionIconState"> @@ -20659,17 +20666,17 @@ <int value="2332" label="ColorInputTypeChooserByTrustedClick"/> <int value="2333" label="ColorInputTypeChooserByUntrustedClick"/> <int value="2334" label="CSSTypedOMStylePropertyMap"/> - <int value="2335" label="ScrollToFragmentRequested"/> - <int value="2336" label="ScrollToFragmentSucceedWithRaw"/> - <int value="2337" label="ScrollToFragmentSucceedWithASCII"/> - <int value="2338" label="ScrollToFragmentSucceedWithUTF8"/> - <int value="2339" label="ScrollToFragmentSucceedWithIsomorphic"/> + <int value="2335" label="OBSOLETE_ScrollToFragmentRequested"/> + <int value="2336" label="OBSOLETE_ScrollToFragmentSucceedWithRaw"/> + <int value="2337" label="OBSOLETE_ScrollToFragmentSucceedWithASCII"/> + <int value="2338" label="OBSOLETE_ScrollToFragmentSucceedWithUTF8"/> + <int value="2339" label="OBSOLETE_ScrollToFragmentSucceedWithIsomorphic"/> <int value="2340" label="OBSOLETE_ScrollToFragmentSucceedWithMixed"/> - <int value="2341" label="ScrollToFragmentFailWithASCII"/> - <int value="2342" label="ScrollToFragmentFailWithUTF8"/> - <int value="2343" label="ScrollToFragmentFailWithIsomorphic"/> + <int value="2341" label="OBSOLETE_ScrollToFragmentFailWithASCII"/> + <int value="2342" label="OBSOLETE_ScrollToFragmentFailWithUTF8"/> + <int value="2343" label="OBSOLETE_ScrollToFragmentFailWithIsomorphic"/> <int value="2344" label="OBSOLETE_ScrollToFragmentFailWithMixed"/> - <int value="2345" label="ScrollToFragmentFailWithInvalidEncoding"/> + <int value="2345" label="OBSOLETE_ScrollToFragmentFailWithInvalidEncoding"/> <int value="2346" label="RTCPeerConnectionWithActiveCsp"/> <int value="2347" label="ImageDecodingAttribute"/> <int value="2348" label="ImageDecodeAPI"/> @@ -30020,6 +30027,7 @@ <int value="-1014936248" label="SyncUSSBookmarks:enabled"/> <int value="-1014649471" label="committed-interstitials"/> <int value="-1010588306" label="SlideTopChromeWithPageScrolls:disabled"/> + <int value="-1008511612" label="EnableCustomMacPaperSizes:disabled"/> <int value="-998255750" label="ExperimentalKeyboardLockUI:enabled"/> <int value="-996673716" label="enable-web-app-frame"/> <int value="-994558985" label="EnableNotificationIndicator:disabled"/> @@ -30216,6 +30224,7 @@ <int value="-649956990" label="enable-harfbuzz-rendertext"/> <int value="-648925189" label="ExploreSites:enabled"/> <int value="-645455405" label="MacViewsNativeDialogs:enabled"/> + <int value="-641820371" label="EnableCustomMacPaperSizes:enabled"/> <int value="-641719457" label="disable-compositor-touch-hit-testing"/> <int value="-639026783" label="disable-gpu-appcontainer"/> <int value="-638952203" label="RendererSideResourceScheduler:disabled"/>
diff --git a/ui/aura/mus/window_port_mus.cc b/ui/aura/mus/window_port_mus.cc index e970a5d..6b925ca131 100644 --- a/ui/aura/mus/window_port_mus.cc +++ b/ui/aura/mus/window_port_mus.cc
@@ -319,6 +319,12 @@ return false; has_embedding_ = true; + if (!client_surface_embedder_) { + client_surface_embedder_ = std::make_unique<ClientSurfaceEmbedder>( + window_, /* inject_gutter */ false, gfx::Insets()); + } + // Triggers updating |client_surface_embedder_|. + GetOrAllocateLocalSurfaceIdForCurrentSize(); return true; } @@ -327,8 +333,10 @@ base::WeakPtr<WindowPortMus> window, ws::mojom::WindowTree::EmbedCallback real_callback, bool result) { - if (window && !result) + if (window && !result) { window->has_embedding_ = false; + window->client_surface_embedder_.reset(); + } std::move(real_callback).Run(window && result); } @@ -336,6 +344,12 @@ return window_tree_client_->delegate_->GetPropertyConverter(); } +void WindowPortMus::GetOrAllocateLocalSurfaceIdForCurrentSize() { + const gfx::Size size_in_pixels = + gfx::ScaleToCeiledSize(window_->bounds().size(), GetDeviceScaleFactor()); + GetOrAllocateLocalSurfaceId(size_in_pixels); +} + Window* WindowPortMus::GetWindow() { return window_; } @@ -578,6 +592,7 @@ void WindowPortMus::NotifyEmbeddedAppDisconnected() { has_embedding_ = false; + client_surface_embedder_.reset(); for (WindowObserver& observer : *GetObservers(window_)) observer.OnEmbeddedAppDisconnected(window_); } @@ -704,11 +719,9 @@ embed_frame_sink_id_ = GenerateFrameSinkIdFromServerId(); window_->SetEmbedFrameSinkId(embed_frame_sink_id_); - gfx::Size size_in_pixel = - gfx::ConvertSizeToPixel(GetDeviceScaleFactor(), window_->bounds().size()); // Make sure |local_surface_id_| and |last_surface_size_in_pixels_| are // correct for the new created |local_layer_tree_frame_sink_|. - GetOrAllocateLocalSurfaceId(size_in_pixel); + GetOrAllocateLocalSurfaceIdForCurrentSize(); return client_layer_tree_frame_sink; } @@ -755,10 +768,9 @@ viz::SurfaceId(window_->GetFrameSinkId(), GetLocalSurfaceIdAllocation().local_surface_id()); - if (!client_surface_embedder_) { - client_surface_embedder_ = std::make_unique<ClientSurfaceEmbedder>( - window_, /* inject_gutter */ false, gfx::Insets()); - } + // ClientSurfaceEmbedder is only applicable if we have an actual embedding. + if (!has_embedding_) + return; client_surface_embedder_->SetSurfaceId(primary_surface_id_); client_surface_embedder_->UpdateSizeAndGutters();
diff --git a/ui/aura/mus/window_port_mus.h b/ui/aura/mus/window_port_mus.h index 14f60e5..20699b5 100644 --- a/ui/aura/mus/window_port_mus.h +++ b/ui/aura/mus/window_port_mus.h
@@ -240,6 +240,9 @@ PropertyConverter* GetPropertyConverter(); + // Calls GetOrAllocateLocalSurfaceId() with the current size. + void GetOrAllocateLocalSurfaceIdForCurrentSize(); + // WindowMus: Window* GetWindow() override; void AddChildFromServer(WindowMus* window) override;
diff --git a/ui/aura/mus/window_port_mus_unittest.cc b/ui/aura/mus/window_port_mus_unittest.cc index 161ec145..8032ada 100644 --- a/ui/aura/mus/window_port_mus_unittest.cc +++ b/ui/aura/mus/window_port_mus_unittest.cc
@@ -90,7 +90,7 @@ Window window(nullptr); window.Init(ui::LAYER_NOT_DRAWN); window.SetBounds(gfx::Rect(300, 300)); - window.SetEmbedFrameSinkId(viz::FrameSinkId(0, 1)); + WindowPortMusTestHelper(&window).SimulateEmbedding(); // Allocate a new LocalSurfaceId. The ui::Layer should be updated. window.AllocateLocalSurfaceId(); @@ -110,7 +110,7 @@ window.set_owned_by_parent(false); window.SetBounds(gfx::Rect(300, 300)); // Simulate an embedding. - window.SetEmbedFrameSinkId(viz::FrameSinkId(0, 1)); + WindowPortMusTestHelper(&window).SimulateEmbedding(); root_window()->AddChild(&window); // AckAllChanges() so that can verify a bounds change happens from @@ -201,4 +201,17 @@ EXPECT_EQ(Window::OcclusionState::HIDDEN, window.occlusion_state()); } +TEST_F(WindowPortMusTest, PrepareForEmbed) { + Window window(nullptr); + window.Init(ui::LAYER_NOT_DRAWN); + window.set_owned_by_parent(false); + window.SetBounds(gfx::Rect(400, 300)); + + WindowPortMusTestHelper helper(&window); + helper.SimulateEmbedding(); + auto* window_mus = WindowPortMus::Get(&window); + ASSERT_TRUE(window_mus->client_surface_embedder()); + EXPECT_TRUE(window_mus->client_surface_embedder()->HasPrimarySurfaceId()); +} + } // namespace aura
diff --git a/ui/aura/mus/window_tree_client_unittest.cc b/ui/aura/mus/window_tree_client_unittest.cc index 03c3b55..88ba2d1e 100644 --- a/ui/aura/mus/window_tree_client_unittest.cc +++ b/ui/aura/mus/window_tree_client_unittest.cc
@@ -283,14 +283,14 @@ TEST_P(WindowTreeClientTestSurfaceSync, ClientSurfaceEmbedderCreated) { Window window(nullptr); window.Init(ui::LAYER_NOT_DRAWN); - WindowPortMusTestHelper(&window).SimulateEmbedding(); WindowPortMus* window_port_mus = WindowPortMus::Get(&window); - ASSERT_NE(nullptr, window_port_mus); + ASSERT_TRUE(window_port_mus); - // A ClientSurfaceEmbedder is only created once there is bounds and a - // FrameSinkId. + // A ClientSurfaceEmbedder is only created once there is an embedding. EXPECT_EQ(nullptr, window_port_mus->client_surface_embedder()); + WindowPortMusTestHelper(&window).SimulateEmbedding(); + gfx::Rect new_bounds(gfx::Rect(0, 0, 100, 100)); ASSERT_NE(new_bounds, window.bounds()); window.SetBounds(new_bounds);
diff --git a/ui/aura/test/mus/window_port_mus_test_helper.cc b/ui/aura/test/mus/window_port_mus_test_helper.cc index 55d8002..18e053dd 100644 --- a/ui/aura/test/mus/window_port_mus_test_helper.cc +++ b/ui/aura/test/mus/window_port_mus_test_helper.cc
@@ -23,6 +23,7 @@ void WindowPortMusTestHelper::SimulateEmbedding() { window_port_mus_->GetWindow()->SetEmbedFrameSinkId( viz::FrameSinkId(next_client_id_++, 1)); + window_port_mus_->PrepareForEmbed(); } base::WeakPtr<cc::LayerTreeFrameSink> WindowPortMusTestHelper::GetFrameSink() {
diff --git a/ui/base/ime/chromeos/component_extension_ime_manager.cc b/ui/base/ime/chromeos/component_extension_ime_manager.cc index c2afaff..ad5c791f 100644 --- a/ui/base/ime/chromeos/component_extension_ime_manager.cc +++ b/ui/base/ime/chromeos/component_extension_ime_manager.cc
@@ -37,6 +37,7 @@ "es(cat)", "fi", "fr", + "fr(bepo)", "fr(oss)", "gb(dvorak)", "gb(extd)",
diff --git a/ui/events/mojo/event_constants.mojom b/ui/events/mojo/event_constants.mojom index fd0356c..234a0d7 100644 --- a/ui/events/mojo/event_constants.mojom +++ b/ui/events/mojo/event_constants.mojom
@@ -17,6 +17,7 @@ KEY_PRESSED, KEY_RELEASED, GESTURE_TAP, + GESTURE_SWIPE, SCROLL, SCROLL_FLING_START, SCROLL_FLING_CANCEL, @@ -89,4 +90,4 @@ MAY_BEGIN, INERTIAL_UPDATE, END, -}; \ No newline at end of file +};
diff --git a/ui/events/mojo/event_struct_traits.cc b/ui/events/mojo/event_struct_traits.cc index ca6e276..5d569237 100644 --- a/ui/events/mojo/event_struct_traits.cc +++ b/ui/events/mojo/event_struct_traits.cc
@@ -117,6 +117,8 @@ return ui::mojom::EventType::KEY_RELEASED; case ui::ET_GESTURE_TAP: return ui::mojom::EventType::GESTURE_TAP; + case ui::ET_GESTURE_SWIPE: + return ui::mojom::EventType::GESTURE_SWIPE; case ui::ET_SCROLL: return ui::mojom::EventType::SCROLL; case ui::ET_SCROLL_FLING_START: @@ -169,6 +171,8 @@ return ui::ET_KEY_RELEASED; case ui::mojom::EventType::GESTURE_TAP: return ui::ET_GESTURE_TAP; + case ui::mojom::EventType::GESTURE_SWIPE: + return ui::ET_GESTURE_SWIPE; case ui::mojom::EventType::SCROLL: return ui::ET_SCROLL; case ui::mojom::EventType::SCROLL_FLING_START: @@ -357,6 +361,7 @@ break; } case ui::mojom::EventType::GESTURE_TAP: + case ui::mojom::EventType::GESTURE_SWIPE: if (!ReadGestureData(&event, time_stamp, out)) return false; break;
diff --git a/ui/file_manager/file_manager/common/js/BUILD.gn b/ui/file_manager/file_manager/common/js/BUILD.gn index f62d12e..31581662e 100644 --- a/ui/file_manager/file_manager/common/js/BUILD.gn +++ b/ui/file_manager/file_manager/common/js/BUILD.gn
@@ -75,6 +75,14 @@ ] } +js_unittest("file_type_unittest") { + deps = [ + ":file_type", + ":mock_entry", + "//ui/file_manager/base/js:test_error_reporting", + ] +} + # These importer files actually belong here. Nothing outside the Files app uses # them, so restrict visibility. TODO(tapted): Simplify visibility when # everything else moves to //ui/file_manager/base. @@ -191,6 +199,7 @@ js_unit_tests("unit_tests") { deps = [ ":async_util_unittest", + ":file_type_unittest", ":files_app_entry_types_unittest", ":importer_common_unittest", ":lru_cache_unittest",
diff --git a/ui/file_manager/file_manager/common/js/file_type.js b/ui/file_manager/file_manager/common/js/file_type.js index a5027f3..b652012 100644 --- a/ui/file_manager/file_manager/common/js/file_type.js +++ b/ui/file_manager/file_manager/common/js/file_type.js
@@ -584,10 +584,34 @@ /** * @param {Entry|VolumeEntry} entry Reference to the file. * @param {string=} opt_mimeType Optional mime type for the file. + * @param {VolumeManagerCommon.RootType=} opt_rootType The root type of the + * entry. * @return {string} Returns string that represents the file icon. * It refers to a file 'images/filetype_' + icon + '.png'. */ -FileType.getIcon = function(entry, opt_mimeType) { +FileType.getIcon = function(entry, opt_mimeType, opt_rootType) { const fileType = FileType.getType(entry, opt_mimeType); - return entry.iconName || fileType.icon || fileType.type || 'unknown'; + const overridenIcon = FileType.getIconOverrides(entry, opt_rootType); + return entry.iconName || overridenIcon || fileType.icon || fileType.type || + 'unknown'; +}; + +/** + * Returns a string to be used as an attribute value to customize the entry + * icon. + * + * @param {Entry|FilesAppEntry} entry + * @param {VolumeManagerCommon.RootType=} opt_rootType The root type of the + * entry. + * @return {string} + */ +FileType.getIconOverrides = function(entry, opt_rootType) { + // Overrides per RootType and defined by fullPath. + const overrides = { + [VolumeManagerCommon.RootType.DOWNLOADS]: { + '/Downloads': VolumeManagerCommon.VolumeType.DOWNLOADS, + }, + }; + const root = overrides[opt_rootType]; + return root ? root[entry.fullPath] : ''; };
diff --git a/ui/file_manager/file_manager/common/js/file_type_unittest.js b/ui/file_manager/file_manager/common/js/file_type_unittest.js new file mode 100644 index 0000000..c34645c0 --- /dev/null +++ b/ui/file_manager/file_manager/common/js/file_type_unittest.js
@@ -0,0 +1,39 @@ +// 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. + +'use strict'; + +/* + * Tests that Downloads icon is customized within Downloads root, but not in + * others. + */ +function testDownloadsIcon() { + const fileSystem = new MockFileSystem('fake-fs'); + const filenames = [ + '/folder/', + '/folder/file_a.txt', + '/Downloads/', + '/Downloads/file_b.txt', + ]; + fileSystem.populate(filenames); + + const folder = fileSystem.entries['/folder']; + const fileA = fileSystem.entries['/folder/file_a.txt']; + const downloads = fileSystem.entries['/Downloads']; + const fileB = fileSystem.entries['/Downloads/file_b.txt']; + + const downloadsRoot = VolumeManagerCommon.RootType.DOWNLOADS; + const driveRoot = VolumeManagerCommon.RootType.DRIVE; + const androidRoot = VolumeManagerCommon.RootType.ANDROID_FILES; + + const mimetype = undefined; + assertEquals('folder', FileType.getIcon(folder, mimetype, downloadsRoot)); + assertEquals('text', FileType.getIcon(fileA, mimetype, downloadsRoot)); + assertEquals('text', FileType.getIcon(fileB, mimetype, downloadsRoot)); + + assertEquals( + 'downloads', FileType.getIcon(downloads, mimetype, downloadsRoot)); + assertEquals('folder', FileType.getIcon(downloads, mimetype, driveRoot)); + assertEquals('folder', FileType.getIcon(downloads, mimetype, androidRoot)); +}
diff --git a/ui/file_manager/file_manager/common/js/files_app_entry_types.js b/ui/file_manager/file_manager/common/js/files_app_entry_types.js index 792baa4..71ad13a 100644 --- a/ui/file_manager/file_manager/common/js/files_app_entry_types.js +++ b/ui/file_manager/file_manager/common/js/files_app_entry_types.js
@@ -579,7 +579,10 @@ * @override */ createReader() { - const readers = [this.rootEntry_.createReader()]; + const readers = []; + if (this.rootEntry_) + readers.push(this.rootEntry_.createReader()); + if (this.children_.length) readers.push(new StaticReader(this.children_));
diff --git a/ui/file_manager/file_manager/common/js/files_app_entry_types_unittest.js b/ui/file_manager/file_manager/common/js/files_app_entry_types_unittest.js index 4bba80f..597bb9eb 100644 --- a/ui/file_manager/file_manager/common/js/files_app_entry_types_unittest.js +++ b/ui/file_manager/file_manager/common/js/files_app_entry_types_unittest.js
@@ -384,6 +384,47 @@ testReportCallback); } +/** Tests VolumeEntry createReader when root entry isn't resolved yet. */ +function testVolumeEntryCreateReaderUnresolved(testReportCallback) { + // A VolumeInfo that doesn't resolve the display root. + const fakeVolumeInfo = /** @type{!VolumeInfo} */ ({ + displayRoot: null, + label: 'Fake Filesystem label', + volumeType: VolumeManagerCommon.VolumeType.DOWNLOADS, + resolveDisplayRoot: (successCallback, errorCallback) => { + // Do nothing here. + }, + }); + + const volumeEntry = new VolumeEntry(fakeVolumeInfo); + const crostini = fakeVolumeEntry(VolumeManagerCommon.VolumeType.CROSTINI); + const android = fakeVolumeEntry(VolumeManagerCommon.VolumeType.ANDROID_FILES); + + volumeEntry.addEntry(crostini); + volumeEntry.addEntry(android); + const reader = volumeEntry.createReader(); + + const readFiles = []; + const accumulateResults = (readerResult) => { + readerResult.map((f) => readFiles.push(f)); + if (readerResult.length > 0) + reader.readEntries(accumulateResults); + }; + + reader.readEntries(accumulateResults); + // readEntries runs asynchronously, so let's wait it to be called. + reportPromise( + waitUntil(() => { + return readFiles.length >= 2; + }).then(() => { + // Now we can check the final result. + assertEquals(2, readFiles.length); + assertEquals(crostini, readFiles[0]); + assertEquals(android, readFiles[1]); + }), + testReportCallback); +} + /** * Tests VolumeEntry getFile and getDirectory methods. */ @@ -435,6 +476,7 @@ }), testReportCallback); } + /** Tests VolumeEntry.getParent */ function testVolumeEntryGetParent(testReportCallback) { const volumeEntry = fakeVolumeEntry(null);
diff --git a/ui/file_manager/file_manager/common/js/util.js b/ui/file_manager/file_manager/common/js/util.js index 558544697..5c122bcb 100644 --- a/ui/file_manager/file_manager/common/js/util.js +++ b/ui/file_manager/file_manager/common/js/util.js
@@ -883,6 +883,19 @@ }; /** + * Compare by label (i18n name). The 2 entries must be in same directory. + * @param {EntryLocation} locationInfo + * @param {!Entry|!FilesAppEntry} entry1 First entry. + * @param {!Entry|!FilesAppEntry} entry2 Second entry. + * @return {number} Compare result. + */ +util.compareLabel = function(locationInfo, entry1, entry2) { + return util.collator.compare( + util.getEntryLabel(locationInfo, entry1), + util.getEntryLabel(locationInfo, entry2)); +}; + +/** * Compare by path. * @param {Entry|FilesAppEntry} entry1 First entry. * @param {Entry|FilesAppEntry} entry2 Second entry. @@ -893,13 +906,14 @@ }; /** + * @param {EntryLocation} locationInfo * @param {!Array<Entry|FilesAppEntry>} bottomEntries entries that should be * grouped in the bottom, used for sorting Linux and Play files entries after * other folders in MyFiles. * return {function(Entry|FilesAppEntry, Entry|FilesAppEntry) to compare entries * by name. */ -util.compareNameAndGroupBottomEntries = function(bottomEntries) { +util.compareLabelAndGroupBottomEntries = function(locationInfo, bottomEntries) { const childrenMap = new Map(); bottomEntries.forEach((entry) => { childrenMap.set(entry.toURL(), entry); @@ -918,9 +932,9 @@ const isBottomlEntry1 = childrenMap.has(entry1.toURL()) ? 1 : 0; const isBottomlEntry2 = childrenMap.has(entry2.toURL()) ? 1 : 0; - // When there are the same type, just compare by name. + // When there are the same type, just compare by label. if (isBottomlEntry1 === isBottomlEntry2) - return util.compareName(entry1, entry2); + return util.compareLabel(locationInfo, entry1, entry2); return isBottomlEntry1 - isBottomlEntry2; } @@ -1241,17 +1255,24 @@ }; /** - * Returns the localized name of the entry. + * Returns the localized/i18n name of the entry. * * @param {EntryLocation} locationInfo - * @param {!Entry|!FakeEntry} entry The entry to be retrieve the name of. - * @return {?string} The localized name. + * @param {!Entry|!FilesAppEntry} entry The entry to be retrieve the name of. + * @return {string} The localized name. */ util.getEntryLabel = function(locationInfo, entry) { if (locationInfo && locationInfo.hasFixedLabel) return util.getRootTypeLabel(locationInfo); - else - return entry.name; + + // Special case for MyFiles/Downloads. + if (locationInfo && util.isMyFilesVolumeEnabled() && + locationInfo.rootType == VolumeManagerCommon.RootType.DOWNLOADS && + entry.fullPath == '/Downloads') { + return str('DOWNLOADS_DIRECTORY_LABEL'); + } + + return entry.name; }; /**
diff --git a/ui/file_manager/file_manager/foreground/js/directory_contents.js b/ui/file_manager/file_manager/foreground/js/directory_contents.js index c20d966..e331189 100644 --- a/ui/file_manager/file_manager/foreground/js/directory_contents.js +++ b/ui/file_manager/file_manager/foreground/js/directory_contents.js
@@ -530,9 +530,10 @@ * * @param {FileFilter} fileFilter The file-filter context. * @param {!MetadataModel} metadataModel + * @param {!VolumeManager} volumeManager The volume manager. * @constructor */ -function FileListContext(fileFilter, metadataModel) { +function FileListContext(fileFilter, metadataModel, volumeManager) { /** * @type {FileListModel} */ @@ -554,6 +555,9 @@ * @const */ this.prefetchPropertyNames = FileListContext.createPrefetchPropertyNames_(); + + /** @public {!VolumeManager} */ + this.volumeManager = volumeManager; } /** @@ -601,8 +605,12 @@ isSearch, directoryEntry, scannerFactory) { + /** @private {FileListContext} */ this.context_ = context; + + /** @private {FileListModel} */ this.fileList_ = context.fileList; + this.fileList_.InitNewDirContents(context.volumeManager); this.isSearch_ = isSearch; this.directoryEntry_ = directoryEntry; @@ -637,14 +645,19 @@ }; /** + * Returns the file list length. + * @return {number} + */ +DirectoryContents.prototype.getFileListLength = function() { + return this.fileList_.length; +}; + +/** * Use a given fileList instead of the fileList from the context. - * @param {(!Array|!cr.ui.ArrayDataModel)} fileList The new file list. + * @param {!FileListModel} fileList The new file list. */ DirectoryContents.prototype.setFileList = function(fileList) { - if (fileList instanceof cr.ui.ArrayDataModel) - this.fileList_ = fileList; - else - this.fileList_ = new cr.ui.ArrayDataModel(fileList); + this.fileList_ = fileList; }; /**
diff --git a/ui/file_manager/file_manager/foreground/js/directory_model.js b/ui/file_manager/file_manager/foreground/js/directory_model.js index 03cc365..9f227205 100644 --- a/ui/file_manager/file_manager/foreground/js/directory_model.js +++ b/ui/file_manager/file_manager/foreground/js/directory_model.js
@@ -48,7 +48,7 @@ this.onFilterChanged_.bind(this)); this.currentFileListContext_ = - new FileListContext(fileFilter, metadataModel); + new FileListContext(fileFilter, metadataModel, volumeManager); this.currentDirContents_ = DirectoryContents.createForDirectory(this.currentFileListContext_, null); /** @@ -472,7 +472,7 @@ } var dirContents = this.currentDirContents_.clone(); - dirContents.setFileList([]); + dirContents.setFileList(new FileListModel(this.metadataModel_)); dirContents.setMetadataSnapshot( this.currentDirContents_.createMetadataSnapshot()); @@ -698,8 +698,8 @@ if (volumeInfo && volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DOWNLOADS && locationInfo.isRootEntry) { - metrics.recordMediumCount('DownloadsCount', - dirContents.fileList_.length); + metrics.recordMediumCount( + 'DownloadsCount', dirContents.getFileListLength()); } }
diff --git a/ui/file_manager/file_manager/foreground/js/file_list_model.js b/ui/file_manager/file_manager/foreground/js/file_list_model.js index ec76b928..02a97be 100644 --- a/ui/file_manager/file_manager/foreground/js/file_list_model.js +++ b/ui/file_manager/file_manager/foreground/js/file_list_model.js
@@ -57,6 +57,15 @@ * @private {boolean} */ this.useModificationByMeTime_ = false; + + /** @private {VolumeManager} The volume manager. */ + this.volumeManager_ = null; + + /** + * @private {EntryLocation} Used to get the label for entries when sorting by + * label. + */ + this.locationInfo_ = null; } /** @@ -328,6 +337,25 @@ }; /** + * Compares entries by label (i18n name). + * @param {!Entry} a First entry. + * @param {!Entry} b Second entry. + * @return {number} Compare result. + * @private + */ +FileListModel.prototype.compareLabel_ = function(a, b) { + // Set locationInfo once because we only compare within the same volume. + if (!this.locationInfo_ && this.volumeManager_) + this.locationInfo_ = this.volumeManager_.getLocationInfo(a); + + // Directories always precede files. + if (a.isDirectory !== b.isDirectory) + return a.isDirectory === this.isDescendingOrder_ ? 1 : -1; + + return util.compareLabel(this.locationInfo_, a, b); +}; + +/** * Compares entries by mtime first, then by name. * @param {Entry} a First entry. * @param {Entry} b Second entry. @@ -407,3 +435,16 @@ var result = util.collator.compare(aType, bType); return result !== 0 ? result : util.compareName(a, b); }; + +/** + * @param {!VolumeManager} volumeManager The volume manager. + */ +FileListModel.prototype.InitNewDirContents = function(volumeManager) { + this.volumeManager_ = volumeManager; + // Clear the location info, it's reset by compareLabel_ when needed. + this.locationInfo_ = null; + // Initialize compare function based on Labels. + this.setCompareFunction( + 'name', + /** @type {function(*, *): number} */ (this.compareLabel_.bind(this))); +};
diff --git a/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js b/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js index 33a5a28..d6a95a44 100644 --- a/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js +++ b/ui/file_manager/file_manager/foreground/js/file_transfer_controller.js
@@ -1653,16 +1653,22 @@ this.preloadThumbnailImage_(entries[0]); } - this.metadataModel_.get(entries, ['externalFileUrl']).then( - function(metadataList) { + this.metadataModel_ + .get(entries, ['alternateUrl', 'externalFileUrl', 'hosted']) + .then(function(metadataList) { // |Copy| is the only menu item affected by allDriveFilesAvailable_. // It could be open right now, update its UI. this.copyCommand_.disabled = !this.canCutOrCopy_(false /* not move operation */); for (var i = 0; i < entries.length; i++) { if (entries[i].isFile) { - asyncData[entries[i].toURL()].externalFileUrl = - metadataList[i].externalFileUrl; + if (metadataList[i].hosted) { + asyncData[entries[i].toURL()].externalFileUrl = + metadataList[i].alternateUrl; + } else { + asyncData[entries[i].toURL()].externalFileUrl = + metadataList[i].externalFileUrl; + } } } }.bind(this));
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/external_metadata_provider.js b/ui/file_manager/file_manager/foreground/js/metadata/external_metadata_provider.js index b275e65..b6746f05 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/external_metadata_provider.js +++ b/ui/file_manager/file_manager/foreground/js/metadata/external_metadata_provider.js
@@ -18,6 +18,7 @@ * @const {!Array<string>} */ ExternalMetadataProvider.PROPERTY_NAMES = [ + 'alternateUrl', 'availableOffline', 'availableWhenMetered', 'contentMimeType', @@ -90,6 +91,8 @@ for (var i = 0; i < propertiesList.length; i++) { var prop = propertiesList[i]; var item = new MetadataItem(); + if (prop.alternateUrl !== undefined || nameMap['alternateUrl']) + item.alternateUrl = prop.alternateUrl; if (prop.availableOffline !== undefined || nameMap['availableOffline']) item.availableOffline = prop.availableOffline; if (prop.availableWhenMetered !== undefined ||
diff --git a/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js b/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js index 2906f6b..649a7ca1 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js +++ b/ui/file_manager/file_manager/foreground/js/metadata_box_controller.js
@@ -109,7 +109,7 @@ return; this.metadataModel_ .get([entry], MetadataBoxController.GENERAL_METADATA_NAME.concat([ - 'hosted', 'externalFileUrl' + 'alternateUrl', 'externalFileUrl', 'hosted' ])) .then(this.onGeneralMetadataLoaded_.bind(this, entry, isSameEntry)); }; @@ -144,7 +144,7 @@ this.fileMetadataFormatter_.formatModDate(item.modificationTime); } - if (item.externalFileUrl) { + if (item.externalFileUrl || item.alternateUrl) { this.metadataModel_.get([entry], ['contentMimeType']).then(function(items) { var item = items[0]; this.metadataBox_.mediaMimeType = item.contentMimeType; @@ -157,7 +157,7 @@ } if (['image', 'video', 'audio'].includes(type)) { - if (item.externalFileUrl) { + if (item.externalFileUrl || item.alternateUrl) { this.metadataModel_.get([entry], ['imageHeight', 'imageWidth']) .then(function(items) { var item = items[0];
diff --git a/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js b/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js index 33a7753..ff4a9b7 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js +++ b/ui/file_manager/file_manager/foreground/js/ui/directory_tree.js
@@ -5,25 +5,6 @@ // Namespace const directorytree = {}; -/** - * Returns a string to be used as an attribute value to customize the entry - * icon. - * - * @param {VolumeManagerCommon.RootType} rootType The root type to entry. - * @param {Entry|FilesAppEntry} entry - * @return {string} a string - */ -directorytree.getIconOverrides = function(rootType, entry) { - // Overrides per RootType and defined by fullPath. - const overrides = { - [VolumeManagerCommon.RootType.DOWNLOADS]: { - '/Downloads': VolumeManagerCommon.VolumeType.DOWNLOADS, - }, - }; - const root = overrides[rootType]; - return root ? root[entry.fullPath] : null; -}; - //////////////////////////////////////////////////////////////////////////////// // DirectoryTreeBase @@ -679,7 +660,7 @@ } } else { const rootType = location.rootType || null; - const iconOverride = directorytree.getIconOverrides(rootType, dirEntry); + const iconOverride = FileType.getIconOverrides(dirEntry, rootType); // Add Downloads icon as volume so current test code passes with // MyFilesVolume flag enabled and disabled. if (iconOverride) @@ -808,9 +789,15 @@ if (!this.entry) return DirectoryItem.prototype.sortEntries.apply(this, [entries]); + // Use locationInfo from first entry because it only compare within the same + // volume. + const locationInfo = + this.parentTree_.volumeManager_.getLocationInfo(entries[0]); + const compareFunction = util.compareLabelAndGroupBottomEntries( + locationInfo, this.entry.getUIChildren()); + const filter = this.fileFilter_.filter.bind(this.fileFilter_); - return entries.filter(filter).sort( - util.compareNameAndGroupBottomEntries(this.entry.getUIChildren())); + return entries.filter(filter).sort(compareFunction); }; /**
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_grid.js b/ui/file_manager/file_manager/foreground/js/ui/file_grid.js index 18441e4..88648a94 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_grid.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_grid.js
@@ -571,15 +571,17 @@ bottom.className = 'thumbnail-bottom'; var mimeType = this.metadataModel_.getCache( [entry], ['contentMimeType'])[0].contentMimeType; + const locationInfo = this.volumeManager_.getLocationInfo(entry); var detailIcon = filelist.renderFileTypeIcon( - li.ownerDocument, entry, mimeType); + li.ownerDocument, entry, locationInfo, mimeType); if (isDirectory) { var checkmark = li.ownerDocument.createElement('div'); checkmark.className = 'detail-checkmark'; detailIcon.appendChild(checkmark); } bottom.appendChild(detailIcon); - bottom.appendChild(filelist.renderFileNameLabel(li.ownerDocument, entry)); + bottom.appendChild( + filelist.renderFileNameLabel(li.ownerDocument, entry, locationInfo)); frame.appendChild(bottom); this.updateSharedStatus_(li, entry);
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_table.js b/ui/file_manager/file_manager/foreground/js/ui/file_table.js index 512338e..1f9fa2d 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_table.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_table.js
@@ -730,7 +730,9 @@ var mimeType = this.metadataModel_.getCache([entry], ['contentMimeType'])[0].contentMimeType; - var icon = filelist.renderFileTypeIcon(this.ownerDocument, entry, mimeType); + const locationInfo = this.volumeManager_.getLocationInfo(entry); + var icon = filelist.renderFileTypeIcon( + this.ownerDocument, entry, locationInfo, mimeType); if (FileType.isImage(entry, mimeType) || FileType.isVideo(entry, mimeType) || FileType.isAudio(entry, mimeType) || FileType.isRaw(entry, mimeType)) { icon.appendChild(this.renderThumbnail_(entry)); @@ -740,7 +742,8 @@ label.entry = entry; label.className = 'detail-name'; - label.appendChild(filelist.renderFileNameLabel(this.ownerDocument, entry)); + label.appendChild( + filelist.renderFileNameLabel(this.ownerDocument, entry, locationInfo)); return label; };
diff --git a/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js b/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js index 70de83c..18eea5c 100644 --- a/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js +++ b/ui/file_manager/file_manager/foreground/js/ui/file_table_list.js
@@ -123,7 +123,7 @@ /** * Common item decoration for table's and grid's items. * @param {cr.ui.ListItem} li List item. - * @param {Entry} entry The entry. + * @param {Entry|FilesAppEntry} entry The entry. * @param {!MetadataModel} metadataModel Cache to * retrieve metadada. */ @@ -169,30 +169,34 @@ * Render the type column of the detail table. * @param {!Document} doc Owner document. * @param {!Entry} entry The Entry object to render. + * @param {EntryLocation} locationInfo * @param {string=} opt_mimeType Optional mime type for the file. * @return {!HTMLDivElement} Created element. */ -filelist.renderFileTypeIcon = function(doc, entry, opt_mimeType) { +filelist.renderFileTypeIcon = function(doc, entry, locationInfo, opt_mimeType) { var icon = /** @type {!HTMLDivElement} */ (doc.createElement('div')); icon.className = 'detail-icon'; - icon.setAttribute('file-type-icon', FileType.getIcon(entry, opt_mimeType)); + icon.setAttribute( + 'file-type-icon', + FileType.getIcon(entry, opt_mimeType, locationInfo.rootType)); return icon; }; /** * Render filename label for grid and list view. * @param {!Document} doc Owner document. - * @param {!Entry} entry The Entry object to render. + * @param {!Entry|!FilesAppEntry} entry The Entry object to render. + * @param {EntryLocation} locationInfo * @return {!HTMLDivElement} The label. */ -filelist.renderFileNameLabel = function(doc, entry) { +filelist.renderFileNameLabel = function(doc, entry, locationInfo) { // Filename need to be in a '.filename-label' container for correct // work of inplace renaming. var box = /** @type {!HTMLDivElement} */ (doc.createElement('div')); box.className = 'filename-label'; var fileName = doc.createElement('span'); fileName.className = 'entry-name'; - fileName.textContent = entry.name; + fileName.textContent = util.getEntryLabel(locationInfo, entry); box.appendChild(fileName); return box;
diff --git a/ui/file_manager/integration_tests/file_manager/quick_view.js b/ui/file_manager/integration_tests/file_manager/quick_view.js index 692583c..346e4976 100644 --- a/ui/file_manager/integration_tests/file_manager/quick_view.js +++ b/ui/file_manager/integration_tests/file_manager/quick_view.js
@@ -109,6 +109,19 @@ // Open the file in Quick View. await openQuickView(appId, ENTRIES.hello.nameText); + + // Check that the correct mime type is displayed. + const mimeTypeSelector = [ + '#quick-view', + '#metadata-box', + // TODO(crbug.com/677338): Replace the attribute selector with key="Type" + // once the key is populated with polymer2 enabled. + 'files-metadata-entry[i18n-values="key:METADATA_BOX_MEDIA_MIME_TYPE"]', + '#value div', + ]; + chrome.test.assertEq( + 'text/plain', + (await remoteCall.waitForElement(appId, mimeTypeSelector)).text); }; /**
diff --git a/ui/views_bridge_mac/bridged_native_widget_impl.mm b/ui/views_bridge_mac/bridged_native_widget_impl.mm index eb29cc6..593e8a2 100644 --- a/ui/views_bridge_mac/bridged_native_widget_impl.mm +++ b/ui/views_bridge_mac/bridged_native_widget_impl.mm
@@ -1039,7 +1039,12 @@ } bool BridgedNativeWidgetImpl::RedispatchKeyEvent(NSEvent* event) { - return [[window_ commandDispatcher] redispatchKeyEvent:event]; + NSWindow* window = ns_window(); + DCHECK([window.class conformsToProtocol:@protocol(CommandDispatchingWindow)]); + NSObject<CommandDispatchingWindow>* command_dispatching_window = + base::mac::ObjCCastStrict<NSObject<CommandDispatchingWindow>>(window); + return + [[command_dispatching_window commandDispatcher] redispatchKeyEvent:event]; } NSWindow* BridgedNativeWidgetImpl::ns_window() {
diff --git a/ui/webui/resources/cr_elements/icons.html b/ui/webui/resources/cr_elements/icons.html index fda872d..6f1e8ee6 100644 --- a/ui/webui/resources/cr_elements/icons.html +++ b/ui/webui/resources/cr_elements/icons.html
@@ -53,6 +53,7 @@ <g id="fullscreen"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"></path></g> <g id="group"><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"></path></g> <g id="info"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"></path></g> + <g id="insert-drive-file"><path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z"></path></g> <g id="more-vert"><path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"></path></g> <g id="open-in-new"><path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"></path></g> <g id="person"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"></path></g>
diff --git a/ui/webui/resources/js/icon.js b/ui/webui/resources/js/icon.js index ef025e7..e38c481 100644 --- a/ui/webui/resources/js/icon.js +++ b/ui/webui/resources/js/icon.js
@@ -31,6 +31,16 @@ } /** + * A URL for the filetype icon for |filePath|. OS and theme dependent. + * @param {string} filePath + * @return {string} + */ + function getFileIconUrl(filePath) { + return 'chrome://fileicon/' + encodeURIComponent(filePath) + + '?scale=' + window.devicePixelRatio + 'x'; + } + + /** * Generates a CSS -webkit-image-set for a chrome:// url. * An entry in the image set is added for each of getSupportedScaleFactors(). * The scale-factor-specific url is generated by replacing the first instance @@ -100,5 +110,6 @@ return { getImage: getImage, getFavicon: getFavicon, + getFileIconUrl: getFileIconUrl, }; });
diff --git a/url/url_util.cc b/url/url_util.cc index 29cebf96..d56d041 100644 --- a/url/url_util.cc +++ b/url/url_util.cc
@@ -799,9 +799,10 @@ charset_converter, output, out_parsed); } -DecodeURLResult DecodeURLEscapeSequences(const char* input, - int length, - CanonOutputW* output) { +void DecodeURLEscapeSequences(const char* input, + int length, + DecodeURLMode mode, + CanonOutputW* output) { RawCanonOutputT<char> unescaped_chars; for (int i = 0; i < length; i++) { if (input[i] == '%') { @@ -819,8 +820,6 @@ } int output_initial_length = output->length(); - bool did_utf8_decode = false; - bool did_isomorphic_decode = false; // Convert that 8-bit to UTF-16. It's not clear IE does this at all to // JavaScript URLs, but Firefox and Safari do. for (int i = 0; i < unescaped_chars.length(); i++) { @@ -838,28 +837,22 @@ // Valid UTF-8 character, convert to UTF-16. AppendUTF16Value(code_point, output); i = next_character; - did_utf8_decode = true; + } else if (mode == DecodeURLMode::kUTF8) { + DCHECK_EQ(code_point, 0xFFFDU); + AppendUTF16Value(code_point, output); + i = next_character; } else { // If there are any sequences that are not valid UTF-8, we // revert |output| changes, and promote any bytes to UTF-16. We // copy all characters from the beginning to the end of the // identified sequence. output->set_length(output_initial_length); - did_utf8_decode = false; for (int j = 0; j < unescaped_chars.length(); ++j) output->push_back(static_cast<unsigned char>(unescaped_chars.at(j))); - did_isomorphic_decode = true; break; } } } - - DCHECK(!(did_utf8_decode && did_isomorphic_decode)); - if (did_isomorphic_decode) - return DecodeURLResult::kIsomorphic; - if (did_utf8_decode) - return DecodeURLResult::kUTF8; - return DecodeURLResult::kAsciiOnly; } void EncodeURIComponent(const char* input, int length, CanonOutput* output) {
diff --git a/url/url_util.h b/url/url_util.h index 4fd5c4f..0bd9f40 100644 --- a/url/url_util.h +++ b/url/url_util.h
@@ -276,23 +276,20 @@ // String helper functions ----------------------------------------------------- -enum class DecodeURLResult { - // Did not contain code points greater than 0x7F. - kAsciiOnly, - // Did UTF-8 decode only. +enum class DecodeURLMode { + // UTF-8 decode only. Invalid byte sequences are replaced with U+FFFD. kUTF8, - // Did byte to Unicode mapping only. - // https://infra.spec.whatwg.org/#isomorphic-decode - kIsomorphic, + // Try UTF-8 decoding. If the input contains byte sequences invalid + // for UTF-8, apply byte to Unicode mapping. + kUTF8OrIsomorphic, }; // Unescapes the given string using URL escaping rules. -// This function tries to decode non-ASCII characters in UTF-8 first, -// then in isomorphic encoding if UTF-8 decoding failed. COMPONENT_EXPORT(URL) -DecodeURLResult DecodeURLEscapeSequences(const char* input, - int length, - CanonOutputW* output); +void DecodeURLEscapeSequences(const char* input, + int length, + DecodeURLMode mode, + CanonOutputW* output); // Escapes the given string as defined by the JS method encodeURIComponent. See // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent
diff --git a/url/url_util_unittest.cc b/url/url_util_unittest.cc index 65f3435..437530a 100644 --- a/url/url_util_unittest.cc +++ b/url/url_util_unittest.cc
@@ -199,71 +199,83 @@ struct DecodeCase { const char* input; const char* output; - DecodeURLResult result; } decode_cases[] = { - {"hello, world", "hello, world", DecodeURLResult::kAsciiOnly}, + {"hello, world", "hello, world"}, {"%01%02%03%04%05%06%07%08%09%0a%0B%0C%0D%0e%0f/", - "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0B\x0C\x0D\x0e\x0f/", - DecodeURLResult::kAsciiOnly}, + "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0B\x0C\x0D\x0e\x0f/"}, {"%10%11%12%13%14%15%16%17%18%19%1a%1B%1C%1D%1e%1f/", - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1B\x1C\x1D\x1e\x1f/", - DecodeURLResult::kAsciiOnly}, + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1B\x1C\x1D\x1e\x1f/"}, {"%20%21%22%23%24%25%26%27%28%29%2a%2B%2C%2D%2e%2f/", - " !\"#$%&'()*+,-.//", DecodeURLResult::kAsciiOnly}, - {"%30%31%32%33%34%35%36%37%38%39%3a%3B%3C%3D%3e%3f/", "0123456789:;<=>?/", - DecodeURLResult::kAsciiOnly}, - {"%40%41%42%43%44%45%46%47%48%49%4a%4B%4C%4D%4e%4f/", "@ABCDEFGHIJKLMNO/", - DecodeURLResult::kAsciiOnly}, + " !\"#$%&'()*+,-.//"}, + {"%30%31%32%33%34%35%36%37%38%39%3a%3B%3C%3D%3e%3f/", + "0123456789:;<=>?/"}, + {"%40%41%42%43%44%45%46%47%48%49%4a%4B%4C%4D%4e%4f/", + "@ABCDEFGHIJKLMNO/"}, {"%50%51%52%53%54%55%56%57%58%59%5a%5B%5C%5D%5e%5f/", - "PQRSTUVWXYZ[\\]^_/", DecodeURLResult::kAsciiOnly}, - {"%60%61%62%63%64%65%66%67%68%69%6a%6B%6C%6D%6e%6f/", "`abcdefghijklmno/", - DecodeURLResult::kAsciiOnly}, + "PQRSTUVWXYZ[\\]^_/"}, + {"%60%61%62%63%64%65%66%67%68%69%6a%6B%6C%6D%6e%6f/", + "`abcdefghijklmno/"}, {"%70%71%72%73%74%75%76%77%78%79%7a%7B%7C%7D%7e%7f/", - "pqrstuvwxyz{|}~\x7f/", DecodeURLResult::kAsciiOnly}, - // Test un-UTF-8-ization. - {"%e4%bd%a0%e5%a5%bd", "\xe4\xbd\xa0\xe5\xa5\xbd", - DecodeURLResult::kUTF8}, + "pqrstuvwxyz{|}~\x7f/"}, + {"%e4%bd%a0%e5%a5%bd", "\xe4\xbd\xa0\xe5\xa5\xbd"}, }; for (size_t i = 0; i < arraysize(decode_cases); i++) { const char* input = decode_cases[i].input; RawCanonOutputT<base::char16> output; - EXPECT_EQ(decode_cases[i].result, - DecodeURLEscapeSequences(input, strlen(input), &output)); + DecodeURLEscapeSequences(input, strlen(input), + DecodeURLMode::kUTF8OrIsomorphic, &output); EXPECT_EQ(decode_cases[i].output, base::UTF16ToUTF8(base::string16(output.data(), output.length()))); + + RawCanonOutputT<base::char16> output_utf8; + DecodeURLEscapeSequences(input, strlen(input), DecodeURLMode::kUTF8, + &output_utf8); + EXPECT_EQ(decode_cases[i].output, + base::UTF16ToUTF8( + base::string16(output_utf8.data(), output_utf8.length()))); } // Our decode should decode %00 const char zero_input[] = "%00"; RawCanonOutputT<base::char16> zero_output; - DecodeURLEscapeSequences(zero_input, strlen(zero_input), &zero_output); + DecodeURLEscapeSequences(zero_input, strlen(zero_input), DecodeURLMode::kUTF8, + &zero_output); EXPECT_NE("%00", base::UTF16ToUTF8( base::string16(zero_output.data(), zero_output.length()))); // Test the error behavior for invalid UTF-8. - { - const char invalid_input[] = "%e4%a0%e5%a5%bd"; - const base::char16 invalid_expected[6] = {0x00e4, 0x00a0, 0x00e5, - 0x00a5, 0x00bd, 0}; - RawCanonOutputT<base::char16> invalid_output; - EXPECT_EQ(DecodeURLResult::kIsomorphic, - DecodeURLEscapeSequences(invalid_input, strlen(invalid_input), - &invalid_output)); - EXPECT_EQ(base::string16(invalid_expected), - base::string16(invalid_output.data(), invalid_output.length())); - } - { - const char invalid_input[] = "%e4%a0%e5%bd"; - const base::char16 invalid_expected[5] = {0x00e4, 0x00a0, 0x00e5, 0x00bd, - 0}; - RawCanonOutputT<base::char16> invalid_output; - EXPECT_EQ(DecodeURLResult::kIsomorphic, - DecodeURLEscapeSequences(invalid_input, strlen(invalid_input), - &invalid_output)); - EXPECT_EQ(base::string16(invalid_expected), - base::string16(invalid_output.data(), invalid_output.length())); + struct Utf8DecodeCase { + const char* input; + std::vector<base::char16> expected_iso; + std::vector<base::char16> expected_utf8; + } utf8_decode_cases[] = { + // %e5%a5%bd is a valid UTF-8 sequence. U+597D + {"%e4%a0%e5%a5%bd", + {0x00e4, 0x00a0, 0x00e5, 0x00a5, 0x00bd, 0}, + {0xfffd, 0x597d, 0}}, + {"%e5%a5%bd%e4%a0", + {0x00e5, 0x00a5, 0x00bd, 0x00e4, 0x00a0, 0}, + {0x597d, 0xfffd, 0}}, + {"%e4%a0%e5%bd", + {0x00e4, 0x00a0, 0x00e5, 0x00bd, 0}, + {0xfffd, 0xfffd, 0}}, + }; + + for (const auto& test : utf8_decode_cases) { + const char* input = test.input; + RawCanonOutputT<base::char16> output_iso; + DecodeURLEscapeSequences(input, strlen(input), + DecodeURLMode::kUTF8OrIsomorphic, &output_iso); + EXPECT_EQ(base::string16(test.expected_iso.data()), + base::string16(output_iso.data(), output_iso.length())); + + RawCanonOutputT<base::char16> output_utf8; + DecodeURLEscapeSequences(input, strlen(input), DecodeURLMode::kUTF8, + &output_utf8); + EXPECT_EQ(base::string16(test.expected_utf8.data()), + base::string16(output_utf8.data(), output_utf8.length())); } }
diff --git a/webrunner/net_http/http_service_unittest.cc b/webrunner/net_http/http_service_unittest.cc index b77d00f9..5b6d20b0 100644 --- a/webrunner/net_http/http_service_unittest.cc +++ b/webrunner/net_http/http_service_unittest.cc
@@ -35,7 +35,7 @@ public: HttpServiceTest() : task_environment_( - base::test::ScopedTaskEnvironment::MainThreadType::IO), + base::test::ScopedTaskEnvironment::MainThreadType::IO_MOCK_TIME), binding_(&http_service_server_) { // Initialize the test server. test_server_.AddDefaultHandlers(