diff --git a/DEPS b/DEPS index 72fca0b..791ed8b 100644 --- a/DEPS +++ b/DEPS
@@ -39,11 +39,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': '56fb57a05159b72a746ab534c3daf50d4220acef', + 'skia_revision': 'a5ab9ec295b2e6dca166775a98db67a9a8c18c37', # 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': '8bdb8d85f5f3a80fe966b4aba97a89c4f6f498ce', + 'v8_revision': 'f31c787725eb23f0771a8c98821fe240dcb534a8', # 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. @@ -51,7 +51,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': 'd8fa921572e43b5c46b28d99a3944a728e332f01', + 'angle_revision': '9cb1df4f4b34e53e5f37d6c99857a6fb8c8f360d', # 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. @@ -59,7 +59,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': '88aa3a76d309e8192a206e40d418294d89f35adb', + 'pdfium_revision': '5ad8474335798295a9c502999324635845d28ff7', # 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. @@ -67,7 +67,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. - 'boringssl_revision': '708db16463a21b922aed6d393ef74c3c5a366668', + 'boringssl_revision': '58218b63bc033782162168e1462c9c8890606885', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling nss # and whatever else without interference from each other. @@ -87,7 +87,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling NaCl # and whatever else without interference from each other. - 'nacl_revision': 'dd370db130c6c4f7d42230431eb9b9a030bd578b', + 'nacl_revision': '558343097fc08a80aa30bd525665905d636af3e5', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling dEQP # and whatever else without interference from each other. @@ -215,7 +215,7 @@ Var('chromium_git') + '/native_client/src/third_party/scons-2.0.1.git' + '@' + '1c1550e17fc26355d08627fbdec13d8291227067', 'src/third_party/webrtc': - Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + 'ea4df373b3daa4db9296fd90ad928d5c17dc6171', # commit position 11859 + Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + 'ea56a15c2228c9c57429ec6244bbe60a30318722', # commit position 11871 'src/third_party/openmax_dl': Var('chromium_git') + '/external/webrtc/deps/third_party/openmax.git' + '@' + Var('openmax_dl_revision'), @@ -270,7 +270,7 @@ 'src/third_party/catapult': Var('chromium_git') + '/external/github.com/catapult-project/catapult.git' + '@' + - '9880e484751ef3ed9873a17b604a5a6798032b2e', + '5528c88fc65d8bf58a26205bd370b93d8a267ff2', 'src/third_party/openh264/src': Var('chromium_git') + '/external/github.com/cisco/openh264' + '@' + 'b37cda248234162033e3e11b0335f3131cdfe488',
diff --git a/android_webview/native/aw_web_contents_delegate.cc b/android_webview/native/aw_web_contents_delegate.cc index 7fbec6f..3fa9571 100644 --- a/android_webview/native/aw_web_contents_delegate.cc +++ b/android_webview/native/aw_web_contents_delegate.cc
@@ -287,9 +287,10 @@ if (!url.is_valid()) continue; base::FilePath path(url.SchemeIsFile() ? - net::UnescapeURLComponent(url.path(), - net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS) : - file_path_str[i]); + net::UnescapeURLComponent(url.path(), + net::UnescapeRule::SPACES | + net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS) : + file_path_str[i]); content::FileChooserFileInfo file_info; file_info.file_path = path; if (!display_name_str[i].empty())
diff --git a/ash/mus/BUILD.gn b/ash/mus/BUILD.gn index 2a4664f5e..c6e9c9c 100644 --- a/ash/mus/BUILD.gn +++ b/ash/mus/BUILD.gn
@@ -26,7 +26,7 @@ "//ash", "//cc", "//cc/surfaces", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/public/cpp", "//components/mus/public/interfaces", "//components/user_manager",
diff --git a/ash/mus/sysui_application.cc b/ash/mus/sysui_application.cc index c55482a..9154947 100644 --- a/ash/mus/sysui_application.cc +++ b/ash/mus/sysui_application.cc
@@ -279,8 +279,8 @@ void SysUIApplication::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { ash_init_.reset(new AshInit()); ash_init_->Initialize(connector); }
diff --git a/ash/mus/sysui_application.h b/ash/mus/sysui_application.h index c597651..78d15990 100644 --- a/ash/mus/sysui_application.h +++ b/ash/mus/sysui_application.h
@@ -24,8 +24,8 @@ // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) override; + const std::string& user_id, + uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; mojo::TracingImpl tracing_;
diff --git a/base/BUILD.gn b/base/BUILD.gn index 61a36c8..a06dfa3 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1942,7 +1942,6 @@ "bind_unittest.nc", "callback_list_unittest.nc", "callback_unittest.nc", - "memory/scoped_ptr_unittest.nc", "memory/weak_ptr_unittest.nc", ]
diff --git a/base/base.gyp b/base/base.gyp index fff51e9..46ec1aa 100644 --- a/base/base.gyp +++ b/base/base.gyp
@@ -467,7 +467,6 @@ 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', - 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/shared_memory_unittest.cc',
diff --git a/base/memory/scoped_ptr_unittest.nc b/base/memory/scoped_ptr_unittest.nc deleted file mode 100644 index 10b45a1..0000000 --- a/base/memory/scoped_ptr_unittest.nc +++ /dev/null
@@ -1,119 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This is a "No Compile Test" suite. -// http://dev.chromium.org/developers/testing/no-compile-tests - -#include "base/memory/scoped_ptr.h" - -#include <utility> - -#include "base/macros.h" -#include "base/memory/ref_counted.h" - -namespace { - -class Parent { -}; - -class Child : public Parent { -}; - -class RefCountedClass : public base::RefCountedThreadSafe<RefCountedClass> { -}; - -} // namespace - -#if defined(NCTEST_NO_PASS_DOWNCAST) // [r"fatal error: no viable conversion from returned value of type 'scoped_ptr<\(anonymous namespace\)::Parent>' to function return type 'scoped_ptr<\(anonymous namespace\)::Child>'"] - -scoped_ptr<Child> DowncastUsingPassAs(scoped_ptr<Parent> object) { - return object; -} - -#elif defined(NCTEST_NO_REF_COUNTED_SCOPED_PTR) // [r"fatal error: static_assert failed \"T is a refcounted type and needs a scoped_refptr\""] - -// scoped_ptr<> should not work for ref-counted objects. -void WontCompile() { - scoped_ptr<RefCountedClass> x; -} - -#elif defined(NCTEST_NO_ARRAY_WITH_SIZE) // [r"fatal error: static_assert failed \"scoped_ptr doesn't support array with size\""] - -void WontCompile() { - scoped_ptr<int[10]> x; -} - -#elif defined(NCTEST_NO_PASS_FROM_ARRAY) // [r"fatal error: no viable overloaded '='"] - -void WontCompile() { - scoped_ptr<int[]> a; - scoped_ptr<int*> b; - b = std::move(a); -} - -#elif defined(NCTEST_NO_PASS_TO_ARRAY) // [r"fatal error: no viable overloaded '='"] - -void WontCompile() { - scoped_ptr<int*> a; - scoped_ptr<int[]> b; - b = std::move(a); -} - -#elif defined(NCTEST_NO_CONSTRUCT_FROM_ARRAY) // [r"fatal error: no matching constructor for initialization of 'scoped_ptr<int \*>'"] - -void WontCompile() { - scoped_ptr<int[]> a; - scoped_ptr<int*> b(std::move(a)); -} - -#elif defined(NCTEST_NO_CONSTRUCT_TO_ARRAY) // [r"fatal error: no matching constructor for initialization of 'scoped_ptr<int \[\]>'"] - -void WontCompile() { - scoped_ptr<int*> a; - scoped_ptr<int[]> b(std::move(a)); -} - -#elif defined(NCTEST_NO_CONSTRUCT_SCOPED_PTR_ARRAY_FROM_NULL) // [r"is ambiguous"] - -void WontCompile() { - scoped_ptr<int[]> x(NULL); -} - -#elif defined(NCTEST_NO_CONSTRUCT_SCOPED_PTR_ARRAY_FROM_DERIVED) // [r"fatal error: calling a private constructor of class 'scoped_ptr<\(anonymous namespace\)::Parent \[\], std::default_delete<\(anonymous namespace\)::Parent \[\]> >'"] - -void WontCompile() { - scoped_ptr<Parent[]> x(new Child[1]); -} - -#elif defined(NCTEST_NO_RESET_SCOPED_PTR_ARRAY_FROM_NULL) // [r"is ambiguous"] - -void WontCompile() { - scoped_ptr<int[]> x; - x.reset(NULL); -} - -#elif defined(NCTEST_NO_RESET_SCOPED_PTR_ARRAY_FROM_DERIVED) // [r"fatal error: 'reset' is a private member of 'scoped_ptr<\(anonymous namespace\)::Parent \[\], std::default_delete<\(anonymous namespace\)::Parent \[\]> >'"] - -void WontCompile() { - scoped_ptr<Parent[]> x; - x.reset(new Child[1]); -} - -#elif defined(NCTEST_NO_DELETER_REFERENCE) // [r"fatal error: base specifier must name a class"] - -struct Deleter { - void operator()(int*) {} -}; - -// Current implementation doesn't support Deleter Reference types. Enabling -// support would require changes to the behavior of the constructors to match -// including the use of SFINAE to discard the type-converting constructor -// as per C++11 20.7.1.2.1.19. -void WontCompile() { - Deleter d; - int n; - scoped_ptr<int*, Deleter&> a(&n, d); -} - -#endif
diff --git a/base/metrics/histogram.cc b/base/metrics/histogram.cc index e85c217..7feacdb 100644 --- a/base/metrics/histogram.cc +++ b/base/metrics/histogram.cc
@@ -165,7 +165,6 @@ PersistentMemoryAllocator* allocator = reinterpret_cast<PersistentMemoryAllocator*>(0xDEADBEEF); PersistentMemoryAllocator::Reference histogram_ref = 0xDEADBEEF; - bool bad_args = false; if (!histogram) { // To avoid racy destruction at shutdown, the following will be leaked. @@ -183,6 +182,8 @@ minimum_ = registered_ranges->range(1); maximum_ = registered_ranges->range(bucket_count_ - 1); } + CHECK_LT(0, minimum_); + CHECK_LT(0, maximum_); // Try to create the histogram using a "persistent" allocator. As of // 2015-01-14, the availability of such is controlled by a base::Feature @@ -204,6 +205,12 @@ registered_ranges, flags_, &histogram_ref); + CHECK_LT(0, minimum_); + CHECK_LT(0, maximum_); + CHECK_EQ(minimum_, + static_cast<Histogram*>(tentative_histogram)->declared_min_); + CHECK_EQ(maximum_, + static_cast<Histogram*>(tentative_histogram)->declared_max_); } // Handle the case where no persistent allocator is present or the @@ -213,6 +220,12 @@ DCHECK(!allocator); // Shouldn't have failed. flags_ &= ~HistogramBase::kIsPersistent; tentative_histogram = HeapAlloc(registered_ranges); + CHECK_LT(0, minimum_); + CHECK_LT(0, maximum_); + CHECK_EQ(minimum_, + static_cast<Histogram*>(tentative_histogram)->declared_min_); + CHECK_EQ(maximum_, + static_cast<Histogram*>(tentative_histogram)->declared_max_); } FillHistogram(tentative_histogram); @@ -227,6 +240,15 @@ } DCHECK_EQ(histogram_type_, histogram->GetHistogramType()); + bool bad_args = false; + HistogramBase* existing_histogram = histogram; + HistogramType existing_type = histogram->GetHistogramType(); + const char* existing_name = histogram->histogram_name().c_str(); + Sample existing_minimum = static_cast<Histogram*>(histogram)->declared_min_; + Sample existing_maximum = static_cast<Histogram*>(histogram)->declared_max_; + uint32_t existing_bucket_count = + static_cast<Histogram*>(histogram)->bucket_count(); + if (bucket_count_ != 0 && !histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) { // The construction arguments do not match the existing histogram. This can @@ -267,7 +289,14 @@ } #endif - base::debug::Alias(&bad_args); // Down here so var is always "used". + // Down here so vars are always "used". + base::debug::Alias(&bad_args); + base::debug::Alias(&existing_histogram); + base::debug::Alias(&existing_type); + base::debug::Alias(&existing_name); + base::debug::Alias(&existing_minimum); + base::debug::Alias(&existing_maximum); + base::debug::Alias(&existing_bucket_count); return histogram; } @@ -529,8 +558,12 @@ bucket_ranges_(ranges), declared_min_(minimum), declared_max_(maximum) { + CHECK_LT(0, minimum); + CHECK_LT(0, maximum); if (ranges) samples_.reset(new SampleVector(HashMetricName(name), ranges)); + CHECK_EQ(minimum, declared_min_); + CHECK_EQ(maximum, declared_max_); } Histogram::Histogram(const std::string& name, @@ -546,12 +579,16 @@ bucket_ranges_(ranges), declared_min_(minimum), declared_max_(maximum) { + CHECK_LT(0, minimum); + CHECK_LT(0, maximum); if (ranges) { samples_.reset(new SampleVector(HashMetricName(name), counts, counts_size, meta, ranges)); logged_samples_.reset(new SampleVector(samples_->id(), logged_counts, counts_size, logged_meta, ranges)); } + CHECK_EQ(minimum, declared_min_); + CHECK_EQ(maximum, declared_max_); } Histogram::~Histogram() {
diff --git a/base/metrics/histogram_persistence.cc b/base/metrics/histogram_persistence.cc index f18d175..8b946475 100644 --- a/base/metrics/histogram_persistence.cc +++ b/base/metrics/histogram_persistence.cc
@@ -288,6 +288,8 @@ HistogramBase::AtomicCount* logged_data = counts_data + histogram_data.bucket_count; + CHECK_LT(0, histogram_data.minimum); + CHECK_LT(0, histogram_data.maximum); std::string name(histogram_data_ptr->name); HistogramBase* histogram = nullptr; switch (histogram_data.histogram_type) {
diff --git a/blimp/docs/build.md b/blimp/docs/build.md index d67f2a90..a235121 100644 --- a/blimp/docs/build.md +++ b/blimp/docs/build.md
@@ -12,18 +12,8 @@ ```bash mkdir -p out-android/Debug -gn args out-android/Debug -``` - -This will bring up an editor, where you can type in the following: - -```bash -target_os = "android" -is_debug = true -is_clang = true -is_component_build = true -symbol_level = 1 # Use -g1 instead of -g2 -use_goma = true +echo "import(\"//build/args/blimp_client.gn\")" > out-android/Debug/args.gn +gn gen out-android/Debug ``` To build: @@ -39,58 +29,20 @@ out-android/Debug/bin/install_blimp_apk_incremental ``` -## Engine inside a Docker container - -Create another out-directory and set the GN args. Note, when building to run -inside a [Docker container](container.md) you'll need to turn off several -dependencies: +To add your own build preferences ```bash -mkdir -p out-docker/Debug -gn args out-docker/Debug +gn args out-android/Debug ``` -This will bring an editor, where you can type in the following: - -```bash -target_os = "linux" -is_debug = true -is_clang = true -symbol_level = 1 # Use -g1 instead of -g2 -use_goma = true -use_aura = true -use_ozone = true -use_alsa = false -use_pulseaudio = false -use_cups = false -use_glib = false -``` - -To build: - -```bash -ninja -C out-docker/Debug blimp -``` - -## "Bare" engine, no Docker container +## Engine Create another out-directory and set the GN args: ```bash mkdir -p out-linux/Debug -gn args out-linux/Debug -``` - -This will bring an editor, where you can type in the following: - -```bash -is_debug = true -is_clang = true -is_component_build = true -symbol_level = 1 # Use -g1 instead of -g2 -use_goma = true -use_aura = true -use_ozone = true +echo "import(\"//build/args/blimp_engine.gn\")" > out-linux/Debug/args.gn +gn gen out-linux/Debug ``` To build: @@ -98,3 +50,9 @@ ```bash ninja -C out-linux/Debug blimp ``` + +To add your own build preferences + +```bash +gn args out-android/Debug +```
diff --git a/build/android/pylib/gtest/gtest_test_instance.py b/build/android/pylib/gtest/gtest_test_instance.py index 173628b4..f84e040 100644 --- a/build/android/pylib/gtest/gtest_test_instance.py +++ b/build/android/pylib/gtest/gtest_test_instance.py
@@ -29,6 +29,8 @@ 'base_unittests': 'base/base_unittests.isolate', 'blink_heap_unittests': 'third_party/WebKit/Source/platform/heap/BlinkHeapUnitTests.isolate', + 'blink_platform_unittests': + 'third_party/WebKit/Source/platform/blink_platform_unittests.isolate', 'breakpad_unittests': 'breakpad/breakpad_unittests.isolate', 'cc_perftests': 'cc/cc_perftests.isolate', 'components_browsertests': 'components/components_browsertests.isolate',
diff --git a/build/args/blimp_client.gn b/build/args/blimp_client.gn new file mode 100644 index 0000000..a072eab5 --- /dev/null +++ b/build/args/blimp_client.gn
@@ -0,0 +1,11 @@ +# GN args template for blimp Android client. +# +# Add import to arg.gn in out directory and run gn gen on the directory to use. +# E.g. for out directory out/foo: +# echo "import(\"build/args/blimp_client.gn\")" > out/foo/args.gn +# gn gen out/foo +# +# Use gn args to add your own build preference args. + +target_os = "android" +is_component_build = true
diff --git a/build/args/blimp_engine.gn b/build/args/blimp_engine.gn new file mode 100644 index 0000000..22a5e43 --- /dev/null +++ b/build/args/blimp_engine.gn
@@ -0,0 +1,17 @@ +# GN args template for a blimp engine. Works within a docker container. +# +# Add import to arg.gn in out directory and run gn gen on the directory to use. +# E.g. for out directory out/foo: +# echo "import(\"build/args/blimp_engine.gn\")" > out/foo/args.gn +# gn gen out/foo +# +# Use gn args to add your own build preference args. + +use_aura = true +use_ozone = true + +# Not available within docker container. +use_alsa = false +use_pulseaudio = false +use_cups = false +use_glib = false \ No newline at end of file
diff --git a/build/common.gypi b/build/common.gypi index f77482c..f0faad2 100644 --- a/build/common.gypi +++ b/build/common.gypi
@@ -290,7 +290,7 @@ # Set default gomadir. ['OS=="win"', { - 'gomadir': 'c:\\goma\\goma-win', + 'gomadir': 'c:\\goma\\goma-win64', }, { 'gomadir': '<!(/bin/echo -n ${HOME}/goma)', }], @@ -2380,24 +2380,17 @@ 'ozone_platform_headless%': 1, 'conditions': [ ['chromecast==1', { + 'ozone_platform_cast%': 1, 'conditions': [ - ['disable_display==0', { - # Enable the Cast ozone platform on all A/V Cast builds. - 'ozone_platform_cast%': 1, - - # For desktop Chromecast builds, override the default "headless" - # platform with --ozone-platform=egltest - # TODO(slan|halliwell): Make the default platform "cast" on - # desktop too. - 'conditions': [ - ['is_cast_desktop_build==1', { - 'ozone_platform_egltest%': 1, - 'ozone_platform_ozonex%': 1, - }, { - # On device builds, enable "cast" as the default platform. - 'ozone_platform%': 'cast', - }], - ], + # For desktop non-audio Chromecast builds, run with + # --ozone-platform=egltest + # TODO(slan|halliwell): Make the default platform "cast" on + # desktop non-audio builds too. + ['is_cast_desktop_build==1 and disable_display==0', { + 'ozone_platform_egltest%': 1, + 'ozone_platform_ozonex%': 1, + }, { + 'ozone_platform%': 'cast', }], ], }, { # chromecast!=1
diff --git a/build/linux/sysroot_scripts/install-sysroot.py b/build/linux/sysroot_scripts/install-sysroot.py index 79d4bae..b8e4300 100755 --- a/build/linux/sysroot_scripts/install-sysroot.py +++ b/build/linux/sysroot_scripts/install-sysroot.py
@@ -32,7 +32,7 @@ import gyp_environment -URL_PREFIX = 'http://commondatastorage.googleapis.com' +URL_PREFIX = 'https://commondatastorage.googleapis.com' URL_PATH = 'chrome-linux-sysroot/toolchain' REVISION_AMD64 = 'c52471d9dec240c8d0a88fa98aa1eefeee32e22f' REVISION_ARM = 'c52471d9dec240c8d0a88fa98aa1eefeee32e22f'
diff --git a/build/toolchain/goma.gni b/build/toolchain/goma.gni index c0f4cf2..86ac0e9 100644 --- a/build/toolchain/goma.gni +++ b/build/toolchain/goma.gni
@@ -14,7 +14,7 @@ # Set the default value based on the platform. if (is_win) { # Absolute directory containing the Goma source code. - goma_dir = "C:\goma\goma-win" + goma_dir = "C:\goma\goma-win64" } else { # Absolute directory containing the Goma source code. goma_dir = getenv("HOME") + "/goma"
diff --git a/cc/animation/layer_animation_controller.cc b/cc/animation/layer_animation_controller.cc index 1f470b5..3a34b32 100644 --- a/cc/animation/layer_animation_controller.cc +++ b/cc/animation/layer_animation_controller.cc
@@ -460,6 +460,7 @@ event.monotonic_time, event.target_property, event.group_id); if (event.target_property == TargetProperty::TRANSFORM) aborted_transform_animation = true; + break; } } if (aborted_transform_animation)
diff --git a/cc/raster/bitmap_tile_task_worker_pool.cc b/cc/raster/bitmap_tile_task_worker_pool.cc index 8892502..de651476 100644 --- a/cc/raster/bitmap_tile_task_worker_pool.cc +++ b/cc/raster/bitmap_tile_task_worker_pool.cc
@@ -128,8 +128,7 @@ bool BitmapTileTaskWorkerPool::GetResourceRequiresSwizzle( bool must_support_alpha) const { - return !PlatformColor::SameComponentOrder( - GetResourceFormat(must_support_alpha)); + return ResourceFormatRequiresSwizzle(GetResourceFormat(must_support_alpha)); } scoped_ptr<RasterBuffer> BitmapTileTaskWorkerPool::AcquireBufferForRaster(
diff --git a/cc/raster/one_copy_tile_task_worker_pool.cc b/cc/raster/one_copy_tile_task_worker_pool.cc index 38e30762..01587524 100644 --- a/cc/raster/one_copy_tile_task_worker_pool.cc +++ b/cc/raster/one_copy_tile_task_worker_pool.cc
@@ -296,8 +296,7 @@ bool OneCopyTileTaskWorkerPool::GetResourceRequiresSwizzle( bool must_support_alpha) const { - return !PlatformColor::SameComponentOrder( - GetResourceFormat(must_support_alpha)); + return ResourceFormatRequiresSwizzle(GetResourceFormat(must_support_alpha)); } scoped_ptr<RasterBuffer> OneCopyTileTaskWorkerPool::AcquireBufferForRaster(
diff --git a/cc/raster/tile_task_runner.cc b/cc/raster/tile_task_runner.cc index 074f045..50e8805d 100644 --- a/cc/raster/tile_task_runner.cc +++ b/cc/raster/tile_task_runner.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "cc/raster/tile_task_runner.h" +#include "cc/resources/platform_color.h" namespace cc { @@ -55,4 +56,24 @@ RasterTask::~RasterTask() { } +bool TileTaskRunner::ResourceFormatRequiresSwizzle(ResourceFormat format) { + switch (format) { + case RGBA_8888: + case BGRA_8888: + // Initialize resource using the preferred PlatformColor component + // order and swizzle in the shader instead of in software. + return !PlatformColor::SameComponentOrder(format); + case RGBA_4444: + case ETC1: + case ALPHA_8: + case LUMINANCE_8: + case RGB_565: + case RED_8: + case LUMINANCE_F16: + return false; + } + NOTREACHED(); + return false; +} + } // namespace cc
diff --git a/cc/raster/tile_task_runner.h b/cc/raster/tile_task_runner.h index ed0f29a..5e2f7fd1 100644 --- a/cc/raster/tile_task_runner.h +++ b/cc/raster/tile_task_runner.h
@@ -104,6 +104,9 @@ virtual bool GetResourceRequiresSwizzle(bool must_support_alpha) const = 0; protected: + // Check if resource format matches output format. + static bool ResourceFormatRequiresSwizzle(ResourceFormat format); + virtual ~TileTaskRunner() {} };
diff --git a/cc/raster/zero_copy_tile_task_worker_pool.cc b/cc/raster/zero_copy_tile_task_worker_pool.cc index 1fd8e3d..410540a 100644 --- a/cc/raster/zero_copy_tile_task_worker_pool.cc +++ b/cc/raster/zero_copy_tile_task_worker_pool.cc
@@ -136,8 +136,7 @@ bool ZeroCopyTileTaskWorkerPool::GetResourceRequiresSwizzle( bool must_support_alpha) const { - return !PlatformColor::SameComponentOrder( - GetResourceFormat(must_support_alpha)); + return ResourceFormatRequiresSwizzle(GetResourceFormat(must_support_alpha)); } scoped_ptr<RasterBuffer> ZeroCopyTileTaskWorkerPool::AcquireBufferForRaster(
diff --git a/cc/resources/platform_color.h b/cc/resources/platform_color.h index 26d6b026..67ede54 100644 --- a/cc/resources/platform_color.h +++ b/cc/resources/platform_color.h
@@ -47,15 +47,25 @@ return RGBA_8888; } - // Return true if the given texture format has the same component order - // as the color on this platform. + // Return true if the given 32bpp resource format has the same component order + // as the platform color data format. static bool SameComponentOrder(ResourceFormat format) { - switch (Format()) { - case SOURCE_FORMAT_RGBA8: - return format == RGBA_8888 || format == RGBA_4444; - case SOURCE_FORMAT_BGRA8: - return format == BGRA_8888 || format == RGBA_4444; + switch (format) { + case RGBA_8888: + return Format() == SOURCE_FORMAT_RGBA8; + case BGRA_8888: + return Format() == SOURCE_FORMAT_BGRA8; + case ALPHA_8: + case LUMINANCE_8: + case RGB_565: + case RGBA_4444: + case ETC1: + case RED_8: + case LUMINANCE_F16: + NOTREACHED(); + return false; } + NOTREACHED(); return false; }
diff --git a/cc/resources/platform_color_unittest.cc b/cc/resources/platform_color_unittest.cc index 49c8353b..83f65b6 100644 --- a/cc/resources/platform_color_unittest.cc +++ b/cc/resources/platform_color_unittest.cc
@@ -21,21 +21,17 @@ case RGBA_8888: EXPECT_EQ(rgba, PlatformColor::SameComponentOrder(format)); break; - case RGBA_4444: - // RGBA_4444 indicates the number of bytes per pixel but the format - // doesn't actually imply RGBA ordering. It uses the native ordering. - EXPECT_EQ(true, PlatformColor::SameComponentOrder(format)); - break; case BGRA_8888: EXPECT_NE(rgba, PlatformColor::SameComponentOrder(format)); break; + // The following formats are not platform colors. case ALPHA_8: case LUMINANCE_8: case RGB_565: + case RGBA_4444: case ETC1: case RED_8: case LUMINANCE_F16: - EXPECT_FALSE(PlatformColor::SameComponentOrder(format)); break; } }
diff --git a/cc/test/fake_tile_manager.cc b/cc/test/fake_tile_manager.cc index 86ce28b..77b9b0d 100644 --- a/cc/test/fake_tile_manager.cc +++ b/cc/test/fake_tile_manager.cc
@@ -50,8 +50,7 @@ return RGBA_8888; } bool GetResourceRequiresSwizzle(bool must_support_alpha) const override { - return !PlatformColor::SameComponentOrder( - GetResourceFormat(must_support_alpha)); + return ResourceFormatRequiresSwizzle(GetResourceFormat(must_support_alpha)); } // Overridden from TileTaskClient:
diff --git a/cc/tiles/tile_manager_perftest.cc b/cc/tiles/tile_manager_perftest.cc index 53b7ba8..d10c4cbc 100644 --- a/cc/tiles/tile_manager_perftest.cc +++ b/cc/tiles/tile_manager_perftest.cc
@@ -67,8 +67,7 @@ return RGBA_8888; } bool GetResourceRequiresSwizzle(bool must_support_alpha) const override { - return !PlatformColor::SameComponentOrder( - GetResourceFormat(must_support_alpha)); + return ResourceFormatRequiresSwizzle(GetResourceFormat(must_support_alpha)); } // Overridden from TileTaskClient:
diff --git a/chrome/VERSION b/chrome/VERSION index 7f5b38f..8be6c9e2 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=51 MINOR=0 -BUILD=2668 +BUILD=2671 PATCH=0
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java index 233b40b..2edb3ee 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManager.java
@@ -641,9 +641,10 @@ String message; boolean doLiteralSearch = false; if (isNetworkUnavailable) { + // TODO(donnd): double-check that the network is really unavailable? message = mActivity.getResources().getString( R.string.contextual_search_network_unavailable); - } else if (!isHttpFailureCode(responseCode)) { + } else if (!isHttpFailureCode(responseCode) && !TextUtils.isEmpty(displayText)) { message = displayText; } else if (!mPolicy.shouldShowErrorCodeInBar()) { message = mSelectionController.getSelectedText();
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 9caafdc7..f84d81a 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -989,7 +989,7 @@ {"enable-stale-while-revalidate", IDS_FLAGS_ENABLE_STALE_WHILE_REVALIDATE_NAME, IDS_FLAGS_ENABLE_STALE_WHILE_REVALIDATE_DESCRIPTION, kOsAll, - SINGLE_VALUE_TYPE(switches::kEnableStaleWhileRevalidate)}, + FEATURE_VALUE_TYPE(features::kStaleWhileRevalidate)}, {"enable-suggestions-with-substring-match", IDS_FLAGS_SUGGESTIONS_WITH_SUB_STRING_MATCH_NAME, IDS_FLAGS_SUGGESTIONS_WITH_SUB_STRING_MATCH_DESCRIPTION, kOsAll,
diff --git a/chrome/browser/android/contextualsearch/contextual_search_delegate.cc b/chrome/browser/android/contextualsearch/contextual_search_delegate.cc index 2e58411..b7385c0 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_delegate.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_delegate.cc
@@ -28,6 +28,7 @@ #include "content/public/browser/android/content_view_core.h" #include "content/public/browser/web_contents.h" #include "net/base/escape.h" +#include "net/http/http_status_code.h" #include "net/url_request/url_fetcher.h" #include "url/gurl.h" @@ -45,8 +46,6 @@ const char kContextualSearchServerEndpoint[] = "_/contextualsearch?"; const int kContextualSearchRequestVersion = 2; const int kContextualSearchMaxSelection = 100; -// The maximum length of a URL to build. -const int kMaxURLSize = 2048; const char kXssiEscape[] = ")]}'\n"; const char kDiscourseContextHeaderPrefix[] = "X-Additional-Discourse-Context: "; const char kDoPreventPreloadValue[] = "1"; @@ -107,7 +106,7 @@ DCHECK(context_.get()); if (!context_.get()) return; - GURL request_url(BuildRequestUrl()); + GURL request_url(BuildRequestUrl(context_->selected_text)); DCHECK(request_url.is_valid()); // Reset will delete any previous fetcher, and we won't get any callback. @@ -133,6 +132,28 @@ const net::URLFetcher* source) { DCHECK(source == search_term_fetcher_.get()); int response_code = source->GetResponseCode(); + + scoped_ptr<ResolvedSearchTerm> resolved_search_term( + new ResolvedSearchTerm(response_code)); + if (source->GetStatus().is_success() && response_code == net::HTTP_OK) { + std::string response; + bool has_string_response = source->GetResponseAsString(&response); + DCHECK(has_string_response); + if (has_string_response) { + resolved_search_term = + GetResolvedSearchTermFromJson(response_code, response); + } + } + search_term_callback_.Run(*resolved_search_term); + + // The ContextualSearchContext is consumed once the request has completed. + context_.reset(); +} + +scoped_ptr<ResolvedSearchTerm> +ContextualSearchDelegate::GetResolvedSearchTermFromJson( + int response_code, + const std::string& json_string) { std::string search_term; std::string display_text; std::string alternate_term; @@ -142,83 +163,48 @@ int start_adjust = 0; int end_adjust = 0; std::string context_language; - std::string target_language; - if (source->GetStatus().is_success() && response_code == 200) { - std::string response; - bool has_string_response = source->GetResponseAsString(&response); - DCHECK(has_string_response); - if (has_string_response) { - DecodeSearchTermFromJsonResponse( - response, &search_term, &display_text, &alternate_term, - &prevent_preload, &mention_start, &mention_end, &context_language); - if (mention_start != 0 || mention_end != 0) { - // Sanity check that our selection is non-zero and it is less than - // 100 characters as that would make contextual search bar hide. - // We also check that there is at least one character overlap between - // the new and old selection. - if (mention_start >= mention_end - || (mention_end - mention_start) > kContextualSearchMaxSelection - || mention_end <= context_->start_offset - || mention_start >= context_->end_offset) { - start_adjust = 0; - end_adjust = 0; - } else { - start_adjust = mention_start - context_->start_offset; - end_adjust = mention_end - context_->end_offset; - } - } + DecodeSearchTermFromJsonResponse( + json_string, &search_term, &display_text, &alternate_term, + &prevent_preload, &mention_start, &mention_end, &context_language); + if (mention_start != 0 || mention_end != 0) { + // Sanity check that our selection is non-zero and it is less than + // 100 characters as that would make contextual search bar hide. + // We also check that there is at least one character overlap between + // the new and old selection. + if (mention_start >= mention_end || + (mention_end - mention_start) > kContextualSearchMaxSelection || + mention_end <= context_->start_offset || + mention_start >= context_->end_offset) { + start_adjust = 0; + end_adjust = 0; + } else { + start_adjust = mention_start - context_->start_offset; + end_adjust = mention_end - context_->end_offset; } } bool is_invalid = response_code == net::URLFetcher::RESPONSE_CODE_INVALID; - ResolvedSearchTerm resolved_search_term( + return scoped_ptr<ResolvedSearchTerm>(new ResolvedSearchTerm( is_invalid, response_code, search_term, display_text, alternate_term, prevent_preload == kDoPreventPreloadValue, start_adjust, end_adjust, - context_language); - search_term_callback_.Run(resolved_search_term); - - // The ContextualSearchContext is consumed once the request has completed. - context_.reset(); + context_language)); } -// TODO(jeremycho): Remove selected_text and base_page_url CGI parameters. -GURL ContextualSearchDelegate::BuildRequestUrl() { - // TODO(jeremycho): Confirm this is the right way to handle TemplateURL fails. +std::string ContextualSearchDelegate::BuildRequestUrl(std::string selection) { + // TODO(donnd): Confirm this is the right way to handle TemplateURL fails. if (!template_url_service_ || !template_url_service_->GetDefaultSearchProvider()) { - return GURL(); + return std::string(); } - std::string selected_text_escaped( - net::EscapeQueryParamValue(context_->selected_text, true)); - std::string base_page_url_escaped( - net::EscapeQueryParamValue(context_->page_url.spec(), true)); - bool use_resolved_search_term = context_->use_resolved_search_term; - - // If the request is too long, don't include the base-page URL. - std::string request = GetSearchTermResolutionUrlString( - selected_text_escaped, base_page_url_escaped, use_resolved_search_term); - if (request.length() >= kMaxURLSize) { - request = GetSearchTermResolutionUrlString( - selected_text_escaped, "", use_resolved_search_term); - } - return GURL(request); -} - -std::string ContextualSearchDelegate::GetSearchTermResolutionUrlString( - const std::string& selected_text, - const std::string& base_page_url, - const bool use_resolved_search_term) { + std::string selected_text(net::EscapeQueryParamValue(selection, true)); TemplateURL* template_url = template_url_service_->GetDefaultSearchProvider(); TemplateURLRef::SearchTermsArgs search_terms_args = TemplateURLRef::SearchTermsArgs(base::string16()); TemplateURLRef::SearchTermsArgs::ContextualSearchParams params( - kContextualSearchRequestVersion, - selected_text, - base_page_url, - use_resolved_search_term); + kContextualSearchRequestVersion, selected_text, "", true); search_terms_args.contextual_search_params = params; @@ -251,6 +237,17 @@ // Immediately cancel any request that's in flight, since we're building a new // context (and the response disposes of any existing context). search_term_fetcher_.reset(); + BuildContext(selection, use_resolved_search_term, content_view_core, + may_send_base_page_url); + content_view_core->RequestTextSurroundingSelection( + field_trial_->GetSurroundingSize(), callback); +} + +void ContextualSearchDelegate::BuildContext( + const std::string& selection, + bool use_resolved_search_term, + content::ContentViewCore* content_view_core, + bool may_send_base_page_url) { // Decide if the URL should be sent with the context. GURL page_url(content_view_core->GetWebContents()->GetURL()); GURL url_to_send; @@ -262,8 +259,6 @@ std::string encoding(content_view_core->GetWebContents()->GetEncoding()); context_.reset(new ContextualSearchContext( selection, use_resolved_search_term, url_to_send, encoding)); - content_view_core->RequestTextSurroundingSelection( - field_trial_->GetSurroundingSize(), callback); } void ContextualSearchDelegate::StartSearchTermRequestFromSelection( @@ -337,6 +332,11 @@ void ContextualSearchDelegate::SetDiscourseContextAndAddToHeader( const ContextualSearchContext& context) { + search_term_fetcher_->AddExtraRequestHeader(GetDiscourseContext(context)); +} + +std::string ContextualSearchDelegate::GetDiscourseContext( + const ContextualSearchContext& context) { discourse_context::ClientDiscourseContext proto; discourse_context::Display* display = proto.add_display(); display->set_uri(context.page_url.spec()); @@ -358,8 +358,7 @@ // The server memoizer expects a web-safe encoding. std::replace(encoded_context.begin(), encoded_context.end(), '+', '-'); std::replace(encoded_context.begin(), encoded_context.end(), '/', '_'); - search_term_fetcher_->AddExtraRequestHeader( - kDiscourseContextHeaderPrefix + encoded_context); + return kDiscourseContextHeaderPrefix + encoded_context; } bool ContextualSearchDelegate::CanSendPageURL(
diff --git a/chrome/browser/android/contextualsearch/contextual_search_delegate.h b/chrome/browser/android/contextualsearch/contextual_search_delegate.h index f926b5d..08dc52bc 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_delegate.h +++ b/chrome/browser/android/contextualsearch/contextual_search_delegate.h
@@ -32,12 +32,17 @@ : public net::URLFetcherDelegate, public base::SupportsWeakPtr<ContextualSearchDelegate> { public: + // Callback that provides the surrounding text past the selection for the UX. typedef base::Callback<void(const std::string&)> SurroundingTextCallback; + // Provides the Resolved Search Term, called when the Resolve Request returns. typedef base::Callback<void(const ResolvedSearchTerm&)> SearchTermResolutionCallback; + // Provides the surrounding text and selection start/end when Blink gathers + // surrounding text for the Context. typedef base::Callback< void(const base::string16&, int, int)> HandleSurroundingsCallback; + // Provides limited surrounding text for icing. typedef base::Callback< void(const std::string&, const base::string16&, size_t, size_t)> IcingCallback; @@ -103,12 +108,21 @@ SurroundingTextForIcingNegativeLimit); FRIEND_TEST_ALL_PREFIXES(ContextualSearchDelegateTest, DecodeSearchTermFromJsonResponse); + FRIEND_TEST_ALL_PREFIXES(ContextualSearchDelegateTest, DecodeStringMentions); // net::URLFetcherDelegate: void OnURLFetchComplete(const net::URLFetcher* source) override; - // Builds the search term resolution request URL from the current context. - GURL BuildRequestUrl(); + // Builds the ContextualSearchContext in the current context from + // the given parameters. + void BuildContext(const std::string& selection, + bool use_resolved_search_term, + content::ContentViewCore* content_view_core, + bool may_send_base_page_url); + + // Builds and returns the search term resolution request URL. + // |selection| is used as the default query. + std::string BuildRequestUrl(std::string selection); // Uses the TemplateURL service to construct a search term resolution URL from // the given parameters. @@ -148,6 +162,9 @@ void SetDiscourseContextAndAddToHeader( const ContextualSearchContext& context); + // Populates and returns the discourse context. + std::string GetDiscourseContext(const ContextualSearchContext& context); + // Checks if we can send the URL for this user. Several conditions are checked // to make sure it's OK to send the URL. These fall into two categories: // 1) check if it's allowed by our policy, and 2) ensure that the user is @@ -156,6 +173,11 @@ Profile* profile, TemplateURLService* template_url_service); + // Builds a Resolved Search Term by decoding the given JSON string. + scoped_ptr<ResolvedSearchTerm> GetResolvedSearchTermFromJson( + int response_code, + const std::string& json_string); + // Decodes the given json response string and extracts parameters. void DecodeSearchTermFromJsonResponse(const std::string& response, std::string* search_term, @@ -166,6 +188,8 @@ int* mention_end, std::string* context_language); + // Extracts the start and end location from a mentions list, and sets the + // integers referenced by |startResult| and |endResult|. void ExtractMentionsStartEnd(const base::ListValue& mentions_list, int* startResult, int* endResult);
diff --git a/chrome/browser/android/contextualsearch/contextual_search_delegate_unittest.cc b/chrome/browser/android/contextualsearch/contextual_search_delegate_unittest.cc index a22c4cd..9bf81d23 100644 --- a/chrome/browser/android/contextualsearch/contextual_search_delegate_unittest.cc +++ b/chrome/browser/android/contextualsearch/contextual_search_delegate_unittest.cc
@@ -6,6 +6,7 @@ #include <stddef.h> +#include "base/base64.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" @@ -13,6 +14,7 @@ #include "base/values.h" #include "chrome/browser/android/contextualsearch/contextual_search_context.h" #include "chrome/browser/android/contextualsearch/resolved_search_term.h" +#include "chrome/browser/android/proto/client_discourse_context.pb.h" #include "components/search_engines/template_url_service.h" #include "net/base/escape.h" #include "net/url_request/test_url_fetcher_factory.h" @@ -23,7 +25,8 @@ namespace { -const char kSomeSpecificBasePage[] = "http://some.specific.host.name.com"; +const char kSomeSpecificBasePage[] = "http://some.specific.host.name.com/"; +const char kDiscourseContextHeaderName[] = "X-Additional-Discourse-Context"; } // namespace @@ -123,13 +126,41 @@ delegate_->set_context_for_testing(test_context_); } - bool DoesRequestContainOurSpecificBasePage() { - return fetcher()->GetOriginalURL().spec().find( - specific_base_page_URL_escaped()) != std::string::npos; + // Gets the Client Discourse Context proto from the request header. + discourse_context::ClientDiscourseContext GetDiscourseContextFromRequest() { + discourse_context::ClientDiscourseContext cdc; + // Make sure we can get the actual raw headers from the fake fetcher. + net::HttpRequestHeaders fetch_headers; + fetcher()->GetExtraRequestHeaders(&fetch_headers); + if (fetch_headers.HasHeader(kDiscourseContextHeaderName)) { + std::string actual_header_value; + fetch_headers.GetHeader(kDiscourseContextHeaderName, + &actual_header_value); + + // Unescape, since the server memoizer expects a web-safe encoding. + std::string unescaped_header = actual_header_value; + std::replace(unescaped_header.begin(), unescaped_header.end(), '-', '+'); + std::replace(unescaped_header.begin(), unescaped_header.end(), '_', '/'); + + // Base64 decode the header. + std::string decoded_header; + if (base::Base64Decode(unescaped_header, &decoded_header)) { + cdc.ParseFromString(decoded_header); + } + } + return cdc; } - std::string specific_base_page_URL_escaped() { - return net::EscapeQueryParamValue(kSomeSpecificBasePage, true); + // Gets the base-page URL from the request, or an empty string if not present. + std::string getBasePageUrlFromRequest() { + std::string result; + discourse_context::ClientDiscourseContext cdc = + GetDiscourseContextFromRequest(); + if (cdc.display_size() > 0) { + const discourse_context::Display& first_display = cdc.display(0); + result = first_display.uri(); + } + return result; } net::TestURLFetcher* fetcher() { return fetcher_; } @@ -211,7 +242,6 @@ EXPECT_EQ("obama", search_term()); EXPECT_EQ("Barack Obama", display_text()); EXPECT_FALSE(do_prevent_preload()); - EXPECT_TRUE(DoesRequestContainOurSpecificBasePage()); } TEST_F(ContextualSearchDelegateTest, NormalFetchWithoutXssiEscape) { @@ -229,7 +259,6 @@ EXPECT_EQ("obama", search_term()); EXPECT_EQ("Barack Obama", display_text()); EXPECT_FALSE(do_prevent_preload()); - EXPECT_TRUE(DoesRequestContainOurSpecificBasePage()); } TEST_F(ContextualSearchDelegateTest, ResponseWithNoDisplayText) { @@ -245,7 +274,6 @@ EXPECT_EQ("obama", search_term()); EXPECT_EQ("obama", display_text()); EXPECT_FALSE(do_prevent_preload()); - EXPECT_TRUE(DoesRequestContainOurSpecificBasePage()); } TEST_F(ContextualSearchDelegateTest, ResponseWithPreventPreload) { @@ -261,7 +289,6 @@ EXPECT_EQ("obama", search_term()); EXPECT_EQ("obama", display_text()); EXPECT_TRUE(do_prevent_preload()); - EXPECT_TRUE(DoesRequestContainOurSpecificBasePage()); } TEST_F(ContextualSearchDelegateTest, NonJsonResponse) { @@ -275,7 +302,6 @@ EXPECT_EQ("", search_term()); EXPECT_EQ("", display_text()); EXPECT_FALSE(do_prevent_preload()); - EXPECT_TRUE(DoesRequestContainOurSpecificBasePage()); } TEST_F(ContextualSearchDelegateTest, InvalidResponse) { @@ -492,6 +518,10 @@ EXPECT_EQ("obama", search_term()); EXPECT_EQ("obama", display_text()); EXPECT_TRUE(do_prevent_preload()); - EXPECT_TRUE(DoesRequestContainOurSpecificBasePage()); EXPECT_EQ("de", context_language()); } + +TEST_F(ContextualSearchDelegateTest, HeaderContainsBasePageUrl) { + CreateDefaultSearchContextAndRequestSearchTerm(); + EXPECT_EQ(kSomeSpecificBasePage, getBasePageUrlFromRequest()); +}
diff --git a/chrome/browser/android/contextualsearch/resolved_search_term.cc b/chrome/browser/android/contextualsearch/resolved_search_term.cc index 7dbae11..7aa01bf 100644 --- a/chrome/browser/android/contextualsearch/resolved_search_term.cc +++ b/chrome/browser/android/contextualsearch/resolved_search_term.cc
@@ -4,6 +4,19 @@ #include "chrome/browser/android/contextualsearch/resolved_search_term.h" +#include "net/url_request/url_fetcher.h" + +ResolvedSearchTerm::ResolvedSearchTerm(int response_code) + : is_invalid(response_code == net::URLFetcher::RESPONSE_CODE_INVALID), + response_code(response_code), + search_term(""), + display_text(""), + alternate_term(""), + prevent_preload(false), + selection_start_adjust(0), + selection_end_adjust(0), + context_language("") {} + ResolvedSearchTerm::ResolvedSearchTerm(bool is_invalid, int response_code, const std::string& search_term,
diff --git a/chrome/browser/android/contextualsearch/resolved_search_term.h b/chrome/browser/android/contextualsearch/resolved_search_term.h index 5760482e..37eb166 100644 --- a/chrome/browser/android/contextualsearch/resolved_search_term.h +++ b/chrome/browser/android/contextualsearch/resolved_search_term.h
@@ -14,6 +14,7 @@ // surrounding text. struct ResolvedSearchTerm { public: + explicit ResolvedSearchTerm(int response_code); ResolvedSearchTerm(bool is_invalid, int response_code, const std::string& search_term, @@ -27,13 +28,14 @@ const bool is_invalid; const int response_code; - const std::string& search_term; - const std::string& display_text; - const std::string& alternate_term; + // Use strings, rather than just references, to keep this complete. + const std::string search_term; + const std::string display_text; + const std::string alternate_term; const bool prevent_preload; const int selection_start_adjust; const int selection_end_adjust; - const std::string& context_language; + const std::string context_language; DISALLOW_COPY_AND_ASSIGN(ResolvedSearchTerm); };
diff --git a/chrome/browser/browsing_data/browsing_data_remover.cc b/chrome/browser/browsing_data/browsing_data_remover.cc index 83f835f..a07aab0 100644 --- a/chrome/browser/browsing_data/browsing_data_remover.cc +++ b/chrome/browser/browsing_data/browsing_data_remover.cc
@@ -89,6 +89,7 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chromeos/attestation/attestation_constants.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/user_manager/user.h" @@ -881,7 +882,8 @@ chromeos::DBusThreadManager::Get() ->GetCryptohomeClient() ->TpmAttestationDeleteKeys( - chromeos::attestation::KEY_USER, user->email(), + chromeos::attestation::KEY_USER, + cryptohome::Identification(user->GetAccountId()), chromeos::attestation::kContentProtectionKeyPrefix, base::Bind(&BrowsingDataRemover::OnClearPlatformKeys, weak_ptr_factory_.GetWeakPtr()));
diff --git a/chrome/browser/chromeos/accessibility/chromevox_panel.cc b/chrome/browser/chromeos/accessibility/chromevox_panel.cc index 2fa56ebe..e716e66 100644 --- a/chrome/browser/chromeos/accessibility/chromevox_panel.cc +++ b/chrome/browser/chromeos/accessibility/chromevox_panel.cc
@@ -26,6 +26,7 @@ const char kChromeVoxPanelRelativeUrl[] = "/cvox2/background/panel.html"; const char kFullscreenURLFragment[] = "fullscreen"; const char kDisableSpokenFeedbackURLFragment[] = "close"; +const char kFocusURLFragment[] = "focus"; } // namespace @@ -50,6 +51,8 @@ panel_->DisableSpokenFeedback(); else if (fragment == kFullscreenURLFragment) panel_->EnterFullscreen(); + else if (fragment == kFocusURLFragment) + panel_->Focus(); else panel_->ExitFullscreen(); } @@ -112,10 +115,8 @@ } void ChromeVoxPanel::EnterFullscreen() { + Focus(); fullscreen_ = true; - widget_->widget_delegate()->set_can_activate(true); - widget_->Activate(); - web_view_->RequestFocus(); UpdateWidgetBounds(); } @@ -130,6 +131,12 @@ false, ui::A11Y_NOTIFICATION_NONE); } +void ChromeVoxPanel::Focus() { + widget_->widget_delegate()->set_can_activate(true); + widget_->Activate(); + web_view_->RequestFocus(); +} + const views::Widget* ChromeVoxPanel::GetWidget() const { return widget_; }
diff --git a/chrome/browser/chromeos/accessibility/chromevox_panel.h b/chrome/browser/chromeos/accessibility/chromevox_panel.h index d03b998..0a526ff 100644 --- a/chrome/browser/chromeos/accessibility/chromevox_panel.h +++ b/chrome/browser/chromeos/accessibility/chromevox_panel.h
@@ -34,6 +34,7 @@ void EnterFullscreen(); void ExitFullscreen(); void DisableSpokenFeedback(); + void Focus(); // WidgetDelegate overrides. const views::Widget* GetWidget() const override;
diff --git a/chrome/browser/chromeos/app_mode/app_session.cc b/chrome/browser/chromeos/app_mode/app_session.cc index 850615e..6f2e374 100644 --- a/chrome/browser/chromeos/app_mode/app_session.cc +++ b/chrome/browser/chromeos/app_mode/app_session.cc
@@ -120,8 +120,9 @@ void OnAppWindowRemoved(AppWindow* app_window) override { if (window_registry_->GetAppWindowsForApp(app_id_).empty()) { - if (DemoAppLauncher::IsDemoAppSession( - user_manager::UserManager::Get()->GetActiveUser()->email())) { + if (DemoAppLauncher::IsDemoAppSession(user_manager::UserManager::Get() + ->GetActiveUser() + ->GetAccountId())) { // If we were in demo mode, we disabled all our network technologies, // re-enable them. NetworkStateHandler* handler = @@ -188,7 +189,7 @@ // For a demo app, we don't need to either setup the update service or // the idle app name notification. if (DemoAppLauncher::IsDemoAppSession( - user_manager::UserManager::Get()->GetActiveUser()->email())) + user_manager::UserManager::Get()->GetActiveUser()->GetAccountId())) return; // Set the app_id for the current instance of KioskAppUpdateService.
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_data.cc b/chrome/browser/chromeos/app_mode/kiosk_app_data.cc index ed463867..0cb0c98 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_data.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_data.cc
@@ -395,14 +395,13 @@ KioskAppData::KioskAppData(KioskAppDataDelegate* delegate, const std::string& app_id, - const std::string& user_id, + const AccountId& account_id, const GURL& update_url) : delegate_(delegate), status_(STATUS_INIT), app_id_(app_id), - user_id_(user_id), - update_url_(update_url) { -} + account_id_(account_id), + update_url_(update_url) {} KioskAppData::~KioskAppData() {}
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_data.h b/chrome/browser/chromeos/app_mode/kiosk_app_data.h index c50fec8..edcf76f2 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_data.h +++ b/chrome/browser/chromeos/app_mode/kiosk_app_data.h
@@ -12,6 +12,7 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/extensions/webstore_data_fetcher_delegate.h" +#include "components/signin/core/account_id/account_id.h" #include "ui/gfx/image/image_skia.h" #include "url/gurl.h" @@ -48,7 +49,7 @@ KioskAppData(KioskAppDataDelegate* delegate, const std::string& app_id, - const std::string& user_id, + const AccountId& account_id, const GURL& update_url); ~KioskAppData() override; @@ -73,7 +74,7 @@ bool IsFromWebStore() const; const std::string& app_id() const { return app_id_; } - const std::string& user_id() const { return user_id_; } + const AccountId& account_id() const { return account_id_; } const std::string& name() const { return name_; } const GURL& update_url() const { return update_url_; } const gfx::ImageSkia& icon() const { return icon_; } @@ -145,7 +146,7 @@ Status status_; std::string app_id_; - std::string user_id_; + AccountId account_id_; std::string name_; GURL update_url_; gfx::ImageSkia icon_;
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc b/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc index b48cb02c..4a39547 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_manager.cc
@@ -35,13 +35,16 @@ #include "chrome/common/extensions/extension_constants.h" #include "chromeos/chromeos_paths.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/login/user_names.h" #include "chromeos/settings/cros_settings_names.h" #include "components/ownership/owner_key_util.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/extension_urls.h" @@ -61,30 +64,34 @@ return app_id + '@' + kKioskAppAccountDomain; } -void ScheduleDelayedCryptohomeRemoval(const std::string& user_id, +void ScheduleDelayedCryptohomeRemoval(const cryptohome::Identification& id, const std::string& app_id) { PrefService* local_state = g_browser_process->local_state(); DictionaryPrefUpdate dict_update(local_state, kKioskUsersToRemove); - dict_update->SetStringWithoutPathExpansion(user_id, app_id); + + // We are using cryptohome::Identification here because it cannot change + // before actual removal will take place. (Possible cryptohome migration + // happens only on session start, but deletion should happen before it.) + dict_update->SetStringWithoutPathExpansion(id.id(), app_id); local_state->CommitPendingWrite(); } -void CancelDelayedCryptohomeRemoval(const std::string& user_id) { +void CancelDelayedCryptohomeRemoval(const cryptohome::Identification& id) { PrefService* local_state = g_browser_process->local_state(); DictionaryPrefUpdate dict_update(local_state, kKioskUsersToRemove); - dict_update->RemoveWithoutPathExpansion(user_id, nullptr); + dict_update->RemoveWithoutPathExpansion(id.id(), nullptr); local_state->CommitPendingWrite(); } -void OnRemoveAppCryptohomeComplete(const std::string& user_id, +void OnRemoveAppCryptohomeComplete(const cryptohome::Identification& id, const std::string& app, const base::Closure& callback, bool success, cryptohome::MountError return_code) { if (success) { - CancelDelayedCryptohomeRemoval(user_id); + CancelDelayedCryptohomeRemoval(id); } else { - ScheduleDelayedCryptohomeRemoval(user_id, app); + ScheduleDelayedCryptohomeRemoval(id, app); LOG(ERROR) << "Remove cryptohome for " << app << " failed, return code: " << return_code; } @@ -102,16 +109,14 @@ const base::DictionaryValue* dict = local_state->GetDictionary(kKioskUsersToRemove); for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) { - std::string user_id = it.key(); + const cryptohome::Identification cryptohome_id( + cryptohome::Identification::FromString(it.key())); std::string app_id; it.value().GetAsString(&app_id); VLOG(1) << "Removing obsolete crypthome for " << app_id; cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( - user_id, - base::Bind(&OnRemoveAppCryptohomeComplete, - user_id, - app_id, - base::Closure())); + cryptohome_id, base::Bind(&OnRemoveAppCryptohomeComplete, cryptohome_id, + app_id, base::Closure())); } } @@ -171,15 +176,17 @@ bool is_extension_pending, bool auto_launched_with_zero_delay) : app_id(data.app_id()), - user_id(data.user_id()), + account_id(data.account_id()), name(data.name()), icon(data.icon()), required_platform_version(data.required_platform_version()), is_loading(data.IsLoading() || is_extension_pending), was_auto_launched_with_zero_delay(auto_launched_with_zero_delay) {} -KioskAppManager::App::App() : is_loading(false), - was_auto_launched_with_zero_delay(false) {} +KioskAppManager::App::App() + : account_id(EmptyAccountId()), + is_loading(false), + was_auto_launched_with_zero_delay(false) {} KioskAppManager::App::~App() {} @@ -642,6 +649,9 @@ if (it->account_id == auto_login_account_id) auto_launch_app_id_ = it->kiosk_app_id; + // Note that app ids are not canonical, i.e. they can contain upper + // case letters. + const AccountId account_id(AccountId::FromUserEmail(it->user_id)); std::map<std::string, KioskAppData*>::iterator old_it = old_apps.find(it->kiosk_app_id); if (old_it != old_apps.end()) { @@ -649,11 +659,11 @@ old_apps.erase(old_it); } else { KioskAppData* new_app = new KioskAppData( - this, it->kiosk_app_id, it->user_id, GURL(it->kiosk_app_update_url)); + this, it->kiosk_app_id, account_id, GURL(it->kiosk_app_update_url)); apps_.push_back(new_app); // Takes ownership of |new_app|. new_app->Load(); } - CancelDelayedCryptohomeRemoval(it->user_id); + CancelDelayedCryptohomeRemoval(cryptohome::Identification(account_id)); } base::Closure cryptohomes_barrier_closure; @@ -663,7 +673,7 @@ if (active_user) { const AccountId active_account_id = active_user->GetAccountId(); for (const auto& it : old_apps) { - if (it.second->user_id() == active_account_id.GetUserEmail()) { + if (it.second->account_id() == active_account_id) { VLOG(1) << "Currently running kiosk app removed from policy, exiting"; cryptohomes_barrier_closure = BarrierClosure( old_apps.size(), base::Bind(&chrome::AttemptUserExit)); @@ -677,12 +687,10 @@ for (std::map<std::string, KioskAppData*>::iterator it = old_apps.begin(); it != old_apps.end(); ++it) { it->second->ClearCache(); + const cryptohome::Identification cryptohome_id(it->second->account_id()); cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( - it->second->user_id(), - base::Bind(&OnRemoveAppCryptohomeComplete, - it->second->user_id(), - it->first, - cryptohomes_barrier_closure)); + cryptohome_id, base::Bind(&OnRemoveAppCryptohomeComplete, cryptohome_id, + it->first, cryptohomes_barrier_closure)); apps_to_remove.push_back(it->second->app_id()); } STLDeleteValues(&old_apps);
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_manager.h b/chrome/browser/chromeos/app_mode/kiosk_app_manager.h index c3877b6..1bc27f1eb 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_manager.h +++ b/chrome/browser/chromeos/app_mode/kiosk_app_manager.h
@@ -20,6 +20,7 @@ #include "chrome/browser/chromeos/extensions/external_cache.h" #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" #include "chrome/browser/chromeos/settings/cros_settings.h" +#include "components/signin/core/account_id/account_id.h" #include "ui/gfx/image/image_skia.h" class PrefRegistrySimple; @@ -70,7 +71,7 @@ ~App(); std::string app_id; - std::string user_id; + AccountId account_id; std::string name; gfx::ImageSkia icon; std::string required_platform_version;
diff --git a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc index d8565204..4c2fe614 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc
@@ -119,10 +119,10 @@ //////////////////////////////////////////////////////////////////////////////// // KioskProfileLoader -KioskProfileLoader::KioskProfileLoader(const std::string& app_user_id, +KioskProfileLoader::KioskProfileLoader(const AccountId& app_account_id, bool use_guest_mount, Delegate* delegate) - : user_id_(app_user_id), + : account_id_(app_account_id), use_guest_mount_(use_guest_mount), delegate_(delegate) {} @@ -137,7 +137,7 @@ void KioskProfileLoader::LoginAsKioskAccount() { login_performer_.reset(new ChromeLoginPerformer(this)); - login_performer_->LoginAsKioskAccount(user_id_, use_guest_mount_); + login_performer_->LoginAsKioskAccount(account_id_, use_guest_mount_); } void KioskProfileLoader::ReportLaunchResult(KioskAppLaunchError::Error error) { @@ -160,7 +160,7 @@ // user as a demo user. UserContext context = user_context; if (context.GetAccountId() == login::GuestAccountId()) - context.SetUserID(login::DemoAccountId().GetUserEmail()); + context.SetAccountId(login::DemoAccountId()); UserSessionManager::GetInstance()->StartSession( context, UserSessionManager::PRIMARY_USER_SESSION, false, // has_auth_cookies
diff --git a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.h b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.h index 01d94072..0b15265 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.h +++ b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.h
@@ -13,6 +13,7 @@ #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chromeos/login/auth/login_performer.h" +#include "components/signin/core/account_id/account_id.h" class Profile; @@ -33,7 +34,7 @@ virtual ~Delegate() {} }; - KioskProfileLoader(const std::string& app_user_id, + KioskProfileLoader(const AccountId& app_account_id, bool use_guest_mount, Delegate* delegate); @@ -58,7 +59,7 @@ // UserSessionManagerDelegate implementation: void OnProfilePrepared(Profile* profile, bool browser_launched) override; - std::string user_id_; + const AccountId account_id_; bool use_guest_mount_; Delegate* delegate_; scoped_ptr<CryptohomedChecker> cryptohomed_checker_;
diff --git a/chrome/browser/chromeos/attestation/attestation_policy_observer.cc b/chrome/browser/chromeos/attestation/attestation_policy_observer.cc index e400fa8..71930dd 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_observer.cc +++ b/chrome/browser/chromeos/attestation/attestation_policy_observer.cc
@@ -17,11 +17,14 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chromeos/attestation/attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_manager.h" +#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/known_user.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "net/cert/pem_tokenizer.h" @@ -171,11 +174,9 @@ weak_factory_.GetWeakPtr()); cryptohome_client_->TpmAttestationDoesKeyExist( KEY_DEVICE, - std::string(), // Not used. + cryptohome::Identification(), // Not used. kEnterpriseMachineKey, - base::Bind(DBusBoolRedirectCallback, - on_does_exist, - on_does_not_exist, + base::Bind(DBusBoolRedirectCallback, on_does_exist, on_does_not_exist, base::Bind(&AttestationPolicyObserver::Reschedule, weak_factory_.GetWeakPtr()), FROM_HERE)); @@ -185,22 +186,21 @@ // We can reuse the dbus callback handler logic. attestation_flow_->GetCertificate( PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - std::string(), // Not used. - std::string(), // Not used. - true, // Force a new key to be generated. + EmptyAccountId(), // Not used. + std::string(), // Not used. + true, // Force a new key to be generated. base::Bind(DBusStringCallback, base::Bind(&AttestationPolicyObserver::UploadCertificate, weak_factory_.GetWeakPtr()), base::Bind(&AttestationPolicyObserver::Reschedule, weak_factory_.GetWeakPtr()), - FROM_HERE, - DBUS_METHOD_CALL_SUCCESS)); + FROM_HERE, DBUS_METHOD_CALL_SUCCESS)); } void AttestationPolicyObserver::GetExistingCertificate() { cryptohome_client_->TpmAttestationGetCertificate( KEY_DEVICE, - std::string(), // Not used. + cryptohome::Identification(), // Not used. kEnterpriseMachineKey, base::Bind(DBusStringCallback, base::Bind(&AttestationPolicyObserver::CheckCertificateExpiry, @@ -272,10 +272,9 @@ base::Callback<void(const std::string&)> callback) { cryptohome_client_->TpmAttestationGetKeyPayload( KEY_DEVICE, - std::string(), // Not used. + cryptohome::Identification(), // Not used. kEnterpriseMachineKey, - base::Bind(DBusStringCallback, - callback, + base::Bind(DBusStringCallback, callback, base::Bind(&AttestationPolicyObserver::Reschedule, weak_factory_.GetWeakPtr()), FROM_HERE)); @@ -301,14 +300,10 @@ } cryptohome_client_->TpmAttestationSetKeyPayload( KEY_DEVICE, - std::string(), // Not used. - kEnterpriseMachineKey, - new_payload, - base::Bind(DBusBoolRedirectCallback, - base::Closure(), - base::Closure(), - base::Closure(), - FROM_HERE)); + cryptohome::Identification(), // Not used. + kEnterpriseMachineKey, new_payload, + base::Bind(DBusBoolRedirectCallback, base::Closure(), base::Closure(), + base::Closure(), FROM_HERE)); } void AttestationPolicyObserver::Reschedule() {
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow.cc b/chrome/browser/chromeos/attestation/platform_verification_flow.cc index a756de0..794ed3a 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow.cc +++ b/chrome/browser/chromeos/attestation/platform_verification_flow.cc
@@ -23,6 +23,7 @@ #include "chromeos/attestation/attestation_flow.h" #include "chromeos/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -249,11 +250,12 @@ return; } - GetCertificate(context, user->email(), false /* Don't force a new key */); + GetCertificate(context, user->GetAccountId(), + false /* Don't force a new key */); } void PlatformVerificationFlow::GetCertificate(const ChallengeContext& context, - const std::string& user_id, + const AccountId& account_id, bool force_new_key) { scoped_ptr<base::Timer> timer(new base::Timer(false, // Don't retain. false)); // Don't repeat. @@ -263,23 +265,17 @@ context); timer->Start(FROM_HERE, timeout_delay_, timeout_callback); - AttestationFlow::CertificateCallback certificate_callback = base::Bind( - &PlatformVerificationFlow::OnCertificateReady, - this, - context, - user_id, - base::Passed(&timer)); - attestation_flow_->GetCertificate( - PROFILE_CONTENT_PROTECTION_CERTIFICATE, - user_id, - context.service_id, - force_new_key, - certificate_callback); + AttestationFlow::CertificateCallback certificate_callback = + base::Bind(&PlatformVerificationFlow::OnCertificateReady, this, context, + account_id, base::Passed(&timer)); + attestation_flow_->GetCertificate(PROFILE_CONTENT_PROTECTION_CERTIFICATE, + account_id, context.service_id, + force_new_key, certificate_callback); } void PlatformVerificationFlow::OnCertificateReady( const ChallengeContext& context, - const std::string& user_id, + const AccountId& account_id, scoped_ptr<base::Timer> timer, bool operation_success, const std::string& certificate_chain) { @@ -301,20 +297,18 @@ ExpiryStatus expiry_status = CheckExpiry(certificate_chain); ReportExpiryStatus(expiry_status); if (expiry_status == EXPIRY_STATUS_EXPIRED) { - GetCertificate(context, user_id, true /* Force a new key */); + GetCertificate(context, account_id, true /* Force a new key */); return; } bool is_expiring_soon = (expiry_status == EXPIRY_STATUS_EXPIRING_SOON); cryptohome::AsyncMethodCaller::DataCallback cryptohome_callback = base::Bind(&PlatformVerificationFlow::OnChallengeReady, this, context, - user_id, certificate_chain, is_expiring_soon); + account_id, certificate_chain, is_expiring_soon); std::string key_name = kContentProtectionKeyPrefix; key_name += context.service_id; - async_caller_->TpmAttestationSignSimpleChallenge(KEY_USER, - user_id, - key_name, - context.challenge, - cryptohome_callback); + async_caller_->TpmAttestationSignSimpleChallenge( + KEY_USER, cryptohome::Identification(account_id), key_name, + context.challenge, cryptohome_callback); } void PlatformVerificationFlow::OnCertificateTimeout( @@ -325,7 +319,7 @@ void PlatformVerificationFlow::OnChallengeReady( const ChallengeContext& context, - const std::string& user_id, + const AccountId& account_id, const std::string& certificate_chain, bool is_expiring_soon, bool operation_success, @@ -352,7 +346,7 @@ base::Bind(&PlatformVerificationFlow::RenewCertificateCallback, this, certificate_chain); attestation_flow_->GetCertificate(PROFILE_CONTENT_PROTECTION_CERTIFICATE, - user_id, context.service_id, + account_id, context.service_id, true, // force_new_key renew_callback); }
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow.h b/chrome/browser/chromeos/attestation/platform_verification_flow.h index 55f6d13..fd7576b 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow.h +++ b/chrome/browser/chromeos/attestation/platform_verification_flow.h
@@ -16,6 +16,8 @@ #include "base/timer/timer.h" #include "url/gurl.h" +class AccountId; + namespace content { class WebContents; } @@ -176,17 +178,17 @@ bool attestation_prepared); // Initiates the flow to get a platform key certificate. The arguments to - // ChallengePlatformKey are in |context|. |user_id| identifies the user for - // which to get a certificate. If |force_new_key| is true then any existing - // key for the same user and service will be ignored and a new key will be - // generated and certified. + // ChallengePlatformKey are in |context|. |account_id| identifies the user + // for which to get a certificate. If |force_new_key| is true then any + // existing key for the same user and service will be ignored and a new key + // will be generated and certified. void GetCertificate(const ChallengeContext& context, - const std::string& user_id, + const AccountId& account_id, bool force_new_key); // A callback called when an attestation certificate request operation // completes. The arguments to ChallengePlatformKey are in |context|. - // |user_id| identifies the user for which the certificate was requested. + // |account_id| identifies the user for which the certificate was requested. // |operation_success| is true iff the certificate request operation // succeeded. |certificate_chain| holds the certificate for the platform key // on success. If the certificate request was successful, this method invokes @@ -194,7 +196,7 @@ // method being called, this method does nothing - notably, the callback is // not invoked. void OnCertificateReady(const ChallengeContext& context, - const std::string& user_id, + const AccountId& account_id, scoped_ptr<base::Timer> timer, bool operation_success, const std::string& certificate_chain); @@ -207,14 +209,14 @@ // A callback called when a challenge signing request has completed. The // |certificate_chain| is the platform certificate chain for the key which // signed the |challenge|. The arguments to ChallengePlatformKey are in - // |context|. |user_id| identifies the user for which the certificate was + // |context|. |account_id| identifies the user for which the certificate was // requested. |is_expiring_soon| will be set iff a certificate in the // |certificate_chain| is expiring soon. |operation_success| is true iff the // challenge signing operation was successful. If it was successful, // |response_data| holds the challenge response and the method will invoke // |context.callback|. void OnChallengeReady(const ChallengeContext& context, - const std::string& user_id, + const AccountId& account_id, const std::string& certificate_chain, bool is_expiring_soon, bool operation_success,
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc b/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc index 14dbb66..58897b3 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc +++ b/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc
@@ -164,22 +164,23 @@ // that there are no calls to the attestation service. Thus, a test must // explicitly expect these calls or the mocks will fail the test. + const AccountId account_id = AccountId::FromUserEmail(kTestEmail); // Configure the mock AttestationFlow to call FakeGetCertificate. EXPECT_CALL(mock_attestation_flow_, GetCertificate(PROFILE_CONTENT_PROTECTION_CERTIFICATE, - kTestEmail, kTestID, _, _)) - .WillRepeatedly(WithArgs<4>(Invoke( - this, &PlatformVerificationFlowTest::FakeGetCertificate))); + account_id, kTestID, _, _)) + .WillRepeatedly(WithArgs<4>( + Invoke(this, &PlatformVerificationFlowTest::FakeGetCertificate))); // Configure the mock AsyncMethodCaller to call FakeSignChallenge. std::string expected_key_name = std::string(kContentProtectionKeyPrefix) + std::string(kTestID); EXPECT_CALL(mock_async_caller_, - TpmAttestationSignSimpleChallenge(KEY_USER, kTestEmail, - expected_key_name, - kTestChallenge, _)) - .WillRepeatedly(WithArgs<4>(Invoke( - this, &PlatformVerificationFlowTest::FakeSignChallenge))); + TpmAttestationSignSimpleChallenge( + KEY_USER, cryptohome::Identification(account_id), + expected_key_name, kTestChallenge, _)) + .WillRepeatedly(WithArgs<4>( + Invoke(this, &PlatformVerificationFlowTest::FakeSignChallenge))); } void FakeGetCertificate(
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index 7ec7f7c..cd13f690 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -93,6 +93,7 @@ #include "chromeos/chromeos_paths.h" #include "chromeos/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/homedir_methods.h" #include "chromeos/cryptohome/system_salt_getter.h" #include "chromeos/dbus/dbus_thread_manager.h" @@ -328,7 +329,8 @@ !parsed_command_line().HasSwitch(switches::kLoginUser) && !parsed_command_line().HasSwitch(switches::kGuestSession)) { singleton_command_line->AppendSwitchASCII( - switches::kLoginUser, login::StubAccountId().GetUserEmail()); + switches::kLoginUser, + cryptohome::Identification(login::StubAccountId()).id()); if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) { singleton_command_line->AppendSwitchASCII(switches::kLoginProfile, chrome::kTestUserProfileDir); @@ -515,11 +517,13 @@ ChromeBrowserMainPartsLinux::PreProfileInit(); if (immediate_login) { - const std::string user_email = login::CanonicalizeUserID( - parsed_command_line().GetSwitchValueASCII(switches::kLoginUser)); + const std::string cryptohome_id = + parsed_command_line().GetSwitchValueASCII(switches::kLoginUser); + const AccountId account_id( + cryptohome::Identification::FromString(cryptohome_id).GetAccountId()); + user_manager::UserManager* user_manager = user_manager::UserManager::Get(); - const AccountId account_id(AccountId::FromUserEmail(user_email)); if (policy::IsDeviceLocalAccountUser(account_id.GetUserEmail(), NULL) && !user_manager->IsKnownUser(account_id)) { // When a device-local account is removed, its policy is deleted from disk @@ -536,7 +540,7 @@ std::string user_id_hash = parsed_command_line().GetSwitchValueASCII(switches::kLoginProfile); user_manager->UserLoggedIn(account_id, user_id_hash, true); - VLOG(1) << "Relaunching browser for user: " << user_email + VLOG(1) << "Relaunching browser for user: " << account_id.Serialize() << " with hash: " << user_id_hash; } }
diff --git a/chrome/browser/chromeos/login/app_launch_controller.cc b/chrome/browser/chromeos/login/app_launch_controller.cc index 057671f..c8c6579 100644 --- a/chrome/browser/chromeos/login/app_launch_controller.cc +++ b/chrome/browser/chromeos/login/app_launch_controller.cc
@@ -29,6 +29,7 @@ #include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chromeos/settings/cros_settings_names.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/notification_service.h" #include "extensions/browser/app_window/app_window.h" @@ -159,9 +160,8 @@ if (delay == 0) KioskAppManager::Get()->SetAppWasAutoLaunchedWithZeroDelay(app_id_); } - kiosk_profile_loader_.reset( - new KioskProfileLoader(app.user_id, false, this)); + new KioskProfileLoader(app.account_id, false, this)); kiosk_profile_loader_->Start(); }
diff --git a/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc b/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc index 606ca65..de73217 100644 --- a/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc +++ b/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc
@@ -266,10 +266,10 @@ cryptohome::KeyDefinition::ProviderData("salt")); key_definition.provider_data.back().bytes = std::move(salt); } - EXPECT_CALL(*mock_homedir_methods_, - GetKeyDataEx(cryptohome::Identification( - user_context_.GetAccountId().GetUserEmail()), - kCryptohomeGAIAKeyLabel, _)) + EXPECT_CALL( + *mock_homedir_methods_, + GetKeyDataEx(cryptohome::Identification(user_context_.GetAccountId()), + kCryptohomeGAIAKeyLabel, _)) .WillOnce(WithArg<2>(Invoke( this, &CryptohomeAuthenticatorTest::InvokeGetDataExCallback))); } @@ -285,10 +285,10 @@ kCryptohomeGAIAKeyLabel, cryptohome::PRIV_DEFAULT)); } - EXPECT_CALL(*mock_homedir_methods_, - MountEx(cryptohome::Identification( - user_context_.GetAccountId().GetUserEmail()), - cryptohome::Authorization(auth_key), mount, _)) + EXPECT_CALL( + *mock_homedir_methods_, + MountEx(cryptohome::Identification(user_context_.GetAccountId()), + cryptohome::Authorization(auth_key), mount, _)) .Times(1) .RetiresOnSaturation(); } @@ -562,8 +562,9 @@ // Set up mock async method caller to respond successfully to a cryptohome // remove attempt. mock_caller_->SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncRemove(user_context_.GetAccountId().GetUserEmail(), _)) + EXPECT_CALL( + *mock_caller_, + AsyncRemove(cryptohome::Identification(user_context_.GetAccountId()), _)) .Times(1) .RetiresOnSaturation(); @@ -585,8 +586,9 @@ // Set up mock async method caller to fail a cryptohome remove attempt. mock_caller_->SetUp(false, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncRemove(user_context_.GetAccountId().GetUserEmail(), _)) + EXPECT_CALL( + *mock_caller_, + AsyncRemove(cryptohome::Identification(user_context_.GetAccountId()), _)) .Times(1) .RetiresOnSaturation(); @@ -616,9 +618,10 @@ // Set up mock async method caller to respond successfully to a key migration. mock_caller_->SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncMigrateKey(user_context_.GetAccountId().GetUserEmail(), _, - transformed_key_.GetSecret(), _)) + EXPECT_CALL( + *mock_caller_, + AsyncMigrateKey(cryptohome::Identification(user_context_.GetAccountId()), + _, transformed_key_.GetSecret(), _)) .Times(1) .RetiresOnSaturation(); @@ -641,9 +644,10 @@ // Set up mock async method caller to fail a key migration attempt, // asserting that the wrong password was used. mock_caller_->SetUp(false, cryptohome::MOUNT_ERROR_KEY_FAILURE); - EXPECT_CALL(*mock_caller_, - AsyncMigrateKey(user_context_.GetAccountId().GetUserEmail(), _, - transformed_key_.GetSecret(), _)) + EXPECT_CALL( + *mock_caller_, + AsyncMigrateKey(cryptohome::Identification(user_context_.GetAccountId()), + _, transformed_key_.GetSecret(), _)) .Times(1) .RetiresOnSaturation(); @@ -732,8 +736,10 @@ // Set up mock async method caller to respond successfully to a cryptohome // key-check attempt. mock_caller_->SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(*mock_caller_, - AsyncCheckKey(user_context_.GetAccountId().GetUserEmail(), _, _)) + EXPECT_CALL( + *mock_caller_, + AsyncCheckKey(cryptohome::Identification(user_context_.GetAccountId()), _, + _)) .Times(1) .RetiresOnSaturation();
diff --git a/chrome/browser/chromeos/login/chrome_restart_request.cc b/chrome/browser/chromeos/login/chrome_restart_request.cc index 037af8c..cdd081bc 100644 --- a/chrome/browser/chromeos/login/chrome_restart_request.cc +++ b/chrome/browser/chromeos/login/chrome_restart_request.cc
@@ -28,6 +28,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "chromeos/login/user_names.h" @@ -322,8 +323,9 @@ otr_switches.SetString(switches::kGuestSession, std::string()); otr_switches.SetString(::switches::kIncognito, std::string()); otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel); - otr_switches.SetString(switches::kLoginUser, - login::GuestAccountId().GetUserEmail()); + otr_switches.SetString( + switches::kLoginUser, + cryptohome::Identification(login::GuestAccountId()).id()); // Override the home page. otr_switches.SetString(::switches::kHomePage,
diff --git a/chrome/browser/chromeos/login/crash_restore_browsertest.cc b/chrome/browser/chromeos/login/crash_restore_browsertest.cc index 4d27624e..41ded0b6 100644 --- a/chrome/browser/chromeos/login/crash_restore_browsertest.cc +++ b/chrome/browser/chromeos/login/crash_restore_browsertest.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/chromeos/login/session/user_session_manager_test_api.h" #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_session_manager_client.h" @@ -40,10 +41,10 @@ ~CrashRestoreSimpleTest() override {} void SetUpCommandLine(base::CommandLine* command_line) override { - command_line->AppendSwitchASCII(switches::kLoginUser, kUserId1); + command_line->AppendSwitchASCII(switches::kLoginUser, cryptohome_id1_.id()); command_line->AppendSwitchASCII( switches::kLoginProfile, - CryptohomeClient::GetStubSanitizedUsername(kUserId1)); + CryptohomeClient::GetStubSanitizedUsername(cryptohome_id1_)); } void SetUpInProcessBrowserTestFixture() override { @@ -51,18 +52,27 @@ session_manager_client_ = new FakeSessionManagerClient; chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( scoped_ptr<SessionManagerClient>(session_manager_client_)); - session_manager_client_->StartSession(kUserId1); + session_manager_client_->StartSession(cryptohome_id1_); } FakeSessionManagerClient* session_manager_client_; + const AccountId account_id1_ = AccountId::FromUserEmail(kUserId1); + const AccountId account_id2_ = AccountId::FromUserEmail(kUserId2); + const AccountId account_id3_ = AccountId::FromUserEmail(kUserId3); + const cryptohome::Identification cryptohome_id1_ = + cryptohome::Identification(account_id1_); + const cryptohome::Identification cryptohome_id2_ = + cryptohome::Identification(account_id2_); + const cryptohome::Identification cryptohome_id3_ = + cryptohome::Identification(account_id3_); }; IN_PROC_BROWSER_TEST_F(CrashRestoreSimpleTest, RestoreSessionForOneUser) { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); user_manager::User* user = user_manager->GetActiveUser(); ASSERT_TRUE(user); - EXPECT_EQ(kUserId1, user->email()); - EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(kUserId1), + EXPECT_EQ(account_id1_, user->GetAccountId()); + EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(cryptohome_id1_), user->username_hash()); EXPECT_EQ(1UL, user_manager->GetLoggedInUsers().size()); } @@ -116,8 +126,8 @@ void SetUpInProcessBrowserTestFixture() override { CrashRestoreSimpleTest::SetUpInProcessBrowserTestFixture(); - session_manager_client_->StartSession(kUserId2); - session_manager_client_->StartSession(kUserId3); + session_manager_client_->StartSession(cryptohome_id2_); + session_manager_client_->StartSession(cryptohome_id3_); } }; @@ -138,21 +148,21 @@ user_manager::UserManager* user_manager = user_manager::UserManager::Get(); user_manager::User* user = user_manager->GetActiveUser(); ASSERT_TRUE(user); - EXPECT_EQ(kUserId3, user->email()); - EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(kUserId3), + EXPECT_EQ(account_id3_, user->GetAccountId()); + EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(cryptohome_id3_), user->username_hash()); const user_manager::UserList& users = user_manager->GetLoggedInUsers(); ASSERT_EQ(3UL, users.size()); // User that becomes active moves to the beginning of the list. - EXPECT_EQ(kUserId3, users[0]->email()); - EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(kUserId3), + EXPECT_EQ(account_id3_, users[0]->GetAccountId()); + EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(cryptohome_id3_), users[0]->username_hash()); - EXPECT_EQ(kUserId2, users[1]->email()); - EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(kUserId2), + EXPECT_EQ(account_id2_, users[1]->GetAccountId()); + EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(cryptohome_id2_), users[1]->username_hash()); - EXPECT_EQ(kUserId1, users[2]->email()); - EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(kUserId1), + EXPECT_EQ(account_id1_, users[2]->GetAccountId()); + EXPECT_EQ(CryptohomeClient::GetStubSanitizedUsername(cryptohome_id1_), users[2]->username_hash()); }
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.cc b/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.cc index e5f452c..5c9c45d 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.cc
@@ -49,14 +49,14 @@ void DemoAppLauncher::StartDemoAppLaunch() { DVLOG(1) << "Launching demo app..."; // user_id = DemoAppUserId, force_emphemeral = true, delegate = this. - kiosk_profile_loader_.reset(new KioskProfileLoader( - login::DemoAccountId().GetUserEmail(), true, this)); + kiosk_profile_loader_.reset( + new KioskProfileLoader(login::DemoAccountId(), true, this)); kiosk_profile_loader_->Start(); } // static -bool DemoAppLauncher::IsDemoAppSession(const std::string& user_id) { - return user_id == login::DemoAccountId().GetUserEmail(); +bool DemoAppLauncher::IsDemoAppSession(const AccountId& account_id) { + return account_id == login::DemoAccountId(); } // static
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h b/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h index dfc3a8f1..74322bd 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h +++ b/chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h
@@ -12,6 +12,8 @@ #include "base/memory/scoped_ptr.h" #include "chrome/browser/chromeos/app_mode/kiosk_profile_loader.h" +class AccountId; + namespace base { class FilePath; } @@ -26,7 +28,7 @@ void StartDemoAppLaunch(); - static bool IsDemoAppSession(const std::string& user_id); + static bool IsDemoAppSession(const AccountId& account_id); static void SetDemoAppPathForTesting(const base::FilePath& path); static const char kDemoAppId[];
diff --git a/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc b/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc index 6b3a82b..536e7c2 100644 --- a/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc +++ b/chrome/browser/chromeos/login/easy_unlock/bootstrap_user_context_initializer.cc
@@ -12,6 +12,8 @@ #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/signin/easy_unlock_service_signin_chromeos.h" +#include "chromeos/login/user_names.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user_manager.h" #include "crypto/random.h" #include "google_apis/gaia/gaia_constants.h" @@ -175,8 +177,8 @@ return; } - user_context_.SetUserID(email); - user_context_.SetGaiaID(gaia_id); + user_context_.SetAccountId(user_manager::known_user::GetAccountId( + login::CanonicalizeUserID(email), gaia_id)); StartCheckExistingKeys(); }
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc index ea8a1220..360e825 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_create_keys_operation.cc
@@ -355,9 +355,7 @@ kEasyUnlockKeyMetaNameWrappedSecret, device->wrapped_secret)); // Add cryptohome key. - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context_.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + const cryptohome::Identification id(user_context_.GetAccountId()); scoped_ptr<Key> auth_key(new Key(*user_context_.GetKey())); if (auth_key->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN)
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc index fdfe3bfb..46e75eb 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc
@@ -36,9 +36,7 @@ } void EasyUnlockGetKeysOperation::GetKeyData() { - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context_.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + const cryptohome::Identification id(user_context_.GetAccountId()); cryptohome::HomedirMethods::GetInstance()->GetKeyDataEx( id, EasyUnlockKeyManager::GetKeyLabel(key_index_),
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc index 9ead3ef..2a61962d 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_remove_keys_operation.cc
@@ -47,9 +47,7 @@ } void EasyUnlockRemoveKeysOperation::RemoveKey() { - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context_.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(user_context_.GetAccountId()); const Key* const auth_key = user_context_.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel());
diff --git a/chrome/browser/chromeos/login/existing_user_controller.cc b/chrome/browser/chromeos/login/existing_user_controller.cc index d265d842..6903f74 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.cc +++ b/chrome/browser/chromeos/login/existing_user_controller.cc
@@ -762,8 +762,8 @@ } void ExistingUserController::LoginAsGuest() { - PerformPreLoginActions(UserContext(user_manager::USER_TYPE_GUEST, - login::GuestAccountId().GetUserEmail())); + PerformPreLoginActions( + UserContext(user_manager::USER_TYPE_GUEST, login::GuestAccountId())); bool allow_guest; cros_settings_->GetBoolean(kAccountsPrefAllowGuest, &allow_guest); @@ -866,20 +866,21 @@ const std::vector<policy::DeviceLocalAccount> device_local_accounts = policy::GetDeviceLocalAccounts(cros_settings_); - public_session_auto_login_username_.clear(); + public_session_auto_login_account_id_ = EmptyAccountId(); for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { if (it->account_id == auto_login_account_id) { - public_session_auto_login_username_ = it->user_id; + public_session_auto_login_account_id_ = + AccountId::FromUserEmail(it->user_id); break; } } const user_manager::User* user = user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(public_session_auto_login_username_)); + public_session_auto_login_account_id_); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) - public_session_auto_login_username_.clear(); + public_session_auto_login_account_id_ = EmptyAccountId(); if (!cros_settings_->GetInteger( kAccountsPrefDeviceLocalAccountAutoLoginDelay, @@ -887,7 +888,7 @@ public_session_auto_login_delay_ = 0; } - if (!public_session_auto_login_username_.empty()) + if (public_session_auto_login_account_id_.is_valid()) StartPublicSessionAutoLoginTimer(); else StopPublicSessionAutoLoginTimer(); @@ -902,9 +903,10 @@ } void ExistingUserController::OnPublicSessionAutoLoginTimerFire() { - CHECK(signin_screen_ready_ && !public_session_auto_login_username_.empty()); + CHECK(signin_screen_ready_ && + public_session_auto_login_account_id_.is_valid()); Login(UserContext(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_auto_login_username_), + public_session_auto_login_account_id_), SigninSpecifics()); } @@ -914,9 +916,8 @@ } void ExistingUserController::StartPublicSessionAutoLoginTimer() { - if (!signin_screen_ready_ || - is_login_in_progress_ || - public_session_auto_login_username_.empty()) { + if (!signin_screen_ready_ || is_login_in_progress_ || + !public_session_auto_login_account_id_.is_valid()) { return; }
diff --git a/chrome/browser/chromeos/login/existing_user_controller.h b/chrome/browser/chromeos/login/existing_user_controller.h index 2d18cfe..c9dd991e 100644 --- a/chrome/browser/chromeos/login/existing_user_controller.h +++ b/chrome/browser/chromeos/login/existing_user_controller.h
@@ -26,6 +26,7 @@ #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chromeos/login/auth/login_performer.h" #include "chromeos/login/auth/user_context.h" +#include "components/signin/core/account_id/account_id.h" #include "components/user_manager/user.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" @@ -256,8 +257,8 @@ // Public session auto-login timeout, in milliseconds. int public_session_auto_login_delay_; - // Username for public session auto-login. - std::string public_session_auto_login_username_; + // AccountId for public session auto-login. + AccountId public_session_auto_login_account_id_ = EmptyAccountId(); // Used to execute login operations. scoped_ptr<LoginPerformer> login_performer_;
diff --git a/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc b/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc index 3d6ff7f..ce4be330 100644 --- a/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc +++ b/chrome/browser/chromeos/login/existing_user_controller_auto_login_unittest.cc
@@ -101,11 +101,12 @@ return existing_user_controller()->auto_login_timer_.get(); } - const std::string& auto_login_username() const { - return existing_user_controller()->public_session_auto_login_username_; + const AccountId& auto_login_account_id() const { + return existing_user_controller()->public_session_auto_login_account_id_; } - void set_auto_login_username(const std::string& username) { - existing_user_controller()->public_session_auto_login_username_ = username; + void set_auto_login_account_id(const AccountId& account_id) { + existing_user_controller()->public_session_auto_login_account_id_ = + account_id; } int auto_login_delay() const { @@ -157,19 +158,19 @@ TEST_F(ExistingUserControllerAutoLoginTest, StartAutoLoginTimer) { // Timer shouldn't start until signin screen is ready. - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_account_id(auto_login_account_id_); set_auto_login_delay(kAutoLoginDelay2); existing_user_controller()->StartPublicSessionAutoLoginTimer(); EXPECT_FALSE(auto_login_timer()); // Timer shouldn't start if the policy isn't set. - set_auto_login_username(""); + set_auto_login_account_id(EmptyAccountId()); existing_user_controller()->OnSigninScreenReady(); existing_user_controller()->StartPublicSessionAutoLoginTimer(); EXPECT_FALSE(auto_login_timer()); // Timer shouldn't fire in the middle of a login attempt. - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_account_id(auto_login_account_id_); set_is_login_in_progress(true); existing_user_controller()->StartPublicSessionAutoLoginTimer(); EXPECT_FALSE(auto_login_timer()); @@ -185,7 +186,7 @@ TEST_F(ExistingUserControllerAutoLoginTest, StopAutoLoginTimer) { existing_user_controller()->OnSigninScreenReady(); - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_account_id(auto_login_account_id_); set_auto_login_delay(kAutoLoginDelay2); existing_user_controller()->StartPublicSessionAutoLoginTimer(); @@ -199,7 +200,7 @@ TEST_F(ExistingUserControllerAutoLoginTest, ResetAutoLoginTimer) { existing_user_controller()->OnSigninScreenReady(); - set_auto_login_username(auto_login_account_id_.GetUserEmail()); + set_auto_login_account_id(auto_login_account_id_); // Timer starts off not running. EXPECT_FALSE(auto_login_timer()); @@ -233,14 +234,14 @@ ConfigureAutoLogin(); EXPECT_FALSE(auto_login_timer()); EXPECT_EQ(auto_login_delay(), 0); - EXPECT_EQ(auto_login_username(), ""); + EXPECT_EQ(auto_login_account_id(), EmptyAccountId()); // Timer shouldn't start when the delay alone is set. SetAutoLoginSettings("", kAutoLoginDelay1); ConfigureAutoLogin(); EXPECT_FALSE(auto_login_timer()); EXPECT_EQ(auto_login_delay(), kAutoLoginDelay1); - EXPECT_EQ(auto_login_username(), ""); + EXPECT_EQ(auto_login_account_id(), EmptyAccountId()); // Timer should start when the account ID is set. SetAutoLoginSettings(auto_login_user_id_, kAutoLoginDelay1); @@ -250,7 +251,7 @@ EXPECT_EQ(auto_login_timer()->GetCurrentDelay().InMilliseconds(), kAutoLoginDelay1); EXPECT_EQ(auto_login_delay(), kAutoLoginDelay1); - EXPECT_EQ(auto_login_username(), auto_login_account_id_.GetUserEmail()); + EXPECT_EQ(auto_login_account_id(), auto_login_account_id_); // Timer should restart when the delay is changed. SetAutoLoginSettings(auto_login_user_id_, kAutoLoginDelay2); @@ -260,7 +261,7 @@ EXPECT_EQ(auto_login_timer()->GetCurrentDelay().InMilliseconds(), kAutoLoginDelay2); EXPECT_EQ(auto_login_delay(), kAutoLoginDelay2); - EXPECT_EQ(auto_login_username(), auto_login_account_id_.GetUserEmail()); + EXPECT_EQ(auto_login_account_id(), auto_login_account_id_); // Timer should stop when the account ID is unset. SetAutoLoginSettings("", kAutoLoginDelay2); @@ -269,7 +270,7 @@ EXPECT_FALSE(auto_login_timer()->IsRunning()); EXPECT_EQ(auto_login_timer()->GetCurrentDelay().InMilliseconds(), kAutoLoginDelay2); - EXPECT_EQ(auto_login_username(), ""); + EXPECT_EQ(auto_login_account_id(), EmptyAccountId()); EXPECT_EQ(auto_login_delay(), kAutoLoginDelay2); }
diff --git a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc index fd45ed8..1fb92a8 100644 --- a/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/existing_user_controller_browsertest.cc
@@ -198,8 +198,7 @@ } AccountId auto_login_account_id() const { - return AccountId::FromUserEmail( - existing_user_controller()->public_session_auto_login_username_); + return existing_user_controller()->public_session_auto_login_account_id_; } int auto_login_delay() const { @@ -220,7 +219,8 @@ // Mock URLFetcher. MockURLFetcherFactory<SuccessFetcher> factory_; - const AccountId account_id_ = AccountId::FromUserEmail(kUsername); + const AccountId account_id_ = + AccountId::FromUserEmailGaiaId(kUsername, kGaiaID); private: DISALLOW_COPY_AND_ASSIGN(ExistingUserControllerTest); @@ -234,7 +234,6 @@ EXPECT_CALL(*mock_login_display_, SetUIEnabled(false)) .Times(2); UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); user_context.SetUserIDHash(account_id_.GetUserEmail()); test::UserSessionManagerTestApi session_manager_test_api( @@ -285,7 +284,6 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerUntrustedTest, ExistingUserLoginForbidden) { UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); user_context.SetUserIDHash(account_id_.GetUserEmail()); existing_user_controller()->Login(user_context, SigninSpecifics()); @@ -294,7 +292,6 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerUntrustedTest, NewUserLoginForbidden) { UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); user_context.SetUserIDHash(account_id_.GetUserEmail()); existing_user_controller()->CompleteLogin(user_context); @@ -303,7 +300,7 @@ IN_PROC_BROWSER_TEST_F(ExistingUserControllerUntrustedTest, GuestLoginForbidden) { existing_user_controller()->Login( - UserContext(user_manager::USER_TYPE_GUEST, std::string()), + UserContext(user_manager::USER_TYPE_GUEST, EmptyAccountId()), SigninSpecifics()); } @@ -526,7 +523,7 @@ AutoLoginNoDelay) { // Set up mocks to check login success. UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()); + public_session_account_id_); user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); @@ -540,7 +537,7 @@ AutoLoginShortDelay) { // Set up mocks to check login success. UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()); + public_session_account_id_); user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); @@ -573,7 +570,6 @@ LoginStopsAutoLogin) { // Set up mocks to check login success. UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); ExpectSuccessfulLogin(user_context); @@ -607,7 +603,6 @@ EXPECT_CALL(*mock_login_display_, SetUIEnabled(false)) .Times(2); UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); test::UserSessionManagerTestApi session_manager_test_api( UserSessionManager::GetInstance()); @@ -618,9 +613,9 @@ EXPECT_TRUE(auto_login_timer()); // Login and check that it stopped the timer. - existing_user_controller()->Login(UserContext(user_manager::USER_TYPE_GUEST, - std::string()), - SigninSpecifics()); + existing_user_controller()->Login( + UserContext(user_manager::USER_TYPE_GUEST, EmptyAccountId()), + SigninSpecifics()); EXPECT_TRUE(is_login_in_progress()); ASSERT_TRUE(auto_login_timer()); EXPECT_FALSE(auto_login_timer()->IsRunning()); @@ -637,7 +632,6 @@ CompleteLoginStopsAutoLogin) { // Set up mocks to check login success. UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); ExpectSuccessfulLogin(user_context); @@ -671,7 +665,7 @@ PublicSessionLoginStopsAutoLogin) { // Set up mocks to check login success. UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()); + public_session_account_id_); user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); ExpectSuccessfulLogin(user_context); existing_user_controller()->OnSigninScreenReady(); @@ -685,7 +679,7 @@ // Login and check that it stopped the timer. existing_user_controller()->Login( UserContext(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - public_session_account_id_.GetUserEmail()), + public_session_account_id_), SigninSpecifics()); EXPECT_TRUE(is_login_in_progress()); @@ -710,7 +704,6 @@ // Check that the attempt to start a public session fails with an error. ExpectLoginFailure(); UserContext user_context(account_id_); - user_context.SetGaiaID(kGaiaID); user_context.SetKey(Key(kPassword)); user_context.SetUserIDHash(user_context.GetAccountId().GetUserEmail()); existing_user_controller()->Login(user_context, SigninSpecifics());
diff --git a/chrome/browser/chromeos/login/login_browsertest.cc b/chrome/browser/chromeos/login/login_browsertest.cc index d1d248e..bd7b287 100644 --- a/chrome/browser/chromeos/login/login_browsertest.cc +++ b/chrome/browser/chromeos/login/login_browsertest.cc
@@ -161,8 +161,8 @@ StartGaiaAuthOffline(); - UserContext user_context(AccountId::FromUserEmail(kTestUser)); - user_context.SetGaiaID(kGaiaId); + UserContext user_context( + AccountId::FromUserEmailGaiaId(kTestUser, kGaiaId)); user_context.SetKey(Key(kPassword)); SetExpectedCredentials(user_context); }
diff --git a/chrome/browser/chromeos/login/login_manager_test.cc b/chrome/browser/chromeos/login/login_manager_test.cc index 7e1a945..c7d15b8 100644 --- a/chrome/browser/chromeos/login/login_manager_test.cc +++ b/chrome/browser/chromeos/login/login_manager_test.cc
@@ -50,7 +50,6 @@ UserContext CreateUserContext(const std::string& user_id) { UserContext user_context(AccountId::FromUserEmailGaiaId( user_id, LoginManagerTest::GetGaiaIDForUserID(user_id))); - user_context.SetGaiaID(LoginManagerTest::GetGaiaIDForUserID(user_id)); user_context.SetKey(Key("password")); if (user_id == LoginManagerTest::kEnterpriseUser1) { user_context.SetRefreshToken(kTestRefreshToken1);
diff --git a/chrome/browser/chromeos/login/saml/saml_browsertest.cc b/chrome/browser/chromeos/login/saml/saml_browsertest.cc index c98c8064..9e8b69a 100644 --- a/chrome/browser/chromeos/login/saml/saml_browsertest.cc +++ b/chrome/browser/chromeos/login/saml/saml_browsertest.cc
@@ -280,7 +280,7 @@ public: SecretInterceptingFakeCryptohomeClient(); - void MountEx(const cryptohome::AccountIdentifier& id, + void MountEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::MountRequest& request, const ProtobufMethodCallback& callback) override; @@ -298,7 +298,7 @@ } void SecretInterceptingFakeCryptohomeClient::MountEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::MountRequest& request, const ProtobufMethodCallback& callback) {
diff --git a/chrome/browser/chromeos/login/session/chrome_session_manager.cc b/chrome/browser/chromeos/login/session/chrome_session_manager.cc index 1802d82e..1039a40 100644 --- a/chrome/browser/chromeos/login/session/chrome_session_manager.cc +++ b/chrome/browser/chromeos/login/session/chrome_session_manager.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/chromeos/login/session/stub_login_session_manager_delegate.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/login/user_names.h" #include "components/signin/core/account_id/account_id.h" @@ -45,8 +46,10 @@ bool force_login_screen_in_test = parsed_command_line.HasSwitch(switches::kForceLoginManagerInTests); - const AccountId login_account_id(AccountId::FromUserEmail( - parsed_command_line.GetSwitchValueASCII(switches::kLoginUser))); + const std::string cryptohome_id = + parsed_command_line.GetSwitchValueASCII(switches::kLoginUser); + const AccountId login_account_id( + cryptohome::Identification::FromString(cryptohome_id).GetAccountId()); KioskAppManager::RemoveObsoleteCryptohomes();
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 572d0a5..75857a2 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -81,6 +81,7 @@ #include "chrome/common/pref_names.h" #include "chromeos/cert_loader.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" @@ -434,7 +435,7 @@ if (!about_flags::AreSwitchesIdenticalToCurrentCommandLine( user_flags, *base::CommandLine::ForCurrentProcess(), NULL)) { DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser( - login::GuestAccountId().GetUserEmail(), + cryptohome::Identification(login::GuestAccountId()), base::CommandLine::StringVector()); } @@ -718,7 +719,9 @@ flags.assign(user_flags.argv().begin() + 1, user_flags.argv().end()); LOG(WARNING) << "Restarting to apply per-session flags..."; DBusThreadManager::Get()->GetSessionManagerClient()->SetFlagsForUser( - user_manager::UserManager::Get()->GetActiveUser()->email(), flags); + cryptohome::Identification( + user_manager::UserManager::Get()->GetActiveUser()->GetAccountId()), + flags); AttemptRestart(profile); return true; } @@ -894,7 +897,7 @@ BootTimesRecorder* btl = BootTimesRecorder::Get(); btl->AddLoginTimeMarker("StartSession-Start", false); DBusThreadManager::Get()->GetSessionManagerClient()->StartSession( - user_context_.GetAccountId().GetUserEmail()); + cryptohome::Identification(user_context_.GetAccountId())); btl->AddLoginTimeMarker("StartSession-End", false); } @@ -908,8 +911,8 @@ } void UserSessionManager::PrepareProfile() { - const bool is_demo_session = DemoAppLauncher::IsDemoAppSession( - user_context_.GetAccountId().GetUserEmail()); + const bool is_demo_session = + DemoAppLauncher::IsDemoAppSession(user_context_.GetAccountId()); // TODO(nkostylev): Figure out whether demo session is using the right profile // path or not. See https://codereview.chromium.org/171423009 @@ -1426,13 +1429,14 @@ user_manager::UserManager* user_manager = user_manager::UserManager::Get(); DCHECK_EQ(1u, user_manager->GetLoggedInUsers().size()); DCHECK(user_manager->GetActiveUser()); - std::string active_user_id = user_manager->GetActiveUser()->email(); + const cryptohome::Identification active_cryptohome_id = + cryptohome::Identification(user_manager->GetActiveUser()->GetAccountId()); SessionManagerClient::ActiveSessionsMap::const_iterator it; for (it = sessions.begin(); it != sessions.end(); ++it) { - if (active_user_id == it->first) + if (active_cryptohome_id == it->first) continue; - pending_user_sessions_[it->first] = it->second; + pending_user_sessions_[(it->first).GetAccountId()] = it->second; } RestorePendingUserSessions(); } @@ -1445,13 +1449,12 @@ } // Get next user to restore sessions and delete it from list. - SessionManagerClient::ActiveSessionsMap::const_iterator it = - pending_user_sessions_.begin(); - std::string user_id = it->first; + PendingUserSessions::const_iterator it = pending_user_sessions_.begin(); + const AccountId account_id = it->first; std::string user_id_hash = it->second; - DCHECK(!user_id.empty()); + DCHECK(account_id.is_valid()); DCHECK(!user_id_hash.empty()); - pending_user_sessions_.erase(user_id); + pending_user_sessions_.erase(account_id); // Check that this user is not logged in yet. user_manager::UserList logged_in_users = @@ -1461,7 +1464,7 @@ it != logged_in_users.end(); ++it) { const user_manager::User* user = (*it); - if (user->email() == user_id) { + if (user->GetAccountId() == account_id) { user_already_logged_in = true; break; } @@ -1469,7 +1472,7 @@ DCHECK(!user_already_logged_in); if (!user_already_logged_in) { - UserContext user_context(AccountId::FromUserEmail(user_id)); + UserContext user_context(account_id); user_context.SetUserIDHash(user_id_hash); user_context.SetIsUsingOAuth(false);
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.h b/chrome/browser/chromeos/login/session/user_session_manager.h index e875f2c..31b7367 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.h +++ b/chrome/browser/chromeos/login/session/user_session_manager.h
@@ -433,7 +433,9 @@ // User sessions that have to be restored after browser crash. // [user_id] > [user_id_hash] - SessionManagerClient::ActiveSessionsMap pending_user_sessions_; + using PendingUserSessions = std::map<AccountId, std::string>; + + PendingUserSessions pending_user_sessions_; base::ObserverList<chromeos::UserSessionStateObserver> session_state_observer_list_;
diff --git a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc index f816a7b..e4071ef 100644 --- a/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/oauth2_browsertest.cc
@@ -264,7 +264,6 @@ } UserContext user_context(account_id); - user_context.SetGaiaID(account_id.GetGaiaId()); user_context.SetKey(Key(password)); controller->Login(user_context, SigninSpecifics()); content::WindowedNotificationObserver(
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_authenticator.cc b/chrome/browser/chromeos/login/supervised/supervised_user_authenticator.cc index a0f9eab..7cbad7c 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_authenticator.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_authenticator.cc
@@ -14,6 +14,8 @@ #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/login/auth/key.h" +#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/known_user.h" #include "content/public/browser/browser_thread.h" #include "crypto/sha2.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -67,18 +69,16 @@ Key key(attempt->password); key.Transform(Key::KEY_TYPE_SALTED_SHA256_TOP_HALF, system_salt); + const AccountId account_id = user_manager::known_user::GetAccountId( + attempt->username, std::string() /* gaia_id */); + const cryptohome::Identification cryptohome_id(account_id); cryptohome::AsyncMethodCaller::GetInstance()->AsyncMount( - attempt->username, - key.GetSecret(), - flags, - base::Bind(&TriggerResolveWithLoginTimeMarker, - "CryptohomeMount-LMU-End", - attempt, - resolver)); + cryptohome_id, key.GetSecret(), flags, + base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeMount-LMU-End", + attempt, resolver)); cryptohome::AsyncMethodCaller::GetInstance()->AsyncGetSanitizedUsername( - attempt->username, - base::Bind(&TriggerResolveResult, attempt, resolver)); + cryptohome_id, base::Bind(&TriggerResolveResult, attempt, resolver)); } // Calls cryptohome's addKey method. @@ -94,14 +94,13 @@ user_key.Transform(Key::KEY_TYPE_SALTED_SHA256_TOP_HALF, system_salt); Key master_key(plain_text_master_key); master_key.Transform(Key::KEY_TYPE_SALTED_SHA256_TOP_HALF, system_salt); + const AccountId account_id = user_manager::known_user::GetAccountId( + attempt->username, std::string() /* gaia_id */); cryptohome::AsyncMethodCaller::GetInstance()->AsyncAddKey( - attempt->username, - user_key.GetSecret(), + cryptohome::Identification(account_id), user_key.GetSecret(), master_key.GetSecret(), - base::Bind(&TriggerResolveWithLoginTimeMarker, - "CryptohomeAddKey-LMU-End", - attempt, - resolver)); + base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeAddKey-LMU-End", + attempt, resolver)); } } // namespace
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc b/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc index 8699e30e..19a1548a 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.cc
@@ -229,8 +229,7 @@ keys.push_back(master_key); authenticator_->CreateMount( - creation_context_->local_user_id, - keys, + AccountId::FromUserEmail(creation_context_->local_user_id), keys, base::Bind(&SupervisedUserCreationControllerNew::OnMountSuccess, weak_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc b/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc index e329a961d..be5e27c 100644 --- a/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc +++ b/chrome/browser/chromeos/login/supervised/supervised_user_test_base.cc
@@ -296,7 +296,6 @@ JSExpect("!$('supervised-user-creation-next-button').disabled"); UserContext user_context(AccountId::FromUserEmailGaiaId( kTestManager, GetGaiaIDForUserID(kTestManager))); - user_context.SetGaiaID(GetGaiaIDForUserID(kTestManager)); user_context.SetKey(Key(kTestManagerPassword)); SetExpectedCredentials(user_context); content::WindowedNotificationObserver login_observer(
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc index 44a3bd79..c1991c6 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc
@@ -107,9 +107,7 @@ class UserImageManagerTest : public LoginManagerTest, public user_manager::UserManager::Observer { protected: - UserImageManagerTest() - : LoginManagerTest(true), - enterprise_account_id_(AccountId::FromUserEmail(kEnterpriseUser1)) {} + UserImageManagerTest() : LoginManagerTest(true) {} // LoginManagerTest overrides: void SetUpInProcessBrowserTestFixture() override { @@ -327,7 +325,10 @@ const AccountId test_account_id1_ = AccountId::FromUserEmail(kTestUser1); const AccountId test_account_id2_ = AccountId::FromUserEmail(kTestUser2); - const AccountId enterprise_account_id_; + const AccountId enterprise_account_id_ = + AccountId::FromUserEmail(kEnterpriseUser1); + const cryptohome::Identification cryptohome_id_ = + cryptohome::Identification(enterprise_account_id_); private: DISALLOW_COPY_AND_ASSIGN(UserImageManagerTest); @@ -666,8 +667,7 @@ ASSERT_TRUE(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_keys_dir)); const std::string sanitized_username = - chromeos::CryptohomeClient::GetStubSanitizedUsername( - enterprise_account_id_.GetUserEmail()); + chromeos::CryptohomeClient::GetStubSanitizedUsername(cryptohome_id_); const base::FilePath user_key_file = user_keys_dir.AppendASCII(sanitized_username) .AppendASCII("policy.pub"); @@ -748,8 +748,8 @@ user_policy_.payload().mutable_useravatarimage()->set_value( ConstructPolicy(test::kUserAvatarImage2RelativePath)); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(cryptohome_id_, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->Load(); run_loop_->Run(); @@ -773,8 +773,8 @@ // image. user_policy_.payload().Clear(); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(cryptohome_id_, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->AddObserver(this); store->Load(); @@ -855,8 +855,8 @@ user_policy_.payload().mutable_useravatarimage()->set_value( ConstructPolicy(test::kUserAvatarImage2RelativePath)); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(cryptohome_id_, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->Load(); run_loop_->Run(); @@ -902,8 +902,8 @@ user_policy_.payload().mutable_useravatarimage()->set_value( ConstructPolicy(test::kUserAvatarImage2RelativePath)); user_policy_.Build(); - fake_session_manager_client_->set_user_policy( - enterprise_account_id_.GetUserEmail(), user_policy_.GetBlob()); + fake_session_manager_client_->set_user_policy(cryptohome_id_, + user_policy_.GetBlob()); run_loop_.reset(new base::RunLoop); store->Load(); run_loop_->Run();
diff --git a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc index 4bac334..0ca91fd 100644 --- a/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc +++ b/chrome/browser/chromeos/login/users/chrome_user_manager_impl.cc
@@ -606,7 +606,7 @@ } bool ChromeUserManagerImpl::IsDemoApp(const AccountId& account_id) const { - return DemoAppLauncher::IsDemoAppSession(account_id.GetUserEmail()); + return DemoAppLauncher::IsDemoAppSession(account_id); } bool ChromeUserManagerImpl::IsKioskApp(const AccountId& account_id) const { @@ -1251,7 +1251,8 @@ void ChromeUserManagerImpl::AsyncRemoveCryptohome( const AccountId& account_id) const { cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( - account_id.GetUserEmail(), base::Bind(&OnRemoveUserComplete, account_id)); + cryptohome::Identification(account_id), + base::Bind(&OnRemoveUserComplete, account_id)); } bool ChromeUserManagerImpl::IsGuestAccountId(
diff --git a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc index 8d4f8d7..7e79232 100644 --- a/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc +++ b/chrome/browser/chromeos/login/users/fake_chrome_user_manager.cc
@@ -28,9 +28,12 @@ FakeChromeUserManager::FakeChromeUserManager() : supervised_user_manager_(new FakeSupervisedUserManager), bootstrap_manager_(NULL), - multi_profile_user_controller_(NULL) {} + multi_profile_user_controller_(NULL) { + ProfileHelper::SetProfileToUserForTestingEnabled(true); +} FakeChromeUserManager::~FakeChromeUserManager() { + ProfileHelper::SetProfileToUserForTestingEnabled(false); } const user_manager::User* FakeChromeUserManager::AddUser( @@ -50,6 +53,7 @@ IDR_PROFILE_PICTURE_LOADING)), user_manager::User::USER_IMAGE_PROFILE, false); users_.push_back(user); + chromeos::ProfileHelper::Get()->SetProfileToUserMappingForTesting(user); return user; }
diff --git a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc index 15f321d3..edfcc68 100644 --- a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc +++ b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.cc
@@ -40,6 +40,7 @@ #include "chrome/common/pref_names.h" #include "chromeos/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/login/user_names.h" #include "components/prefs/pref_registry_simple.h" @@ -805,7 +806,7 @@ if (user->username_hash().empty()) { cryptohome::AsyncMethodCaller::GetInstance()->AsyncGetSanitizedUsername( - account_id.GetUserEmail(), + cryptohome::Identification(account_id), base::Bind(&WallpaperManager::SetCustomWallpaperOnSanitizedUsername, weak_factory_.GetWeakPtr(), account_id, user_image.image(), true /* update wallpaper */));
diff --git a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc index 9e6c82e2..16ec162 100644 --- a/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc +++ b/chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_policy_browsertest.cc
@@ -150,7 +150,8 @@ base::FilePath user_keys_dir; EXPECT_TRUE(PathService::Get(DIR_USER_POLICY_KEYS, &user_keys_dir)); const std::string sanitized_user_id = - CryptohomeClient::GetStubSanitizedUsername(account_id.GetUserEmail()); + CryptohomeClient::GetStubSanitizedUsername( + cryptohome::Identification(account_id)); const base::FilePath user_key_file = user_keys_dir.AppendASCII(sanitized_user_id) .AppendASCII("policy.pub"); @@ -252,8 +253,8 @@ builder->payload().Clear(); } builder->Build(); - fake_session_manager_client_->set_user_policy(account_id.GetUserEmail(), - builder->GetBlob()); + fake_session_manager_client_->set_user_policy( + cryptohome::Identification(account_id), builder->GetBlob()); const user_manager::User* user = user_manager::UserManager::Get()->FindUser(account_id); ASSERT_TRUE(user);
diff --git a/chrome/browser/chromeos/policy/affiliation_test_helper.cc b/chrome/browser/chromeos/policy/affiliation_test_helper.cc index acdba14..8cdfc1f 100644 --- a/chrome/browser/chromeos/policy/affiliation_test_helper.cc +++ b/chrome/browser/chromeos/policy/affiliation_test_helper.cc
@@ -44,11 +44,13 @@ const char kEnterpriseUser[] = "testuser@example.com"; void SetUserKeys(policy::UserPolicyBuilder* user_policy) { - std::string username = user_policy->policy_data().username(); + const AccountId account_id = + AccountId::FromUserEmail(user_policy->policy_data().username()); base::FilePath user_keys_dir; ASSERT_TRUE(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_keys_dir)); const std::string sanitized_username = - chromeos::CryptohomeClient::GetStubSanitizedUsername(username); + chromeos::CryptohomeClient::GetStubSanitizedUsername( + cryptohome::Identification(account_id)); const base::FilePath user_key_file = user_keys_dir.AppendASCII(sanitized_username).AppendASCII("policy.pub"); std::vector<uint8_t> user_key_bits; @@ -84,14 +86,15 @@ chromeos::FakeSessionManagerClient* fake_session_manager_client, const std::string& user_email, const std::set<std::string>& user_affiliation_ids) { + const AccountId account_id = AccountId::FromUserEmail(user_email); user_policy->policy_data().set_username(user_email); SetUserKeys(user_policy); for (const auto& user_affiliation_id : user_affiliation_ids) { user_policy->policy_data().add_user_affiliation_ids(user_affiliation_id); } user_policy->Build(); - fake_session_manager_client->set_user_policy(user_email, - user_policy->GetBlob()); + fake_session_manager_client->set_user_policy( + cryptohome::Identification(account_id), user_policy->GetBlob()); } void PreLoginUser(const std::string& user_id) { @@ -105,8 +108,8 @@ chromeos::UserSessionManager::GetInstance()); session_manager_test_api.SetShouldObtainTokenHandleInTests(false); - chromeos::UserContext user_context(AccountId::FromUserEmail(user_id)); - user_context.SetGaiaID("gaia-id-" + user_id); + chromeos::UserContext user_context( + AccountId::FromUserEmailGaiaId(user_id, "gaia-id-" + user_id)); user_context.SetKey(chromeos::Key("password")); if (user_id == kEnterpriseUser) { user_context.SetRefreshToken(kFakeRefreshToken);
diff --git a/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc b/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc index c0f2c93f..5532529 100644 --- a/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc +++ b/chrome/browser/chromeos/policy/consumer_enrollment_handler_factory_unittest.cc
@@ -44,15 +44,20 @@ make_scoped_ptr(fake_service_)); // Set up FakeChromeUserManager. - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestOwner)); - fake_user_manager_->AddUser(AccountId::FromUserEmail(kTestUser)); - fake_user_manager_->set_owner_id(AccountId::FromUserEmail(kTestOwner)); + fake_user_manager_->AddUser(owner_account_id); + fake_user_manager_->AddUser(test_account_id); + fake_user_manager_->set_owner_id(owner_account_id); } void SetUp() override { + testing::Test::SetUp(); + ASSERT_TRUE(testing_profile_manager_->SetUp()); } + const AccountId owner_account_id = AccountId::FromUserEmail(kTestOwner); + const AccountId test_account_id = AccountId::FromUserEmail(kTestUser); + content::TestBrowserThreadBundle thread_bundle_; FakeConsumerManagementService* fake_service_; chromeos::FakeChromeUserManager* fake_user_manager_; @@ -61,7 +66,8 @@ }; TEST_F(ConsumerEnrollmentHandlerFactoryTest, ServiceIsCreated) { - Profile* profile = testing_profile_manager_->CreateTestingProfile(kTestOwner); + Profile* profile = testing_profile_manager_->CreateTestingProfile( + owner_account_id.GetUserEmail()); EXPECT_TRUE(ConsumerEnrollmentHandlerFactory::GetForBrowserContext(profile)); }
diff --git a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc index fd7dcbe..1f54448 100644 --- a/chrome/browser/chromeos/policy/device_local_account_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_local_account_browsertest.cc
@@ -731,7 +731,7 @@ ASSERT_TRUE(controller); chromeos::UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - account_id_1_.GetUserEmail()); + account_id_1_); user_context.SetPublicSessionLocale(locale); user_context.SetPublicSessionInputMethod(input_method); controller->Login(user_context, chromeos::SigninSpecifics());
diff --git a/chrome/browser/chromeos/policy/power_policy_browsertest.cc b/chrome/browser/chromeos/policy/power_policy_browsertest.cc index 4f95ae9..6d09024 100644 --- a/chrome/browser/chromeos/policy/power_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/power_policy_browsertest.cc
@@ -206,7 +206,7 @@ ASSERT_TRUE(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_keys_dir)); std::string sanitized_username = chromeos::CryptohomeClient::GetStubSanitizedUsername( - chromeos::login::StubAccountId().GetUserEmail()); + cryptohome::Identification(chromeos::login::StubAccountId())); base::FilePath user_key_file = user_keys_dir.AppendASCII(sanitized_username) .AppendASCII("policy.pub"); @@ -224,7 +224,8 @@ // Install the new user policy blob in session manager client. user_policy_.Build(); session_manager_client()->set_user_policy( - user_policy_.policy_data().username(), + cryptohome::Identification( + AccountId::FromUserEmail(user_policy_.policy_data().username())), user_policy_.GetBlob()); // Reload user policy from session manager client and wait for the update to
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc index 7695acf..a9c85468 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.cc
@@ -138,10 +138,9 @@ // - For device-local accounts, policy is provided by // |DeviceLocalAccountPolicyService|. // All other user types do not have user policy. - const std::string& username = user->email(); - if (!user->HasGaiaAccount() || - user->IsSupervised() || - BrowserPolicyConnector::IsNonEnterpriseUser(username)) { + const AccountId account_id = user->GetAccountId(); + if (!user->HasGaiaAccount() || user->IsSupervised() || + BrowserPolicyConnector::IsNonEnterpriseUser(account_id.GetUserEmail())) { return scoped_ptr<UserCloudPolicyManagerChromeOS>(); } @@ -195,8 +194,8 @@ new UserCloudPolicyStoreChromeOS( chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), chromeos::DBusThreadManager::Get()->GetSessionManagerClient(), - background_task_runner, - username, policy_key_dir, token_cache_file, policy_cache_file)); + background_task_runner, account_id, policy_key_dir, token_cache_file, + policy_cache_file)); scoped_refptr<base::SequencedTaskRunner> backend_task_runner = content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( @@ -226,9 +225,11 @@ bool wildcard_match = false; if (connector->IsEnterpriseManaged() && - chromeos::CrosSettings::IsWhitelisted(username, &wildcard_match) && - wildcard_match && !connector->IsNonEnterpriseUser(username)) { - manager->EnableWildcardLoginCheck(username); + chromeos::CrosSettings::IsWhitelisted(account_id.GetUserEmail(), + &wildcard_match) && + wildcard_match && + !connector->IsNonEnterpriseUser(account_id.GetUserEmail())) { + manager->EnableWildcardLoginCheck(account_id.GetUserEmail()); } manager->Init(
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc index 369a494..4e470142 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.cc
@@ -20,6 +20,7 @@ #include "base/strings/stringprintf.h" #include "chrome/browser/chromeos/policy/user_policy_disk_cache.h" #include "chrome/browser/chromeos/policy/user_policy_token_loader.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/session_manager_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" @@ -178,14 +179,14 @@ chromeos::CryptohomeClient* cryptohome_client, chromeos::SessionManagerClient* session_manager_client, scoped_refptr<base::SequencedTaskRunner> background_task_runner, - const std::string& username, + const AccountId& account_id, const base::FilePath& user_policy_key_dir, const base::FilePath& legacy_token_cache_file, const base::FilePath& legacy_policy_cache_file) : UserCloudPolicyStoreBase(background_task_runner), cryptohome_client_(cryptohome_client), session_manager_client_(session_manager_client), - username_(username), + account_id_(account_id), user_policy_key_dir_(user_policy_key_dir), legacy_cache_dir_(legacy_token_cache_file.DirName()), legacy_loader_(new LegacyPolicyCacheLoader(legacy_token_cache_file, @@ -213,7 +214,7 @@ // Cancel all pending requests. weak_factory_.InvalidateWeakPtrs(); session_manager_client_->RetrievePolicyForUser( - username_, + cryptohome::Identification(account_id_), base::Bind(&UserCloudPolicyStoreChromeOS::OnPolicyRetrieved, weak_factory_.GetWeakPtr())); } @@ -228,7 +229,8 @@ // Profile initialization never sees unmanaged prefs, which would lead to // data loss. http://crbug.com/263061 std::string policy_blob = - session_manager_client_->BlockingRetrievePolicyForUser(username_); + session_manager_client_->BlockingRetrievePolicyForUser( + cryptohome::Identification(account_id_)); if (policy_blob.empty()) { // The session manager doesn't have policy, or the call failed. // Just notify that the load is done, and don't bother with the legacy @@ -245,7 +247,8 @@ } std::string sanitized_username = - cryptohome_client_->BlockingGetSanitizedUsername(username_); + cryptohome_client_->BlockingGetSanitizedUsername( + cryptohome::Identification(account_id_)); if (sanitized_username.empty()) { status_ = STATUS_LOAD_ERROR; NotifyStoreError(); @@ -268,15 +271,14 @@ // Create and configure a validator. scoped_ptr<UserCloudPolicyValidator> validator = CreateValidator( std::move(policy), CloudPolicyValidatorBase::TIMESTAMP_REQUIRED); - validator->ValidateUsername(username_, true); + validator->ValidateUsername(account_id_.GetUserEmail(), true); if (policy_key_.empty()) { validator->ValidateInitialKey(GetPolicyVerificationKey(), - ExtractDomain(username_)); + ExtractDomain(account_id_.GetUserEmail())); } else { const bool allow_rotation = true; - validator->ValidateSignature(policy_key_, - GetPolicyVerificationKey(), - ExtractDomain(username_), + validator->ValidateSignature(policy_key_, GetPolicyVerificationKey(), + ExtractDomain(account_id_.GetUserEmail()), allow_rotation); } @@ -310,8 +312,7 @@ } session_manager_client_->StorePolicyForUser( - username_, - policy_blob, + cryptohome::Identification(account_id_), policy_blob, base::Bind(&UserCloudPolicyStoreChromeOS::OnPolicyStored, weak_factory_.GetWeakPtr())); } @@ -418,7 +419,7 @@ // the signature on this policy is not verified. scoped_ptr<UserCloudPolicyValidator> validator = CreateValidator( std::move(policy), CloudPolicyValidatorBase::TIMESTAMP_REQUIRED); - validator->ValidateUsername(username_, true); + validator->ValidateUsername(account_id_.GetUserEmail(), true); validator.release()->StartValidation( base::Bind(&UserCloudPolicyStoreChromeOS::OnLegacyPolicyValidated, weak_factory_.GetWeakPtr(), @@ -532,10 +533,10 @@ } else { // Get the hashed username that's part of the key's path, to determine // |policy_key_path_|. - cryptohome_client_->GetSanitizedUsername(username_, + cryptohome_client_->GetSanitizedUsername( + cryptohome::Identification(account_id_), base::Bind(&UserCloudPolicyStoreChromeOS::OnGetSanitizedUsername, - weak_factory_.GetWeakPtr(), - callback)); + weak_factory_.GetWeakPtr(), callback)); } } @@ -559,15 +560,16 @@ scoped_ptr<em::PolicyFetchResponse> policy) { scoped_ptr<UserCloudPolicyValidator> validator = CreateValidator( std::move(policy), CloudPolicyValidatorBase::TIMESTAMP_NOT_BEFORE); - validator->ValidateUsername(username_, true); + validator->ValidateUsername(account_id_.GetUserEmail(), true); const bool allow_rotation = false; const std::string empty_key = std::string(); // The policy loaded from session manager need not be validated using the // verification key since it is secure, and since there may be legacy policy // data that was stored without a verification key. Hence passing an empty // value for the verification key. - validator->ValidateSignature( - policy_key_, empty_key, ExtractDomain(username_), allow_rotation); + validator->ValidateSignature(policy_key_, empty_key, + ExtractDomain(account_id_.GetUserEmail()), + allow_rotation); return validator; } } // namespace policy
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h index edf34d89..3f5fef7 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos.h
@@ -17,6 +17,7 @@ #include "chromeos/dbus/dbus_method_call_status.h" #include "components/policy/core/common/cloud/cloud_policy_validator.h" #include "components/policy/core/common/cloud/user_cloud_policy_store_base.h" +#include "components/signin/core/account_id/account_id.h" namespace base { class SequencedTaskRunner; @@ -44,7 +45,7 @@ chromeos::CryptohomeClient* cryptohome_client, chromeos::SessionManagerClient* session_manager_client, scoped_refptr<base::SequencedTaskRunner> background_task_runner, - const std::string& username, + const AccountId& account_id, const base::FilePath& user_policy_key_dir, const base::FilePath& legacy_token_cache_file, const base::FilePath& legacy_policy_cache_file); @@ -124,7 +125,7 @@ chromeos::CryptohomeClient* cryptohome_client_; chromeos::SessionManagerClient* session_manager_client_; - const std::string username_; + const AccountId account_id_; base::FilePath user_policy_key_dir_; // TODO(mnissler): Remove all the legacy policy support members below after
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc index 0d32195d4..482ca602 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc
@@ -58,18 +58,15 @@ UserCloudPolicyStoreChromeOSTest() {} void SetUp() override { - EXPECT_CALL(cryptohome_client_, - GetSanitizedUsername(PolicyBuilder::kFakeUsername, _)) + EXPECT_CALL(cryptohome_client_, GetSanitizedUsername(cryptohome_id_, _)) .Times(AnyNumber()) - .WillRepeatedly( - SendSanitizedUsername(chromeos::DBUS_METHOD_CALL_SUCCESS, - kSanitizedUsername)); + .WillRepeatedly(SendSanitizedUsername( + chromeos::DBUS_METHOD_CALL_SUCCESS, kSanitizedUsername)); ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir()); store_.reset(new UserCloudPolicyStoreChromeOS( &cryptohome_client_, &session_manager_client_, loop_.task_runner(), - PolicyBuilder::kFakeUsername, user_policy_dir(), token_file(), - policy_file())); + account_id_, user_policy_dir(), token_file(), policy_file())); store_->AddObserver(&observer_); // Install the initial public key, so that by default the validation of @@ -102,7 +99,7 @@ // Issue a load command. chromeos::SessionManagerClient::RetrievePolicyCallback retrieve_callback; EXPECT_CALL(session_manager_client_, - RetrievePolicyForUser(PolicyBuilder::kFakeUsername, _)) + RetrievePolicyForUser(cryptohome_id_, _)) .WillOnce(SaveArg<1>(&retrieve_callback)); store_->Load(); RunUntilIdle(); @@ -144,8 +141,7 @@ const char* new_value) { chromeos::SessionManagerClient::StorePolicyCallback store_callback; EXPECT_CALL(session_manager_client_, - StorePolicyForUser(PolicyBuilder::kFakeUsername, - policy_.GetBlob(), _)) + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) .WillOnce(SaveArg<2>(&store_callback)); store_->Store(policy_.policy()); RunUntilIdle(); @@ -173,7 +169,7 @@ // Let the store operation complete. chromeos::SessionManagerClient::RetrievePolicyCallback retrieve_callback; EXPECT_CALL(session_manager_client_, - RetrievePolicyForUser(PolicyBuilder::kFakeUsername, _)) + RetrievePolicyForUser(cryptohome_id_, _)) .WillOnce(SaveArg<1>(&retrieve_callback)); store_callback.Run(true); RunUntilIdle(); @@ -227,6 +223,10 @@ UserPolicyBuilder policy_; MockCloudPolicyStoreObserver observer_; scoped_ptr<UserCloudPolicyStoreChromeOS> store_; + const AccountId account_id_ = + AccountId::FromUserEmail(PolicyBuilder::kFakeUsername); + const cryptohome::Identification cryptohome_id_ = + cryptohome::Identification(account_id_); private: base::ScopedTempDir tmp_dir_; @@ -255,8 +255,8 @@ *policy_.policy().mutable_new_public_key_verification_signature() = "garbage"; EXPECT_CALL(session_manager_client_, - StorePolicyForUser( - PolicyBuilder::kFakeUsername, policy_.GetBlob(), _)).Times(0); + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) + .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); Mock::VerifyAndClearExpectations(&session_manager_client_); @@ -271,8 +271,8 @@ policy_.policy().clear_new_public_key_verification_signature(); EXPECT_CALL(session_manager_client_, - StorePolicyForUser( - PolicyBuilder::kFakeUsername, policy_.GetBlob(), _)).Times(0); + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) + .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); Mock::VerifyAndClearExpectations(&session_manager_client_); @@ -301,8 +301,8 @@ policy_.policy().clear_new_public_key_verification_signature(); EXPECT_CALL(session_manager_client_, - StorePolicyForUser( - PolicyBuilder::kFakeUsername, policy_.GetBlob(), _)).Times(0); + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) + .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); Mock::VerifyAndClearExpectations(&session_manager_client_); @@ -315,8 +315,8 @@ *policy_.policy().mutable_new_public_key_verification_signature() = "garbage"; EXPECT_CALL(session_manager_client_, - StorePolicyForUser( - PolicyBuilder::kFakeUsername, policy_.GetBlob(), _)).Times(0); + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) + .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); Mock::VerifyAndClearExpectations(&session_manager_client_); @@ -326,8 +326,7 @@ // Store policy. chromeos::SessionManagerClient::StorePolicyCallback store_callback; EXPECT_CALL(session_manager_client_, - StorePolicyForUser(PolicyBuilder::kFakeUsername, - policy_.GetBlob(), _)) + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) .WillOnce(SaveArg<2>(&store_callback)); store_->Store(policy_.policy()); RunUntilIdle(); @@ -351,8 +350,7 @@ chromeos::SessionManagerClient::StorePolicyCallback store_callback; ExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR); EXPECT_CALL(session_manager_client_, - StorePolicyForUser(PolicyBuilder::kFakeUsername, - policy_.GetBlob(), _)) + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); @@ -362,8 +360,7 @@ TEST_F(UserCloudPolicyStoreChromeOSTest, StoreWithoutPolicyKey) { // Make the dbus call to cryptohome fail. Mock::VerifyAndClearExpectations(&cryptohome_client_); - EXPECT_CALL(cryptohome_client_, - GetSanitizedUsername(PolicyBuilder::kFakeUsername, _)) + EXPECT_CALL(cryptohome_client_, GetSanitizedUsername(cryptohome_id_, _)) .Times(AnyNumber()) .WillRepeatedly(SendSanitizedUsername(chromeos::DBUS_METHOD_CALL_FAILURE, std::string())); @@ -372,8 +369,7 @@ chromeos::SessionManagerClient::StorePolicyCallback store_callback; ExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR); EXPECT_CALL(session_manager_client_, - StorePolicyForUser(PolicyBuilder::kFakeUsername, - policy_.GetBlob(), _)) + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); @@ -388,8 +384,7 @@ chromeos::SessionManagerClient::StorePolicyCallback store_callback; ExpectError(CloudPolicyStore::STATUS_VALIDATION_ERROR); EXPECT_CALL(session_manager_client_, - StorePolicyForUser(PolicyBuilder::kFakeUsername, - policy_.GetBlob(), _)) + StorePolicyForUser(cryptohome_id_, policy_.GetBlob(), _)) .Times(0); store_->Store(policy_.policy()); RunUntilIdle(); @@ -580,10 +575,9 @@ TEST_F(UserCloudPolicyStoreChromeOSTest, LoadImmediately) { EXPECT_CALL(observer_, OnStoreLoaded(store_.get())); EXPECT_CALL(session_manager_client_, - BlockingRetrievePolicyForUser(PolicyBuilder::kFakeUsername)) + BlockingRetrievePolicyForUser(cryptohome_id_)) .WillOnce(Return(policy_.GetBlob())); - EXPECT_CALL(cryptohome_client_, - BlockingGetSanitizedUsername(PolicyBuilder::kFakeUsername)) + EXPECT_CALL(cryptohome_client_, BlockingGetSanitizedUsername(cryptohome_id_)) .WillOnce(Return(kSanitizedUsername)); EXPECT_FALSE(store_->policy()); @@ -606,7 +600,7 @@ TEST_F(UserCloudPolicyStoreChromeOSTest, LoadImmediatelyNoPolicy) { EXPECT_CALL(observer_, OnStoreLoaded(store_.get())); EXPECT_CALL(session_manager_client_, - BlockingRetrievePolicyForUser(PolicyBuilder::kFakeUsername)) + BlockingRetrievePolicyForUser(cryptohome_id_)) .WillOnce(Return("")); EXPECT_FALSE(store_->policy()); @@ -622,7 +616,7 @@ TEST_F(UserCloudPolicyStoreChromeOSTest, LoadImmediatelyInvalidBlob) { EXPECT_CALL(observer_, OnStoreError(store_.get())); EXPECT_CALL(session_manager_client_, - BlockingRetrievePolicyForUser(PolicyBuilder::kFakeUsername)) + BlockingRetrievePolicyForUser(cryptohome_id_)) .WillOnce(Return("le blob")); EXPECT_FALSE(store_->policy()); @@ -638,10 +632,9 @@ TEST_F(UserCloudPolicyStoreChromeOSTest, LoadImmediatelyDBusFailure) { EXPECT_CALL(observer_, OnStoreError(store_.get())); EXPECT_CALL(session_manager_client_, - BlockingRetrievePolicyForUser(PolicyBuilder::kFakeUsername)) + BlockingRetrievePolicyForUser(cryptohome_id_)) .WillOnce(Return(policy_.GetBlob())); - EXPECT_CALL(cryptohome_client_, - BlockingGetSanitizedUsername(PolicyBuilder::kFakeUsername)) + EXPECT_CALL(cryptohome_client_, BlockingGetSanitizedUsername(cryptohome_id_)) .WillOnce(Return("")); EXPECT_FALSE(store_->policy()); @@ -658,10 +651,9 @@ TEST_F(UserCloudPolicyStoreChromeOSTest, LoadImmediatelyNoUserPolicyKey) { EXPECT_CALL(observer_, OnStoreError(store_.get())); EXPECT_CALL(session_manager_client_, - BlockingRetrievePolicyForUser(PolicyBuilder::kFakeUsername)) + BlockingRetrievePolicyForUser(cryptohome_id_)) .WillOnce(Return(policy_.GetBlob())); - EXPECT_CALL(cryptohome_client_, - BlockingGetSanitizedUsername(PolicyBuilder::kFakeUsername)) + EXPECT_CALL(cryptohome_client_, BlockingGetSanitizedUsername(cryptohome_id_)) .WillOnce(Return("wrong@example.com")); EXPECT_FALSE(store_->policy());
diff --git a/chrome/browser/chromeos/settings/device_settings_test_helper.cc b/chrome/browser/chromeos/settings/device_settings_test_helper.cc index 48b6aee..63701db 100644 --- a/chrome/browser/chromeos/settings/device_settings_test_helper.cc +++ b/chrome/browser/chromeos/settings/device_settings_test_helper.cc
@@ -14,6 +14,7 @@ #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/ownership/mock_owner_key_util.h" #include "content/public/browser/browser_thread.h" @@ -111,7 +112,8 @@ void DeviceSettingsTestHelper::RestartJob( const std::vector<std::string>& argv) {} -void DeviceSettingsTestHelper::StartSession(const std::string& user_email) {} +void DeviceSettingsTestHelper::StartSession( + const cryptohome::Identification& cryptohome_id) {} void DeviceSettingsTestHelper::StopSession() {} @@ -136,12 +138,11 @@ } void DeviceSettingsTestHelper::RetrievePolicyForUser( - const std::string& username, - const RetrievePolicyCallback& callback) { -} + const cryptohome::Identification& cryptohome_id, + const RetrievePolicyCallback& callback) {} std::string DeviceSettingsTestHelper::BlockingRetrievePolicyForUser( - const std::string& username) { + const cryptohome::Identification& cryptohome_id) { return ""; } @@ -160,10 +161,9 @@ } void DeviceSettingsTestHelper::StorePolicyForUser( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const std::string& policy_blob, - const StorePolicyCallback& callback) { -} + const StorePolicyCallback& callback) {} void DeviceSettingsTestHelper::StoreDeviceLocalAccountPolicy( const std::string& account_id, @@ -174,7 +174,7 @@ } void DeviceSettingsTestHelper::SetFlagsForUser( - const std::string& account_id, + const cryptohome::Identification& cryptohome_id, const std::vector<std::string>& flags) {} void DeviceSettingsTestHelper::GetServerBackedStateKeys(
diff --git a/chrome/browser/chromeos/settings/device_settings_test_helper.h b/chrome/browser/chromeos/settings/device_settings_test_helper.h index cb36b6a..5bf73f3 100644 --- a/chrome/browser/chromeos/settings/device_settings_test_helper.h +++ b/chrome/browser/chromeos/settings/device_settings_test_helper.h
@@ -89,7 +89,7 @@ bool IsScreenLocked() const override; void EmitLoginPromptVisible() override; void RestartJob(const std::vector<std::string>& argv) override; - void StartSession(const std::string& user_email) override; + void StartSession(const cryptohome::Identification& cryptohome_id) override; void StopSession() override; void NotifySupervisedUserCreationStarted() override; void NotifySupervisedUserCreationFinished() override; @@ -99,23 +99,23 @@ void NotifyLockScreenDismissed() override; void RetrieveActiveSessions(const ActiveSessionsCallback& callback) override; void RetrieveDevicePolicy(const RetrievePolicyCallback& callback) override; - void RetrievePolicyForUser(const std::string& username, + void RetrievePolicyForUser(const cryptohome::Identification& cryptohome_id, const RetrievePolicyCallback& callback) override; std::string BlockingRetrievePolicyForUser( - const std::string& username) override; + const cryptohome::Identification& cryptohome_id) override; void RetrieveDeviceLocalAccountPolicy( const std::string& account_id, const RetrievePolicyCallback& callback) override; void StoreDevicePolicy(const std::string& policy_blob, const StorePolicyCallback& callback) override; - void StorePolicyForUser(const std::string& username, + void StorePolicyForUser(const cryptohome::Identification& cryptohome_id, const std::string& policy_blob, const StorePolicyCallback& callback) override; void StoreDeviceLocalAccountPolicy( const std::string& account_id, const std::string& policy_blob, const StorePolicyCallback& callback) override; - void SetFlagsForUser(const std::string& account_id, + void SetFlagsForUser(const cryptohome::Identification& cryptohome_id, const std::vector<std::string>& flags) override; void GetServerBackedStateKeys(const StateKeysCallback& callback) override;
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc index 914535b..7989e95 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer.cc +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer.cc
@@ -23,6 +23,8 @@ #include "base/sequenced_task_runner.h" #include "base/strings/string_util.h" #include "base/thread_task_runner_handle.h" +#include "base/value_conversions.h" +#include "base/values.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/supervised_user/supervised_user_whitelist_service.h" #include "chrome/common/chrome_paths.h" @@ -54,6 +56,8 @@ // (since it's not built on Android). const char kExtensionName[] = "name"; const char kExtensionShortName[] = "short_name"; +const char kExtensionIcons[] = "icons"; +const char kExtensionLargeIcon[] = "128"; base::string16 GetWhitelistTitle(const base::DictionaryValue& manifest) { base::string16 title; @@ -62,14 +66,33 @@ return title; } +base::FilePath GetLargeIconPath(const base::DictionaryValue& manifest, + const base::FilePath& install_dir) { + const base::DictionaryValue* icons = nullptr; + if (!manifest.GetDictionary(kExtensionIcons, &icons)) + return base::FilePath(); + + base::FilePath path; + const base::Value* path_value = nullptr; + if (!icons->Get(kExtensionLargeIcon, &path_value)) + return base::FilePath(); + if (!base::GetValueAsFilePath(*path_value, &path)) + return base::FilePath(); + + return install_dir.Append(path); +} + base::FilePath GetRawWhitelistPath(const base::DictionaryValue& manifest, const base::FilePath& install_dir) { const base::DictionaryValue* whitelist_dict = nullptr; if (!manifest.GetDictionary(kWhitelistedContent, &whitelist_dict)) return base::FilePath(); - base::FilePath::StringType whitelist_file; - if (!whitelist_dict->GetString(kSites, &whitelist_file)) + base::FilePath whitelist_file; + const base::Value* whitelist_file_value = nullptr; + if (!whitelist_dict->Get(kSites, &whitelist_file_value)) + return base::FilePath(); + if (!base::GetValueAsFilePath(*whitelist_file_value, &whitelist_file)) return base::FilePath(); return install_dir.Append(whitelist_file); @@ -207,7 +230,9 @@ : public ComponentInstallerTraits { public: using RawWhitelistReadyCallback = - base::Callback<void(const base::string16&, const base::FilePath&)>; + base::Callback<void(const base::string16&, /* title */ + const base::FilePath&, /* icon_path */ + const base::FilePath& /* whitelist_path */)>; SupervisedUserWhitelistComponentInstallerTraits( const std::string& crx_id, @@ -264,6 +289,7 @@ // using extension_l10n_util::LocalizeExtension, but that doesn't exist on // Android. crbug.com/558387 callback_.Run(GetWhitelistTitle(*manifest), + GetLargeIconPath(*manifest, install_dir), GetRawWhitelistPath(*manifest, install_dir)); } @@ -304,9 +330,11 @@ void OnRawWhitelistReady(const std::string& crx_id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& whitelist_path); void OnSanitizedWhitelistReady(const std::string& crx_id, - const base::string16& title); + const base::string16& title, + const base::FilePath& large_icon_path); // SupervisedUserWhitelistInstaller overrides: void RegisterComponents() override; @@ -399,6 +427,7 @@ void SupervisedUserWhitelistInstallerImpl::OnRawWhitelistReady( const std::string& crx_id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& whitelist_path) { cus_->GetSequencedTaskRunner()->PostTask( FROM_HERE, @@ -407,14 +436,16 @@ base::ThreadTaskRunnerHandle::Get(), base::Bind( &SupervisedUserWhitelistInstallerImpl::OnSanitizedWhitelistReady, - weak_ptr_factory_.GetWeakPtr(), crx_id, title))); + weak_ptr_factory_.GetWeakPtr(), crx_id, title, large_icon_path))); } void SupervisedUserWhitelistInstallerImpl::OnSanitizedWhitelistReady( const std::string& crx_id, - const base::string16& title) { + const base::string16& title, + const base::FilePath& large_icon_path) { for (const WhitelistReadyCallback& callback : callbacks_) - callback.Run(crx_id, title, GetSanitizedWhitelistPath(crx_id)); + callback.Run(crx_id, title, large_icon_path, + GetSanitizedWhitelistPath(crx_id)); } void SupervisedUserWhitelistInstallerImpl::RegisterComponents() {
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer.h b/chrome/browser/component_updater/supervised_user_whitelist_installer.h index bf75b438..47ea4c66 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer.h +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer.h
@@ -33,6 +33,7 @@ using WhitelistReadyCallback = base::Callback<void(const std::string& crx_id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& whitelist_path)>; virtual ~SupervisedUserWhitelistInstaller() {}
diff --git a/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc b/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc index 7b716a4..a45fb3a3 100644 --- a/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc +++ b/chrome/browser/component_updater/supervised_user_whitelist_installer_unittest.cc
@@ -52,6 +52,7 @@ const char kVersion[] = "1.2.3.4"; const char kWhitelistContents[] = "{\"foo\": \"bar\"}"; const char kWhitelistFile[] = "whitelist.json"; +const char kLargeIconFile[] = "icon.png"; std::string CrxIdToHashToCrxId(const std::string& kCrxId) { CrxComponent component; @@ -165,17 +166,22 @@ void Wait() { run_loop_.Run(); } - const base::FilePath& whitelist_path() { return whitelist_path_; } + const base::FilePath& large_icon_path() const { return large_icon_path_; } + const base::FilePath& whitelist_path() const { return whitelist_path_; } private: void OnWhitelistReady(const std::string& crx_id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& whitelist_path) { + EXPECT_EQ(base::FilePath::StringType(), large_icon_path_.value()); EXPECT_EQ(base::FilePath::StringType(), whitelist_path_.value()); whitelist_path_ = whitelist_path; + large_icon_path_ = large_icon_path; run_loop_.Quit(); } + base::FilePath large_icon_path_; base::FilePath whitelist_path_; base::RunLoop run_loop_; @@ -226,6 +232,12 @@ new base::DictionaryValue); whitelist_dict->SetString("sites", kWhitelistFile); manifest_.Set("whitelisted_content", whitelist_dict.release()); + + large_icon_path_ = whitelist_version_directory_.AppendASCII(kLargeIconFile); + scoped_ptr<base::DictionaryValue> icons_dict(new base::DictionaryValue); + icons_dict->SetString("128", kLargeIconFile); + manifest_.Set("icons", icons_dict.release()); + manifest_.SetString("version", kVersion); scoped_ptr<base::DictionaryValue> crx_dict(new base::DictionaryValue); @@ -287,6 +299,7 @@ base::FilePath whitelist_version_directory_; base::FilePath installed_whitelist_directory_; base::FilePath whitelist_path_; + base::FilePath large_icon_path_; base::DictionaryValue manifest_; base::DictionaryValue pref_; }; @@ -336,6 +349,7 @@ observer.Wait(); EXPECT_EQ(whitelist_path_.value(), observer.whitelist_path().value()); + EXPECT_EQ(large_icon_path_.value(), observer.large_icon_path().value()); std::string whitelist_contents; ASSERT_TRUE(base::ReadFileToString(whitelist_path_, &whitelist_contents));
diff --git a/chrome/browser/download/notification/download_notification_browsertest.cc b/chrome/browser/download/notification/download_notification_browsertest.cc index 98f81ea..fe7205c 100644 --- a/chrome/browser/download/notification/download_notification_browsertest.cc +++ b/chrome/browser/download/notification/download_notification_browsertest.cc
@@ -1194,10 +1194,12 @@ user_manager::UserManager* const user_manager = user_manager::UserManager::Get(); if (log_in) - user_manager->UserLoggedIn(AccountId::FromUserEmail(info.email), - info.hash, false); - user_manager->SaveUserDisplayName(AccountId::FromUserEmail(info.email), - base::UTF8ToUTF16(info.display_name)); + user_manager->UserLoggedIn( + AccountId::FromUserEmailGaiaId(info.email, info.gaia_id), info.hash, + false); + user_manager->SaveUserDisplayName( + AccountId::FromUserEmailGaiaId(info.email, info.gaia_id), + base::UTF8ToUTF16(info.display_name)); SigninManagerFactory::GetForProfile( chromeos::ProfileHelper::GetProfileByUserIdHash(info.hash)) ->SetAuthenticatedAccountInfo(info.gaia_id, info.email);
diff --git a/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc b/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc index a61a301..3484ec3 100644 --- a/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc +++ b/chrome/browser/extensions/api/declarative_content/content_action_unittest.cc
@@ -21,6 +21,7 @@ #include "extensions/browser/extension_system.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" +#include "extensions/common/feature_switch.h" #include "extensions/common/value_builder.h" #include "ipc/ipc_message_utils.h" #include "testing/gmock/include/gmock/gmock.h" @@ -98,6 +99,9 @@ } TEST(DeclarativeContentActionTest, ShowPageActionWithoutPageAction) { + // Tests legacy behavior. + FeatureSwitch::ScopedOverride action_redesign_override( + FeatureSwitch::extension_action_redesign(), false); TestExtensionEnvironment env; const Extension* extension = env.MakeExtension(base::DictionaryValue());
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc index f0694a0..97a58a1 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
@@ -20,6 +20,8 @@ #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile_manager.h" #include "chromeos/attestation/attestation_constants.h" #include "chromeos/attestation/mock_attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" @@ -72,7 +74,7 @@ void RegisterKeyCallbackTrue( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const cryptohome::AsyncMethodCaller::Callback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -81,7 +83,7 @@ void RegisterKeyCallbackFalse( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const cryptohome::AsyncMethodCaller::Callback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -90,7 +92,7 @@ void SignChallengeCallbackTrue( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -103,7 +105,7 @@ void SignChallengeCallbackFalse( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -116,7 +118,7 @@ void GetCertificateCallbackTrue( chromeos::attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool force_new_key, const chromeos::attestation::AttestationFlow::CertificateCallback& @@ -127,7 +129,7 @@ void GetCertificateCallbackFalse( chromeos::attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool force_new_key, const chromeos::attestation::AttestationFlow::CertificateCallback& @@ -141,6 +143,7 @@ EPKChallengeKeyTestBase() : settings_helper_(false), extension_(test_util::CreateEmptyExtension()), + profile_manager_(TestingBrowserProcess::GetGlobal()), fake_user_manager_(new chromeos::FakeChromeUserManager), user_manager_enabler_(fake_user_manager_) { // Set up the default behavior of mocks. @@ -169,6 +172,8 @@ } void SetUp() override { + ASSERT_TRUE(profile_manager_.SetUp()); + BrowserWithTestWindowTest::SetUp(); // Set the user preferences. @@ -178,8 +183,19 @@ prefs_->Set(prefs::kAttestationExtensionWhitelist, whitelist); SetAuthenticatedUser(); + } + + // This will be called by BrowserWithTestWindowTest::SetUp(); + TestingProfile* CreateProfile() override { fake_user_manager_->AddUserWithAffiliation( AccountId::FromUserEmail(kUserEmail), true); + return profile_manager_.CreateTestingProfile(kUserEmail); + } + + void DestroyProfile(TestingProfile* profile) override { + profile_manager_.DeleteTestingProfile(profile->GetProfileUserName()); + // Profile itself will be destroyed later in + // ProfileManager::ProfileInfo::~ProfileInfo() . } // Derived classes can override this method to set the required authenticated @@ -228,9 +244,11 @@ chromeos::ScopedCrosSettingsTestHelper settings_helper_; scoped_refptr<extensions::Extension> extension_; policy::StubEnterpriseInstallAttributes stub_install_attributes_; - PrefService* prefs_; + TestingProfileManager profile_manager_; + // fake_user_manager_ is owned by user_manager_enabler_. chromeos::FakeChromeUserManager* fake_user_manager_; chromeos::ScopedUserManagerEnabler user_manager_enabler_; + PrefService* prefs_ = nullptr; }; class EPKChallengeMachineKeyTest : public EPKChallengeKeyTestBase { @@ -328,10 +346,11 @@ _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. - EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_DEVICE, "", "attest-ent-machine", - "google.com", "device_id", _, "challenge", _)) + EXPECT_CALL( + mock_async_method_caller_, + TpmAttestationSignEnterpriseChallenge( + chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), + "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) .Times(1); scoped_ptr<base::Value> value( @@ -492,17 +511,19 @@ GetCertificate(chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, _, _, _, _)) .Times(1); + const cryptohome::Identification cryptohome_id( + AccountId::FromUserEmail(kUserEmail)); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL( mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_USER, kUserEmail, "attest-ent-user", + chromeos::attestation::KEY_USER, cryptohome_id, "attest-ent-user", kUserEmail, "device_id", _, "challenge", _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(chromeos::attestation::KEY_USER, - kUserEmail, "attest-ent-user", _)) + cryptohome_id, "attest-ent-user", _)) .Times(1); scoped_ptr<base::Value> value( @@ -537,8 +558,19 @@ protected: void SetAuthenticatedUser() override { SigninManagerFactory::GetForProfile(browser()->profile()) - ->SetAuthenticatedAccountInfo("12345", "test@chromium.com"); + ->SetAuthenticatedAccountInfo(account_id_.GetGaiaId(), + account_id_.GetUserEmail()); } + + TestingProfile* CreateProfile() override { + fake_user_manager_->AddUser(account_id_); + TestingProfile* profile = + profile_manager_.CreateTestingProfile(account_id_.GetUserEmail()); + return profile; + } + + const AccountId account_id_ = + AccountId::FromUserEmailGaiaId("test@chromium.com", "12345"); }; TEST_F(EPKChallengeMachineKeyUnmanagedUserTest, UserNotManaged) { @@ -550,8 +582,19 @@ protected: void SetAuthenticatedUser() override { SigninManagerFactory::GetForProfile(browser()->profile()) - ->SetAuthenticatedAccountInfo("12345", "test@chromium.com"); + ->SetAuthenticatedAccountInfo(account_id_.GetGaiaId(), + account_id_.GetUserEmail()); } + + TestingProfile* CreateProfile() override { + fake_user_manager_->AddUser(account_id_); + TestingProfile* profile = + profile_manager_.CreateTestingProfile(account_id_.GetUserEmail()); + return profile; + } + + const AccountId account_id_ = + AccountId::FromUserEmailGaiaId("test@chromium.com", "12345"); }; TEST_F(EPKChallengeUserKeyUnmanagedUserTest, UserNotManaged) {
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index 2d95cd0a..b394488a 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/chromeos/attestation/attestation_ca_client.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/profiles/profile.h" @@ -25,6 +26,7 @@ #include "chromeos/attestation/attestation_constants.h" #include "chromeos/attestation/attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" @@ -33,6 +35,7 @@ #include "components/prefs/pref_service.h" #include "components/signin/core/account_id/account_id.h" #include "components/signin/core/browser/signin_manager.h" +#include "components/user_manager/known_user.h" #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -59,18 +62,17 @@ EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, const base::Callback<void(PrepareKeyResult)>& callback) : key_type(key_type), - user_id(user_id), + account_id(account_id), key_name(key_name), certificate_profile(certificate_profile), require_user_consent(require_user_consent), - callback(callback) { -} + callback(callback) {} EPKPChallengeKeyBase::PrepareKeyContext::~PrepareKeyContext() { } @@ -141,16 +143,21 @@ return list->Find(value) != list->end(); } -bool EPKPChallengeKeyBase::IsUserManaged() const { - std::string email = GetUserEmail(); +AccountId EPKPChallengeKeyBase::GetAccountId() const { + const user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile_); - if (email.empty()) { - return false; + // Signin profile doesn't have associated user. + if (!user) { + return EmptyAccountId(); } + return user->GetAccountId(); +} + +bool EPKPChallengeKeyBase::IsUserManaged() const { const user_manager::User* const user = - user_manager::UserManager::Get()->FindUser( - AccountId::FromUserEmail(email)); + user_manager::UserManager::Get()->FindUser(GetAccountId()); if (user) { return user->IsAffiliated(); @@ -164,13 +171,7 @@ } std::string EPKPChallengeKeyBase::GetUserEmail() const { - SigninManagerBase* signin_manager = - SigninManagerFactory::GetForProfile(profile_); - if (!signin_manager) - return std::string(); - - return gaia::CanonicalizeEmail( - signin_manager->GetAuthenticatedAccountInfo().email); + return GetAccountId().GetUserEmail(); } std::string EPKPChallengeKeyBase::GetDeviceId() const { @@ -179,13 +180,13 @@ void EPKPChallengeKeyBase::PrepareKey( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, const base::Callback<void(PrepareKeyResult)>& callback) { const PrepareKeyContext context = PrepareKeyContext(key_type, - user_id, + account_id, key_name, certificate_profile, require_user_consent, @@ -209,7 +210,8 @@ } // Attestation is available, see if the key we need already exists. cryptohome_client_->TpmAttestationDoesKeyExist( - context.key_type, context.user_id, context.key_name, + context.key_type, cryptohome::Identification(context.account_id), + context.key_name, base::Bind(&EPKPChallengeKeyBase::DoesKeyExistCallback, base::Unretained(this), context)); } @@ -259,7 +261,7 @@ // Generate a new key and have it signed by PCA. attestation_flow_->GetCertificate( - context.certificate_profile, context.user_id, + context.certificate_profile, context.account_id, std::string(), // Not used. true, // Force a new key to be generated. base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback, @@ -356,7 +358,7 @@ } PrepareKey(chromeos::attestation::KEY_DEVICE, - std::string(), // Not used. + EmptyAccountId(), // Not used. kKeyName, chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, false, // user consent is not required. @@ -375,7 +377,7 @@ // Everything is checked. Sign the challenge. async_caller_->TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_DEVICE, - std::string(), // Not used. + cryptohome::Identification(), // Not used. kKeyName, GetEnterpriseDomain(), GetDeviceId(), chromeos::attestation::CHALLENGE_OPTION_NONE, challenge, base::Bind(&EPKPChallengeMachineKey::SignChallengeCallback, @@ -489,7 +491,7 @@ return; } - PrepareKey(chromeos::attestation::KEY_USER, GetUserEmail(), kKeyName, + PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(), kKeyName, chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, require_user_consent, base::Bind(&EPKPChallengeUserKey::PrepareKeyCallback, @@ -507,7 +509,8 @@ // Everything is checked. Sign the challenge. async_caller_->TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_USER, GetUserEmail(), kKeyName, GetUserEmail(), + chromeos::attestation::KEY_USER, + cryptohome::Identification(GetAccountId()), kKeyName, GetUserEmail(), GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, @@ -525,7 +528,8 @@ if (register_key) { async_caller_->TpmAttestationRegisterKey( - chromeos::attestation::KEY_USER, GetUserEmail(), kKeyName, + chromeos::attestation::KEY_USER, + cryptohome::Identification(GetAccountId()), kKeyName, base::Bind(&EPKPChallengeUserKey::RegisterKeyCallback, base::Unretained(this), response)); } else {
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h index 19f201b..98bb8d2 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h
@@ -18,6 +18,7 @@ #include "chromeos/attestation/attestation_flow.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" +#include "components/signin/core/account_id/account_id.h" #include "extensions/browser/extension_function.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -94,6 +95,9 @@ // Returns the user email. std::string GetUserEmail() const; + // Returns account id. + AccountId GetAccountId() const; + // Returns the enterprise virtual device ID. std::string GetDeviceId() const; @@ -103,7 +107,7 @@ // user consent before calling GetCertificate(). void PrepareKey( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, @@ -120,18 +124,17 @@ private: // Holds the context of a PrepareKey() operation. struct PrepareKeyContext { - PrepareKeyContext( - chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - chromeos::attestation::AttestationCertificateProfile - certificate_profile, - bool require_user_consent, - const base::Callback<void(PrepareKeyResult)>& callback); + PrepareKeyContext(chromeos::attestation::AttestationKeyType key_type, + const AccountId& account_id, + const std::string& key_name, + chromeos::attestation::AttestationCertificateProfile + certificate_profile, + bool require_user_consent, + const base::Callback<void(PrepareKeyResult)>& callback); ~PrepareKeyContext(); chromeos::attestation::AttestationKeyType key_type; - const std::string user_id; + const AccountId account_id; const std::string key_name; chromeos::attestation::AttestationCertificateProfile certificate_profile; bool require_user_consent;
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc index 4867a5ef..e52f893 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
@@ -20,9 +20,12 @@ #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile_manager.h" #include "chromeos/attestation/attestation_constants.h" #include "chromeos/attestation/mock_attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/mock_cryptohome_client.h" @@ -74,7 +77,7 @@ void RegisterKeyCallbackTrue( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const cryptohome::AsyncMethodCaller::Callback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -84,7 +87,7 @@ void RegisterKeyCallbackFalse( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const cryptohome::AsyncMethodCaller::Callback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -94,7 +97,7 @@ void SignChallengeCallbackTrue( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -108,7 +111,7 @@ void SignChallengeCallbackFalse( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -122,7 +125,7 @@ void GetCertificateCallbackTrue( chromeos::attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool force_new_key, const chromeos::attestation::AttestationFlow::CertificateCallback& @@ -134,7 +137,7 @@ void GetCertificateCallbackFalse( chromeos::attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool force_new_key, const chromeos::attestation::AttestationFlow::CertificateCallback& @@ -147,9 +150,11 @@ class EPKPChallengeKeyTestBase : public BrowserWithTestWindowTest { protected: EPKPChallengeKeyTestBase() - : settings_helper_(false), extension_(test_util::CreateEmptyExtension()), + : settings_helper_(false), + extension_(test_util::CreateEmptyExtension()), + profile_manager_(TestingBrowserProcess::GetGlobal()), fake_user_manager_(new chromeos::FakeChromeUserManager), - user_manager_enabler_(fake_user_manager_){ + user_manager_enabler_(fake_user_manager_) { // Set up the default behavior of mocks. ON_CALL(mock_cryptohome_client_, TpmAttestationDoesKeyExist(_, _, _, _)) .WillByDefault(WithArgs<3>(Invoke(FakeBoolDBusMethod( @@ -176,6 +181,8 @@ } void SetUp() override { + ASSERT_TRUE(profile_manager_.SetUp()); + BrowserWithTestWindowTest::SetUp(); // Set the user preferences. @@ -185,8 +192,19 @@ prefs_->Set(prefs::kAttestationExtensionWhitelist, whitelist); SetAuthenticatedUser(); + } + + // This will be called by BrowserWithTestWindowTest::SetUp(); + TestingProfile* CreateProfile() override { fake_user_manager_->AddUserWithAffiliation( AccountId::FromUserEmail(kUserEmail), true); + return profile_manager_.CreateTestingProfile(kUserEmail); + } + + void DestroyProfile(TestingProfile* profile) override { + profile_manager_.DeleteTestingProfile(profile->GetProfileUserName()); + // Profile itself will be destroyed later in + // ProfileManager::ProfileInfo::~ProfileInfo() . } // Derived classes can override this method to set the required authenticated @@ -202,9 +220,11 @@ chromeos::ScopedCrosSettingsTestHelper settings_helper_; scoped_refptr<extensions::Extension> extension_; policy::StubEnterpriseInstallAttributes stub_install_attributes_; - PrefService* prefs_; + TestingProfileManager profile_manager_; + // fake_user_manager_ is owned by user_manager_enabler_. chromeos::FakeChromeUserManager* fake_user_manager_; chromeos::ScopedUserManagerEnabler user_manager_enabler_; + PrefService* prefs_ = nullptr; }; class EPKPChallengeMachineKeyTest : public EPKPChallengeKeyTestBase { @@ -308,10 +328,11 @@ _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. - EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_DEVICE, "", "attest-ent-machine", - "google.com", "device_id", _, "challenge", _)) + EXPECT_CALL( + mock_async_method_caller_, + TpmAttestationSignEnterpriseChallenge( + chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), + "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) .Times(1); scoped_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( @@ -470,17 +491,19 @@ chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, _, _, _, _)) .Times(1); + const AccountId account_id = AccountId::FromUserEmail(kUserEmail); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_USER, kUserEmail, - "attest-ent-user", kUserEmail, "device_id", _, + chromeos::attestation::KEY_USER, + cryptohome::Identification(account_id), "attest-ent-user", + cryptohome::Identification(account_id).id(), "device_id", _, "challenge", _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(chromeos::attestation::KEY_USER, - kUserEmail, + cryptohome::Identification(account_id), "attest-ent-user", _)) .Times(1); @@ -514,9 +537,20 @@ : public EPKPChallengeMachineKeyTest { protected: void SetAuthenticatedUser() override { - SigninManagerFactory::GetForProfile(browser()->profile())-> - SetAuthenticatedAccountInfo("12345", "test@chromium.com"); + SigninManagerFactory::GetForProfile(browser()->profile()) + ->SetAuthenticatedAccountInfo(account_id_.GetGaiaId(), + account_id_.GetUserEmail()); } + + TestingProfile* CreateProfile() override { + fake_user_manager_->AddUser(account_id_); + TestingProfile* profile = + profile_manager_.CreateTestingProfile(account_id_.GetUserEmail()); + return profile; + } + + const AccountId account_id_ = + AccountId::FromUserEmailGaiaId("test@chromium.com", "12345"); }; TEST_F(EPKPChallengeMachineKeyUnmanagedUserTest, UserNotManaged) { @@ -527,9 +561,20 @@ class EPKPChallengeUserKeyUnmanagedUserTest : public EPKPChallengeUserKeyTest { protected: void SetAuthenticatedUser() override { - SigninManagerFactory::GetForProfile(browser()->profile())-> - SetAuthenticatedAccountInfo("12345", "test@chromium.com"); + SigninManagerFactory::GetForProfile(browser()->profile()) + ->SetAuthenticatedAccountInfo(account_id_.GetGaiaId(), + account_id_.GetUserEmail()); } + + TestingProfile* CreateProfile() override { + fake_user_manager_->AddUser(account_id_); + TestingProfile* profile = + profile_manager_.CreateTestingProfile(account_id_.GetUserEmail()); + return profile; + } + + const AccountId account_id_ = + AccountId::FromUserEmailGaiaId("test@chromium.com", "12345"); }; TEST_F(EPKPChallengeUserKeyUnmanagedUserTest, UserNotManaged) {
diff --git a/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc b/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc index f6f3fb5..7390dd9 100644 --- a/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc +++ b/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc
@@ -224,7 +224,8 @@ return RespondNow(Error(kErrorNoActiveEngine)); int frame_id = engine->CreateImeWindow( - extension(), options.url.get() ? *options.url : url::kAboutBlankURL, + extension(), render_frame_host(), + options.url.get() ? *options.url : url::kAboutBlankURL, options.window_type == input_ime::WINDOW_TYPE_FOLLOWCURSOR ? ui::ImeWindow::FOLLOW_CURSOR : ui::ImeWindow::NORMAL,
diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc index 39b6c694..34f14cbe 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_api.cc
@@ -64,22 +64,16 @@ namespace extensions { namespace MediaGalleries = api::media_galleries; -namespace DropPermissionForMediaFileSystem = - MediaGalleries::DropPermissionForMediaFileSystem; namespace GetMediaFileSystems = MediaGalleries::GetMediaFileSystems; namespace AddGalleryWatch = MediaGalleries::AddGalleryWatch; namespace RemoveGalleryWatch = MediaGalleries::RemoveGalleryWatch; -namespace GetAllGalleryWatch = MediaGalleries::GetAllGalleryWatch; namespace { const char kDisallowedByPolicy[] = "Media Galleries API is disallowed by policy: "; -const char kFailedToSetGalleryPermission[] = - "Failed to set gallery permission."; const char kInvalidGalleryIdMsg[] = "Invalid gallery id."; const char kMissingEventListener[] = "Missing event listener registration."; -const char kNonExistentGalleryId[] = "Non-existent gallery id."; const char kDeviceIdKey[] = "deviceId"; const char kGalleryIdKey[] = "galleryId"; @@ -472,72 +466,6 @@ cb); } - -/////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesGetAllMediaFileSystemMetadataFunction // -/////////////////////////////////////////////////////////////////////////////// -MediaGalleriesGetAllMediaFileSystemMetadataFunction:: - ~MediaGalleriesGetAllMediaFileSystemMetadataFunction() {} - -bool MediaGalleriesGetAllMediaFileSystemMetadataFunction::RunAsync() { - media_galleries::UsageCount( - media_galleries::GET_ALL_MEDIA_FILE_SYSTEM_METADATA); - return Setup(GetProfile(), &error_, base::Bind( - &MediaGalleriesGetAllMediaFileSystemMetadataFunction::OnPreferencesInit, - this)); -} - -void MediaGalleriesGetAllMediaFileSystemMetadataFunction::OnPreferencesInit() { - MediaFileSystemRegistry* registry = media_file_system_registry(); - MediaGalleriesPreferences* prefs = registry->GetPreferences(GetProfile()); - DCHECK(prefs->IsInitialized()); - MediaGalleryPrefIdSet permitted_gallery_ids = - prefs->GalleriesForExtension(*extension()); - - MediaStorageUtil::DeviceIdSet* device_ids = new MediaStorageUtil::DeviceIdSet; - const MediaGalleriesPrefInfoMap& galleries = prefs->known_galleries(); - for (MediaGalleryPrefIdSet::const_iterator it = permitted_gallery_ids.begin(); - it != permitted_gallery_ids.end(); ++it) { - MediaGalleriesPrefInfoMap::const_iterator gallery_it = galleries.find(*it); - DCHECK(gallery_it != galleries.end()); - device_ids->insert(gallery_it->second.device_id); - } - - MediaStorageUtil::FilterAttachedDevices( - device_ids, - base::Bind( - &MediaGalleriesGetAllMediaFileSystemMetadataFunction::OnGetGalleries, - this, - permitted_gallery_ids, - base::Owned(device_ids))); -} - -void MediaGalleriesGetAllMediaFileSystemMetadataFunction::OnGetGalleries( - const MediaGalleryPrefIdSet& permitted_gallery_ids, - const MediaStorageUtil::DeviceIdSet* available_devices) { - MediaFileSystemRegistry* registry = media_file_system_registry(); - MediaGalleriesPreferences* prefs = registry->GetPreferences(GetProfile()); - - base::ListValue* list = new base::ListValue(); - const MediaGalleriesPrefInfoMap& galleries = prefs->known_galleries(); - for (MediaGalleryPrefIdSet::const_iterator it = permitted_gallery_ids.begin(); - it != permitted_gallery_ids.end(); ++it) { - MediaGalleriesPrefInfoMap::const_iterator gallery_it = galleries.find(*it); - DCHECK(gallery_it != galleries.end()); - const MediaGalleryPrefInfo& gallery = gallery_it->second; - MediaGalleries::MediaFileSystemMetadata metadata; - metadata.name = base::UTF16ToUTF8(gallery.GetGalleryDisplayName()); - metadata.gallery_id = base::Uint64ToString(gallery.pref_id); - metadata.is_removable = StorageInfo::IsRemovableDevice(gallery.device_id); - metadata.is_media_device = StorageInfo::IsMediaDevice(gallery.device_id); - metadata.is_available = ContainsKey(*available_devices, gallery.device_id); - list->Append(metadata.ToValue().release()); - } - - SetResult(list); - SendResponse(true); -} - /////////////////////////////////////////////////////////////////////////////// // MediaGalleriesAddUserSelectedFolderFunction // /////////////////////////////////////////////////////////////////////////////// @@ -644,52 +572,6 @@ } /////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesDropPermissionForMediaFileSystemFunction // -/////////////////////////////////////////////////////////////////////////////// -MediaGalleriesDropPermissionForMediaFileSystemFunction:: - ~MediaGalleriesDropPermissionForMediaFileSystemFunction() {} - -bool MediaGalleriesDropPermissionForMediaFileSystemFunction::RunAsync() { - media_galleries::UsageCount( - media_galleries::DROP_PERMISSION_FOR_MEDIA_FILE_SYSTEM); - - scoped_ptr<DropPermissionForMediaFileSystem::Params> params( - DropPermissionForMediaFileSystem::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - MediaGalleryPrefId pref_id; - if (!base::StringToUint64(params->gallery_id, &pref_id)) { - error_ = kInvalidGalleryIdMsg; - return false; - } - - base::Closure callback = base::Bind( - &MediaGalleriesDropPermissionForMediaFileSystemFunction:: - OnPreferencesInit, - this, - pref_id); - return Setup(GetProfile(), &error_, callback); -} - -void MediaGalleriesDropPermissionForMediaFileSystemFunction::OnPreferencesInit( - MediaGalleryPrefId pref_id) { - MediaGalleriesPreferences* preferences = - media_file_system_registry()->GetPreferences(GetProfile()); - if (!ContainsKey(preferences->known_galleries(), pref_id)) { - error_ = kNonExistentGalleryId; - SendResponse(false); - return; - } - - bool dropped = preferences->SetGalleryPermissionForExtension( - *extension(), pref_id, false); - if (dropped) - SetResult(new base::StringValue(base::Uint64ToString(pref_id))); - else - error_ = kFailedToSetGalleryPermission; - SendResponse(dropped); -} - -/////////////////////////////////////////////////////////////////////////////// // MediaGalleriesGetMetadataFunction // /////////////////////////////////////////////////////////////////////////////// MediaGalleriesGetMetadataFunction::~MediaGalleriesGetMetadataFunction() {} @@ -991,66 +873,4 @@ SendResponse(true); } -/////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesGetAllGalleryWatchFunction // -/////////////////////////////////////////////////////////////////////////////// - -MediaGalleriesGetAllGalleryWatchFunction:: - ~MediaGalleriesGetAllGalleryWatchFunction() { -} - -bool MediaGalleriesGetAllGalleryWatchFunction::RunAsync() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - media_galleries::UsageCount(media_galleries::GET_ALL_GALLERY_WATCH); - if (!render_frame_host() || !render_frame_host()->GetProcess()) - return false; - - MediaGalleriesPreferences* preferences = - g_browser_process->media_file_system_registry()->GetPreferences( - GetProfile()); - preferences->EnsureInitialized(base::Bind( - &MediaGalleriesGetAllGalleryWatchFunction::OnPreferencesInit, this)); - return true; -} - -void MediaGalleriesGetAllGalleryWatchFunction::OnPreferencesInit() { - std::vector<std::string> result; - MediaGalleryPrefIdSet gallery_ids = - gallery_watch_manager()->GetWatchSet(GetProfile(), extension_id()); - for (MediaGalleryPrefIdSet::const_iterator iter = gallery_ids.begin(); - iter != gallery_ids.end(); - ++iter) { - result.push_back(base::Uint64ToString(*iter)); - } - results_ = GetAllGalleryWatch::Results::Create(result); - SendResponse(true); -} - -/////////////////////////////////////////////////////////////////////////////// -// MediaGalleriesRemoveAllGalleryWatchFunction // -/////////////////////////////////////////////////////////////////////////////// - -MediaGalleriesRemoveAllGalleryWatchFunction:: - ~MediaGalleriesRemoveAllGalleryWatchFunction() { -} - -bool MediaGalleriesRemoveAllGalleryWatchFunction::RunAsync() { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - media_galleries::UsageCount(media_galleries::REMOVE_ALL_GALLERY_WATCH); - if (!render_frame_host() || !render_frame_host()->GetProcess()) - return false; - - MediaGalleriesPreferences* preferences = - g_browser_process->media_file_system_registry()->GetPreferences( - GetProfile()); - preferences->EnsureInitialized(base::Bind( - &MediaGalleriesRemoveAllGalleryWatchFunction::OnPreferencesInit, this)); - return true; -} - -void MediaGalleriesRemoveAllGalleryWatchFunction::OnPreferencesInit() { - gallery_watch_manager()->RemoveAllWatches(GetProfile(), extension_id()); - SendResponse(true); -} - } // namespace extensions
diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_api.h b/chrome/browser/extensions/api/media_galleries/media_galleries_api.h index ea40115..e5f692b7 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_api.h +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_api.h
@@ -131,28 +131,6 @@ void GetMediaFileSystemsForExtension(const MediaFileSystemsCallback& cb); }; -class MediaGalleriesGetAllMediaFileSystemMetadataFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.getAllMediaFileSystemMetadata", - MEDIAGALLERIES_GETALLMEDIAFILESYSTEMMETADATA) - - protected: - ~MediaGalleriesGetAllMediaFileSystemMetadataFunction() override; - bool RunAsync() override; - - private: - // Bottom half for RunAsync, invoked after the preferences is initialized. - // Gets the list of permitted galleries and checks if they are available. - void OnPreferencesInit(); - - // Callback to run upon getting the list of available devices. - // Sends the list of media filesystem metadata back to the extension. - void OnGetGalleries( - const MediaGalleryPrefIdSet& permitted_gallery_ids, - const storage_monitor::MediaStorageUtil::DeviceIdSet* available_devices); -}; - class MediaGalleriesAddUserSelectedFolderFunction : public ChromeAsyncExtensionFunction { public: @@ -186,21 +164,6 @@ void GetMediaFileSystemsForExtension(const MediaFileSystemsCallback& cb); }; -class MediaGalleriesDropPermissionForMediaFileSystemFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.dropPermissionForMediaFileSystem", - MEDIAGALLERIES_DROPPERMISSIONFORMEDIAFILESYSTEM) - - protected: - ~MediaGalleriesDropPermissionForMediaFileSystemFunction() override; - bool RunAsync() override; - - private: - // Bottom half for RunAsync, invoked after the preferences is initialized. - void OnPreferencesInit(MediaGalleryPrefId pref_id); -}; - class MediaGalleriesGetMetadataFunction : public ChromeAsyncExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("mediaGalleries.getMetadata", @@ -262,34 +225,6 @@ void OnPreferencesInit(const std::string& pref_id); }; -class MediaGalleriesGetAllGalleryWatchFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.getAllGalleryWatch", - MEDIAGALLERIES_GETALLGALLERYWATCH); - - protected: - ~MediaGalleriesGetAllGalleryWatchFunction() override; - bool RunAsync() override; - - private: - void OnPreferencesInit(); -}; - -class MediaGalleriesRemoveAllGalleryWatchFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("mediaGalleries.removeAllGalleryWatch", - MEDIAGALLERIES_REMOVEALLGALLERYWATCH); - - protected: - ~MediaGalleriesRemoveAllGalleryWatchFunction() override; - bool RunAsync() override; - - private: - void OnPreferencesInit(); -}; - } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_MEDIA_GALLERIES_MEDIA_GALLERIES_API_H_
diff --git a/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc b/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc index f80da1da..af7306f 100644 --- a/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc +++ b/chrome/browser/extensions/api/media_galleries/media_galleries_watch_apitest.cc
@@ -32,7 +32,6 @@ const char kTestExtensionPath[] = "media_galleries/gallerywatch"; // JS commands. -const char kGetAllWatchedGalleryIdsCmd[] = "getAllWatchedGalleryIds()"; const char kGetMediaFileSystemsCmd[] = "getMediaFileSystems()"; const char kSetupWatchOnValidGalleriesCmd[] = "setupWatchOnValidGalleries()"; const char kSetupWatchOnUnlistenedValidGalleriesCmd[] = @@ -40,7 +39,6 @@ const char kAddGalleryChangedListenerCmd[] = "addGalleryChangedListener()"; const char kAddCheckingGalleryChangedListenerCmd[] = "addCheckingGalleryChangedListener()"; -const char kRemoveAllGalleryWatchCmd[] = "removeAllGalleryWatch()"; const char kRemoveGalleryChangedListenerCmd[] = "removeGalleryChangedListener()"; const char kRemoveGalleryWatchCmd[] = "removeGalleryWatch()"; @@ -48,25 +46,21 @@ // And JS reply messages. const char kAddGalleryWatchOK[] = "add_gallery_watch_ok"; -const char kGetAllGalleryWatchOK[] = "get_all_gallery_watch_ok"; const char kGetMediaFileSystemsCallbackOK[] = "get_media_file_systems_callback_ok"; const char kGetMediaFileSystemsOK[] = "get_media_file_systems_ok"; const char kAddGalleryChangedListenerOK[] = "add_gallery_changed_listener_ok"; -const char kRemoveAllGalleryWatchOK[] = "remove_all_gallery_watch_ok"; const char kRemoveGalleryChangedListenerOK[] = "remove_gallery_changed_listener_ok"; const char kRemoveGalleryWatchOK[] = "remove_gallery_watch_ok"; const char kOnGalleryChangedCheckingOK[] = "on_gallery_changed_checking_ok"; // Test reply messages. -const char kNoGalleryWatchesInstalled[] = "gallery_watchers_does_not_exists"; const char kAddGalleryWatchRequestFailed[] = "add_watch_request_failed"; const char kAddGalleryWatchRequestRuntimeError[] = "add_watch_request_runtime_error"; const char kAddGalleryWatchRequestSucceeded[] = "add_watch_request_succeeded"; const char kGalleryChangedEventReceived[] = "gallery_changed_event_received"; -const char kGalleryWatchesCheck[] = "gallery_watcher_checks"; } // namespace @@ -293,69 +287,3 @@ ExecuteCmdAndCheckReply( kSetupWatchOnInvalidGalleryCmd, kAddGalleryWatchRequestFailed); } - -IN_PROC_BROWSER_TEST_F(MediaGalleriesGalleryWatchApiTest, GetAllGalleryWatch) { - // Add gallery watch listener. - ExecuteCmdAndCheckReply(kAddGalleryChangedListenerCmd, - kAddGalleryChangedListenerOK); - - // Gallery watchers are not yet added. - // chrome.mediaGalleries.getAllGalleryWatch should return an empty - // list. - ExtensionTestMessageListener initial_get_all_check_finished( - kNoGalleryWatchesInstalled, false /* no reply */); - ExecuteCmdAndCheckReply(kGetAllWatchedGalleryIdsCmd, kGetAllGalleryWatchOK); - EXPECT_TRUE(initial_get_all_check_finished.WaitUntilSatisfied()); - - if (!GalleryWatchesSupported()) - return; - - SetupGalleryWatches(); - - // chrome.mediaGalleries.getAllGalleryWatch should return the - // gallery identifiers. - ExtensionTestMessageListener get_all_watched_galleries_finished( - kGalleryWatchesCheck, false /* no reply */); - ExecuteCmdAndCheckReply(kGetAllWatchedGalleryIdsCmd, kGetAllGalleryWatchOK); - EXPECT_TRUE(get_all_watched_galleries_finished.WaitUntilSatisfied()); - - // Remove gallery watch request. - ExecuteCmdAndCheckReply(kRemoveGalleryWatchCmd, kRemoveGalleryWatchOK); - - // Gallery watchers removed. - // chrome.mediaGalleries.getAllGalleryWatch() should return an empty - // list. - ExtensionTestMessageListener final_get_all_check_finished( - kNoGalleryWatchesInstalled, false /* no reply */); - ExecuteCmdAndCheckReply(kGetAllWatchedGalleryIdsCmd, kGetAllGalleryWatchOK); - EXPECT_TRUE(final_get_all_check_finished.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(MediaGalleriesGalleryWatchApiTest, - RemoveAllGalleryWatch) { - // Add gallery watch listener. - ExecuteCmdAndCheckReply(kAddGalleryChangedListenerCmd, - kAddGalleryChangedListenerOK); - - if (!GalleryWatchesSupported()) - return; - - SetupGalleryWatches(); - - // chrome.mediaGalleries.getAllGalleryWatch should return the watched - // gallery identifiers. - ExtensionTestMessageListener get_all_watched_galleries_finished( - kGalleryWatchesCheck, false /* no reply */); - ExecuteCmdAndCheckReply(kGetAllWatchedGalleryIdsCmd, kGetAllGalleryWatchOK); - EXPECT_TRUE(get_all_watched_galleries_finished.WaitUntilSatisfied()); - - // Remove all gallery watchers. - ExecuteCmdAndCheckReply(kRemoveAllGalleryWatchCmd, kRemoveAllGalleryWatchOK); - - // Gallery watchers removed. chrome.mediaGalleries.getAllGalleryWatch - // should return an empty list. - ExtensionTestMessageListener final_get_all_check_finished( - kNoGalleryWatchesInstalled, false /* no reply */); - ExecuteCmdAndCheckReply(kGetAllWatchedGalleryIdsCmd, kGetAllGalleryWatchOK); - EXPECT_TRUE(final_get_all_check_finished.WaitUntilSatisfied()); -}
diff --git a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc index f11313f..32709b6 100644 --- a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc +++ b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/shill_device_client.h" @@ -195,8 +196,11 @@ // TODO(pneubeck): Remove the following hack, once the NetworkingPrivateAPI // uses the ProfileHelper to obtain the userhash crbug/238623. - const std::string login_user = chromeos::login::CanonicalizeUserID( - command_line->GetSwitchValueNative(chromeos::switches::kLoginUser)); + const cryptohome::Identification login_user = + cryptohome::Identification::FromString( + chromeos::login::CanonicalizeUserID( + command_line->GetSwitchValueNative( + chromeos::switches::kLoginUser))); const std::string sanitized_user = CryptohomeClient::GetStubSanitizedUsername(login_user); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, @@ -209,7 +213,8 @@ CHECK(user); std::string userhash; DBusThreadManager::Get()->GetCryptohomeClient()->GetSanitizedUsername( - user->email(), base::Bind(&AssignString, &userhash_)); + cryptohome::Identification(user->GetAccountId()), + base::Bind(&AssignString, &userhash_)); content::RunAllPendingInMessageLoop(); CHECK(!userhash_.empty()); }
diff --git a/chrome/browser/extensions/api/page_capture/page_capture_api.cc b/chrome/browser/extensions/api/page_capture/page_capture_api.cc index ba0fd50..4707e64 100644 --- a/chrome/browser/extensions/api/page_capture/page_capture_api.cc +++ b/chrome/browser/extensions/api/page_capture/page_capture_api.cc
@@ -157,7 +157,7 @@ SendResponse(false); - Release(); // Balanced in Run() + // Must not Release() here, OnMessageReceived will call it eventually. } void PageCaptureSaveAsMHTMLFunction::ReturnSuccess(int64_t file_size) {
diff --git a/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc b/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc index 0062aaf..e40a5f1 100644 --- a/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc +++ b/chrome/browser/extensions/api/preference/chrome_direct_setting_api.cc
@@ -34,7 +34,6 @@ whitelist_.insert("googlegeolocationaccess.enabled"); // The following settings need to be checked and probably removed. See // http://crbug.com/164227#c157 . - whitelist_.insert("data_reduction.update_daily_lengths"); whitelist_.insert("easy_unlock.proximity_required"); }
diff --git a/chrome/browser/extensions/api/preference/preference_apitest.cc b/chrome/browser/extensions/api/preference/preference_apitest.cc index cd8e80d5..a8f8438 100644 --- a/chrome/browser/extensions/api/preference/preference_apitest.cc +++ b/chrome/browser/extensions/api/preference/preference_apitest.cc
@@ -345,12 +345,7 @@ EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } -#if defined(OS_WIN) // http://crbug.com/477844 -#define MAYBE_DataReductionProxy DISABLED_DataReductionProxy -#else -#define MAYBE_DataReductionProxy DataReductionProxy -#endif -IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, MAYBE_DataReductionProxy) { +IN_PROC_BROWSER_TEST_F(ExtensionPreferenceApiTest, DataReductionProxy) { EXPECT_TRUE(RunExtensionTest("preference/data_reduction_proxy")) << message_; }
diff --git a/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc b/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc index 756f6f2a..f8d78f7 100644 --- a/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc +++ b/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc
@@ -67,6 +67,11 @@ void RemoveObserver(Observer* observer) override { NOTREACHED(); } + int CountActiveDevices() const override { + NOTREACHED(); + return 0; + } + void Add(const DeviceInfo* device) { devices_.push_back(device); } private:
diff --git a/chrome/browser/extensions/api/socket/combined_socket_unittest.cc b/chrome/browser/extensions/api/socket/combined_socket_unittest.cc index d6ae864..22cdebb 100644 --- a/chrome/browser/extensions/api/socket/combined_socket_unittest.cc +++ b/chrome/browser/extensions/api/socket/combined_socket_unittest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/memory/scoped_ptr.h" #include "chrome/browser/extensions/api/socket/mock_tcp_client_socket.h" #include "extensions/browser/api/socket/socket.h" #include "extensions/browser/api/socket/tcp_socket.h" @@ -14,6 +15,20 @@ const int kBufferLength = 10; +template <typename T> +scoped_ptr<T> CreateTestSocket(scoped_ptr<MockTCPClientSocket> stream); + +template <> +scoped_ptr<TCPSocket> CreateTestSocket(scoped_ptr<MockTCPClientSocket> stream) { + return make_scoped_ptr(new TCPSocket(std::move(stream), "fake id", + true /* is_connected */)); +} + +template <> +scoped_ptr<TLSSocket> CreateTestSocket(scoped_ptr<MockTCPClientSocket> stream) { + return make_scoped_ptr(new TLSSocket(std::move(stream), "fake id")); +} + class CombinedSocketTest : public testing::Test { public: CombinedSocketTest() : count_(0), io_buffer_(nullptr) {} @@ -30,10 +45,10 @@ testing::Return(kBufferLength))); EXPECT_CALL(*stream, Disconnect()); - T socket(std::move(stream), "fake id"); + scoped_ptr<T> socket = CreateTestSocket<T>(std::move(stream)); ReadCompletionCallback read_callback = base::Bind(&CombinedSocketTest::OnRead, base::Unretained(this)); - socket.Read(kBufferLength, read_callback); + socket->Read(kBufferLength, read_callback); EXPECT_EQ(kBufferLength, count_); EXPECT_NE(nullptr, buffer); EXPECT_EQ(buffer, io_buffer_); @@ -53,10 +68,10 @@ testing::Return(net::ERR_IO_PENDING))); EXPECT_CALL(*stream, Disconnect()); - T socket(std::move(stream), "fake id"); + scoped_ptr<T> socket = CreateTestSocket<T>(std::move(stream)); ReadCompletionCallback read_callback = base::Bind(&CombinedSocketTest::OnRead, base::Unretained(this)); - socket.Read(kBufferLength, read_callback); + socket->Read(kBufferLength, read_callback); EXPECT_EQ(0, count_); EXPECT_EQ(nullptr, io_buffer_); socket_cb.Run(kBufferLength); @@ -78,10 +93,10 @@ ON_CALL(*stream, IsConnected()).WillByDefault(testing::Return(false)); EXPECT_CALL(*stream, Disconnect()); - T socket(std::move(stream), "fake id"); + scoped_ptr<T> socket = CreateTestSocket<T>(std::move(stream)); ReadCompletionCallback read_callback = base::Bind(&CombinedSocketTest::OnRead, base::Unretained(this)); - socket.Read(kBufferLength, read_callback); + socket->Read(kBufferLength, read_callback); EXPECT_EQ(kBufferLength, count_); EXPECT_NE(nullptr, buffer); EXPECT_EQ(buffer, io_buffer_);
diff --git a/chrome/browser/extensions/extension_action_icon_factory_unittest.cc b/chrome/browser/extensions/extension_action_icon_factory_unittest.cc index ae27486..5a1eb3e 100644 --- a/chrome/browser/extensions/extension_action_icon_factory_unittest.cc +++ b/chrome/browser/extensions/extension_action_icon_factory_unittest.cc
@@ -211,15 +211,14 @@ ASSERT_FALSE(browser_action->default_icon()); ASSERT_TRUE(browser_action->GetExplicitlySetIcon(0 /*tab id*/).IsEmpty()); - gfx::ImageSkia favicon = GetFavicon(); - ExtensionActionIconFactory icon_factory( profile(), extension.get(), browser_action, this); gfx::Image icon = icon_factory.GetIcon(0); EXPECT_TRUE(ImageRepsAreEqual( - favicon.GetRepresentation(1.0f), + browser_action->GetDefaultIconImage().ToImageSkia()->GetRepresentation( + 1.0f), icon.ToImageSkia()->GetRepresentation(1.0f))); } @@ -253,11 +252,12 @@ set_icon.ToImageSkia()->GetRepresentation(1.0f), icon.ToImageSkia()->GetRepresentation(1.0f))); - // It should still return favicon for another tabs. + // It should still return the default icon for another tab. icon = icon_factory.GetIcon(1); EXPECT_TRUE(ImageRepsAreEqual( - GetFavicon().GetRepresentation(1.0f), + browser_action->GetDefaultIconImage().ToImageSkia()->GetRepresentation( + 1.0f), icon.ToImageSkia()->GetRepresentation(1.0f))); }
diff --git a/chrome/browser/extensions/extension_browsertest.cc b/chrome/browser/extensions/extension_browsertest.cc index ace18cd..3476574 100644 --- a/chrome/browser/extensions/extension_browsertest.cc +++ b/chrome/browser/extensions/extension_browsertest.cc
@@ -138,7 +138,7 @@ // ExtensionService and then the real profile with one, as we do when // running on chromeos. command_line->AppendSwitchASCII(chromeos::switches::kLoginUser, - "TestUser@gmail.com"); + "testuser@gmail.com"); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user"); } #endif
diff --git a/chrome/browser/extensions/location_bar_controller_unittest.cc b/chrome/browser/extensions/location_bar_controller_unittest.cc index d34f821..09c12d28 100644 --- a/chrome/browser/extensions/location_bar_controller_unittest.cc +++ b/chrome/browser/extensions/location_bar_controller_unittest.cc
@@ -40,6 +40,8 @@ void SetUp() override { active_script_override_.reset(new FeatureSwitch::ScopedOverride( FeatureSwitch::scripts_require_action(), true)); + extension_action_override_.reset(new FeatureSwitch::ScopedOverride( + FeatureSwitch::extension_action_redesign(), false)); ChromeRenderViewHostTestHarness::SetUp(); #if defined OS_CHROMEOS @@ -99,6 +101,9 @@ // Since we also test that we show page actions for pending script requests, // we need to enable that feature. scoped_ptr<FeatureSwitch::ScopedOverride> active_script_override_; + + // This tests legacy page actions. + scoped_ptr<FeatureSwitch::ScopedOverride> extension_action_override_; }; // Test that the location bar gets the proper current actions.
diff --git a/chrome/browser/local_discovery/service_discovery_client_impl.cc b/chrome/browser/local_discovery/service_discovery_client_impl.cc index ba9317f7..77fc0148 100644 --- a/chrome/browser/local_discovery/service_discovery_client_impl.cc +++ b/chrome/browser/local_discovery/service_discovery_client_impl.cc
@@ -498,7 +498,7 @@ DCHECK(record->type() == net::dns_protocol::kTypeA); const net::ARecordRdata* a_rdata = record->rdata<net::ARecordRdata>(); DCHECK(a_rdata); - return net::IPAddress(a_rdata->address()); + return a_rdata->address(); } LocalDomainResolverImpl::LocalDomainResolverImpl( @@ -545,11 +545,11 @@ if (result == net::MDnsTransaction::RESULT_RECORD) { if (record->type() == net::dns_protocol::kTypeA) { const net::ARecordRdata* rdata = record->rdata<net::ARecordRdata>(); - address_ipv4_ = net::IPAddress(rdata->address()); + address_ipv4_ = rdata->address(); } else { DCHECK_EQ(net::dns_protocol::kTypeAAAA, record->type()); const net::AAAARecordRdata* rdata = record->rdata<net::AAAARecordRdata>(); - address_ipv6_ = net::IPAddress(rdata->address()); + address_ipv6_ = rdata->address(); } }
diff --git a/chrome/browser/media/media_browsertest.cc b/chrome/browser/media/media_browsertest.cc index 79eb35c5..d02f752 100644 --- a/chrome/browser/media/media_browsertest.cc +++ b/chrome/browser/media/media_browsertest.cc
@@ -17,11 +17,16 @@ #include "media/base/test_data_util.h" #include "net/test/embedded_test_server/embedded_test_server.h" -// Common test results. -const char MediaBrowserTest::kEnded[] = "ENDED"; -const char MediaBrowserTest::kError[] = "ERROR"; +// Normal failure title. const char MediaBrowserTest::kFailed[] = "FAILED"; +// Capitalized event name set by Utils.installTitleEventHandler(). +const char MediaBrowserTest::kEnded[] = "ENDED"; + +// Uncapitalized event name as set by Utils.failTest(). +// TODO(sandersd): Change the tests to use a more unique message. +const char MediaBrowserTest::kError[] = "error"; + MediaBrowserTest::MediaBrowserTest() : ignore_plugin_crash_(false) {} MediaBrowserTest::~MediaBrowserTest() {}
diff --git a/chrome/browser/metrics/chrome_metrics_service_client.cc b/chrome/browser/metrics/chrome_metrics_service_client.cc index 4beb040..cd2abf0 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client.cc
@@ -24,6 +24,7 @@ #include "chrome/browser/google/google_brand.h" #include "chrome/browser/metrics/chrome_stability_metrics_provider.h" #include "chrome/browser/metrics/time_ticks_experiment_win.h" +#include "chrome/browser/sync/chrome_sync_client.h" #include "chrome/browser/ui/browser_otr_state.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_constants.h" @@ -49,6 +50,7 @@ #include "components/omnibox/browser/omnibox_metrics_provider.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" +#include "components/sync_driver/device_count_metrics_provider.h" #include "components/variations/variations_associated_data.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" @@ -430,6 +432,11 @@ make_scoped_ptr(new ChromeSigninStatusMetricsProviderDelegate)))); #endif // !defined(OS_CHROMEOS) + metrics_service_->RegisterMetricsProvider( + scoped_ptr<metrics::MetricsProvider>( + new sync_driver::DeviceCountMetricsProvider(base::Bind( + &browser_sync::ChromeSyncClient::GetDeviceInfoTrackers)))); + // Clear stability metrics if it is the first time cellular upload logic // should apply to avoid sudden bulk uploads. It needs to be done after all // providers are registered.
diff --git a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc index 360fc36..b660aa0 100644 --- a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc
@@ -54,8 +54,10 @@ #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h" #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h" #include "chromeos/chromeos_paths.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" #include "chromeos/login/user_names.h" +#include "components/signin/core/account_id/account_id.h" #else #include "chrome/browser/policy/cloud/user_cloud_policy_manager_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" @@ -334,7 +336,9 @@ ASSERT_TRUE( PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &user_policy_key_dir)); std::string sanitized_username = - chromeos::CryptohomeClient::GetStubSanitizedUsername(GetTestUser()); + chromeos::CryptohomeClient::GetStubSanitizedUsername( + cryptohome::Identification( + AccountId::FromUserEmail(GetTestUser()))); user_policy_key_file_ = user_policy_key_dir.AppendASCII(sanitized_username) .AppendASCII("policy.pub"); #endif
diff --git a/chrome/browser/profiles/profile_io_data.cc b/chrome/browser/profiles/profile_io_data.cc index 9e86ca9a..f34a67b 100644 --- a/chrome/browser/profiles/profile_io_data.cc +++ b/chrome/browser/profiles/profile_io_data.cc
@@ -295,15 +295,14 @@ } } -void GetTPMInfoForUserOnUIThread(const std::string& username, +void GetTPMInfoForUserOnUIThread(const AccountId& account_id, const std::string& username_hash) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DVLOG(1) << "Getting TPM info from cryptohome for " - << " " << username << " " << username_hash; + << " " << account_id.Serialize() << " " << username_hash; scoped_ptr<chromeos::TPMTokenInfoGetter> scoped_token_info_getter = chromeos::TPMTokenInfoGetter::CreateForUserToken( - username, - chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), + account_id, chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), base::ThreadTaskRunnerHandle::Get()); chromeos::TPMTokenInfoGetter* token_info_getter = scoped_token_info_getter.get(); @@ -318,21 +317,20 @@ username_hash)); } -void StartTPMSlotInitializationOnIOThread(const std::string& username, +void StartTPMSlotInitializationOnIOThread(const AccountId& account_id, const std::string& username_hash) { DCHECK_CURRENTLY_ON(BrowserThread::IO); BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - base::Bind(&GetTPMInfoForUserOnUIThread, username, username_hash)); + BrowserThread::UI, FROM_HERE, + base::Bind(&GetTPMInfoForUserOnUIThread, account_id, username_hash)); } -void StartNSSInitOnIOThread(const std::string& username, +void StartNSSInitOnIOThread(const AccountId& account_id, const std::string& username_hash, const base::FilePath& path) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - DVLOG(1) << "Starting NSS init for " << username + DVLOG(1) << "Starting NSS init for " << account_id.Serialize() << " hash:" << username_hash; // Make sure NSS is initialized for the user. @@ -347,9 +345,10 @@ crypto::WillInitializeTPMForChromeOSUser(username_hash); if (crypto::IsTPMTokenEnabledForNSS()) { - if (crypto::IsTPMTokenReady(base::Bind( - &StartTPMSlotInitializationOnIOThread, username, username_hash))) { - StartTPMSlotInitializationOnIOThread(username, username_hash); + if (crypto::IsTPMTokenReady( + base::Bind(&StartTPMSlotInitializationOnIOThread, account_id, + username_hash))) { + StartTPMSlotInitializationOnIOThread(account_id, username_hash); } else { DVLOG(1) << "Waiting for tpm ready ..."; } @@ -446,12 +445,10 @@ if (user && !user->username_hash().empty()) { params->username_hash = user->username_hash(); DCHECK(!params->username_hash.empty()); - BrowserThread::PostTask(BrowserThread::IO, - FROM_HERE, - base::Bind(&StartNSSInitOnIOThread, - user->email(), - user->username_hash(), - profile->GetPath())); + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::Bind(&StartNSSInitOnIOThread, user->GetAccountId(), + user->username_hash(), profile->GetPath())); // Use the device-wide system key slot only if the user is affiliated on // the device.
diff --git a/chrome/browser/resources/chromeos/braille_ime/compiled_resources.gyp b/chrome/browser/resources/chromeos/braille_ime/compiled_resources.gyp deleted file mode 100644 index 1722255..0000000 --- a/chrome/browser/resources/chromeos/braille_ime/compiled_resources.gyp +++ /dev/null
@@ -1,21 +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. - -{ - 'targets': [ - { - 'target_name': 'main', - 'variables': { - 'depends': [ - 'braille_ime.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/chrome_extensions.js', - 'externs.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/chromeos/braille_ime/compiled_resources2.gyp b/chrome/browser/resources/chromeos/braille_ime/compiled_resources2.gyp new file mode 100644 index 0000000..b02b750 --- /dev/null +++ b/chrome/browser/resources/chromeos/braille_ime/compiled_resources2.gyp
@@ -0,0 +1,26 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'braille_ime', + 'dependencies': [ + '<(EXTERNS_GYP):chrome_extensions', + 'externs', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'externs', + 'includes': ['../../../../../third_party/closure_compiler/include_js.gypi'], + }, + { + 'target_name': 'main', + 'dependencies': [ + 'braille_ime', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox.gni b/chrome/browser/resources/chromeos/chromevox/chromevox.gni index f3bf9a6..b5535cb19 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox.gni +++ b/chrome/browser/resources/chromeos/chromevox/chromevox.gni
@@ -133,6 +133,7 @@ "cvox2/background/desktop_automation_handler.js", "cvox2/background/earcon_engine.js", "cvox2/background/editing.js", + "cvox2/background/i_search.js", "cvox2/background/live_regions.js", "cvox2/background/next_earcons.js", "cvox2/background/output.js",
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json b/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json index f64e8f4..e35b812 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/background/keymaps/next_keymap.json
@@ -492,6 +492,15 @@ "keyCode": [65, 73] } } + }, + { + "command": "toggleSearchWidget", + "sequence": { + "cvoxModifier": true, + "keys": { + "keyCode": [191] + } + } } ] }
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi b/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi index e683b09..63b56bcf 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi +++ b/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi
@@ -84,6 +84,7 @@ 'cvox2/background/background_test.extjs', 'cvox2/background/cursors_test.extjs', 'cvox2/background/editing_test.extjs', + 'cvox2/background/i_search_test.extjs', 'cvox2/background/live_regions_test.extjs', 'cvox2/background/output_test.extjs', 'cvox2/background/tree_walker_test.extjs',
diff --git a/chrome/browser/resources/chromeos/chromevox/common/msgs.js b/chrome/browser/resources/chromeos/chromevox/common/msgs.js index 1492db7..98f0995a 100644 --- a/chrome/browser/resources/chromeos/chromevox/common/msgs.js +++ b/chrome/browser/resources/chromeos/chromevox/common/msgs.js
@@ -75,7 +75,12 @@ if (!msgid) { throw new Error('Element has no msgid attribute: ' + elts[i]); } - elts[i].textContent = this.getMsg(msgid); + var val = this.getMsg(msgid); + if (elts[i].tagName == 'INPUT') { + elts[i].setAttribute('placeholder', val); + } else { + elts[i].textContent = val; + } elts[i].classList.add('i18n-processed'); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js index 39455296..bb137d1 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background.js
@@ -554,6 +554,9 @@ this.startExcursion(); (new PanelCommand(PanelCommandType.OPEN_MENUS)).send(); return false; + case 'toggleSearchWidget': + (new PanelCommand(PanelCommandType.SEARCH)).send(); + return false; case 'showKbExplorerPage': var explorerPage = {url: 'chromevox/background/kbexplorer.html'}; chrome.tabs.create(explorerPage); @@ -928,12 +931,23 @@ */ restoreCurrentRange_: function() { if (this.savedRange_) { - var containingWebView = this.savedRange_.start.node; + var node = this.savedRange_.start.node; + var containingWebView = node; while (containingWebView && containingWebView.role != RoleType.webView) containingWebView = containingWebView.parent; - if (containingWebView) - containingWebView.focus(); + if (containingWebView) { + // Focusing the webView causes a focus change event which steals focus + // away from the saved range. + var saved = this.savedRange_; + var setSavedRange = function(e) { + if (e.target.root == saved.start.node.root) + this.navigateToRange_(saved); + node.root.removeEventListener(EventType.focus, setSavedRange, true); + }.bind(this); + node.root.addEventListener(EventType.focus, setSavedRange, true); + containingWebView.focus(); + } this.navigateToRange_(this.savedRange_); this.savedRange_ = null; } @@ -953,6 +967,14 @@ this.inExcursion_ = false; this.restoreCurrentRange_(); }, + + /** + * Move ChromeVox back to the last saved range. + */ + saveExcursion: function() { + this.savedRange_ = + new cursors.Range(this.currentRange_.start, this.currentRange_.end); + }, }; /**
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js index 5512f38..2f85472 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors.js
@@ -13,6 +13,7 @@ goog.provide('cursors.Unit'); goog.require('AutomationUtil'); +goog.require('StringUtil'); goog.require('constants'); /**
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js new file mode 100644 index 0000000..b219420 --- /dev/null +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search.js
@@ -0,0 +1,225 @@ +// 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. + +/** + * @fileoverview Objects related to incremental search. + */ + +goog.provide('ISearch'); +goog.provide('ISearchHandler'); +goog.provide('ISearchUI'); + +goog.require('AutomationUtil'); +goog.require('ChromeVoxState'); +goog.require('Output'); +goog.require('constants'); +goog.require('cursors.Cursor'); + +goog.scope(function() { +var AutomationNode = chrome.automation.AutomationNode; +var Dir = constants.Dir; + +/** + * An interface implemented by objects that wish to handle events related to + * incremental search. + * @interface + */ +ISearchHandler = function() {}; + +ISearchHandler.prototype = { + /** + * Called when there are no remaining nodes in the document matching + * search. + * @param {!AutomationNode} boundaryNode The last node before reaching either + * the start or end of the document. + */ + onSearchReachedBoundary: function(boundaryNode) {}, + + /** + * Called when search result node changes. + * @param {!AutomationNode} node The new search result. + */ + onSearchResultChanged: function(node) {} +}; + +/** + * Controls an incremental search. + * @param {!AutomationNode} initialNode + * @constructor + */ +ISearch = function(initialNode) { + var leaf = AutomationUtil.findNodePre( + initialNode, Dir.FORWARD, AutomationPredicate.leaf) || initialNode; + + /** @type {!AutomationNode} @private */ + this.node_ = leaf; + + /** + * This tracks the id of a search that is in progress. + * @type {number} @private + */ + this.pendingSearchId_ = 0; + + // Global exports. + /** Exported for this background script. */ + cvox.ChromeVox = chrome.extension.getBackgroundPage()['cvox']['ChromeVox']; +}; + +ISearch.prototype = { + /** + * @param {!ISearchHandler} handler + */ + set handler(handler) { + this.handler_ = handler; + }, + + /** + * Performs a search. + * @param {string} searchStr + * @param {Dir} dir + */ + search: function(searchStr, dir) { + searchStr = searchStr.toLocaleLowerCase(); + // Keep things responsive by chunking cursor moves up into discrete + // blocks. We can, if needed, simulate getting interrupted by the enter key. + var currentSearchId = ++this.pendingSearchId_; + var move = function(curNode) { + var cur = cursors.Cursor.fromNode(curNode); + var prev = cur; + cur = + cur.move(cursors.Unit.DOM_NODE, cursors.Movement.DIRECTIONAL, dir); + if (prev.equals(cur)) { + this.handler_.onSearchReachedBoundary(this.node_); + return; + } + + if (cur.getText().toLocaleLowerCase().indexOf(searchStr) != -1) { + this.node_ = cur.node; + this.handler_.onSearchResultChanged(this.node_); + return; + } + if (this.pendingSearchId_ == currentSearchId) + window.setTimeout(move.bind(this, cur.node), 0); + }; + window.setTimeout(move.bind(this, this.node_), 0); + } +}; + +/** + * @param {Element} input + * @constructor + * @implements {ISearchHandler} + */ +ISearchUI = function(input) { + /** @type {ChromeVoxState} */ + this.background_ = + chrome.extension.getBackgroundPage()['global']['backgroundObj']; + this.iSearch_ = new ISearch(this.background_.currentRange.start.node); + this.input_ = input; + this.dir_ = Dir.FORWARD; + this.iSearch_.handler = this; + + this.onKeyDown = this.onKeyDown.bind(this); + this.onTextInput = this.onTextInput.bind(this); + + this.background_['startExcursion'](); + input.addEventListener('keydown', this.onKeyDown, true); + input.addEventListener('textInput', this.onTextInput, true); +}; + +/** + * @param {Element} input + * @return {ISearchUI} + */ +ISearchUI.get = function(input) { + if (ISearchUI.instance_) + ISearchUI.instance_.destroy(); + ISearchUI.instance_ = new ISearchUI(input); + input.focus(); + return ISearchUI.instance_; +}; + +ISearchUI.prototype = { + /** + * Listens to key down events. + * @param {Event} evt + * @return {boolean} + */ + onKeyDown: function(evt) { + switch (evt.keyIdentifier) { + case 'Up': + this.dir_ = Dir.BACKWARD; + break; + case 'Down': + this.dir_ = Dir.FORWARD; + break; + case 'U+001B': // Escape + this.pendingSearchId_ = 0; + this.background_['endExcursion'](); + Panel.closeMenusAndRestoreFocus(); + return false; + case 'Enter': + this.pendingSearchId_ = 0; + this.background_['saveExcursion'](); + Panel.closeMenusAndRestoreFocus(); + return false; + default: + this.pendingSearchId_ = 0; + return false; + } + this.iSearch_.search(this.input_.value, this.dir_); + evt.preventDefault(); + evt.stopPropagation(); + return false; + }, + + /** + * Listens to text input events. + * @param {Event} evt + * @return {boolean} + */ + onTextInput: function(evt) { + this.iSearch_.search(this.input_.value, this.dir_); + return true; + }, + + /** + * @override + */ + onSearchReachedBoundary: function(boundaryNode) { + this.output_(boundaryNode); + cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP); + }, + + /** + * @override + */ + onSearchResultChanged: function(node) { + this.output_(node); + }, + + /** + * @param {!AutomationNode} node + * @private + */ + output_: function(node) { + Output.flushNextSpeechUtterance(); + var o = new Output().withRichSpeechAndBraille( + cursors.Range.fromNode(node), null, Output.EventType.NAVIGATE).go(); + + this.background_.setCurrentRange(cursors.Range.fromNode(node)); + }, + + /** Unregisters event handlers. */ + destroy: function() { + this.iSearch_.handler_ = null; + this.iSearch_ = null; + var input = this.input_; + this.input_ = null; + input.removeEventListener('keydown', this.onKeyDown, true); + input.removeEventListener('textInput', this.onTextInput, true); + } +}; + +}); // goog.scope
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search_test.extjs new file mode 100644 index 0000000..fe4fe4b3 --- /dev/null +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/i_search_test.extjs
@@ -0,0 +1,96 @@ +// 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 test fixture. +GEN_INCLUDE(['../../testing/chromevox_next_e2e_test_base.js']); + +/** + * Test fixture for ISearch. + * @constructor + * @extends {ChromeVoxNextE2ETest} + */ +function ISearchTest() { + ChromeVoxNextE2ETest.call(this); +} + +ISearchTest.prototype = { + __proto__: ChromeVoxNextE2ETest.prototype, + + /** @override */ + runtimeDeps: ['ISearch', 'ISearchHandler'], + + linksAndHeadingsDoc: function() {/*! + <p>start</p> + <a href='#a'>Home</a> + <a href='#b'>About US</a> + <p> + <h1>Latest Breaking News</h1> + <a href='foo'>See more...</a> + </p> + <a href='#bar'>Questions?</a> + <h2>Privacy Policy</h2> + <p>end<span>of test</span></p> + */} +}; + +/** + * @implements {ISearchHandler} + * @constructor + */ +function FakeISearchHandler(testObj) { + this.test = testObj; + this.expect_ = []; +} + +FakeISearchHandler.prototype = { + /** @override */ + onSearchReachedBoundary: function(boundaryNode) { + this.expect_.shift()(boundaryNode, true); + }, + + onSearchResultChanged: function(node) { + this.expect_.shift()(node); + }, + + expect: function(str, opt_callback) { + this.expect_.push(this.test.newCallback(function(node, isBound) { + var actual = node.name || node.role; + if (isBound) + actual = 'boundary=' + actual; + assertEquals(str, actual); + opt_callback && opt_callback(); + })); + } +}; + +TEST_F('ISearchTest', 'Simple', function() { + this.runWithLoadedTree(this.linksAndHeadingsDoc, function(rootNode) { + var handler = new FakeISearchHandler(this); + var search = new ISearch(rootNode); + search.handler = handler; + + // Simple forward search. + search.search('US', 'forward'); + handler.expect('About US', + search.search.bind(search, 'start', 'backward')); + + handler.expect('start', + // Boundary (beginning). + search.search.bind(search, 'foo', 'backward')); + + handler.expect('boundary=start', + // Boundary (end). + search.search.bind(search, 'foo', 'forward')); + + // Search "focus" doesn't move. + handler.expect('boundary=start', + // Mixed case substring. + search.search.bind(search, 'bReak', 'forward')); + + handler.expect('Latest Breaking News', + search.search.bind(search, 'bReak', 'forward')); + + handler.expect('boundary=Latest Breaking News'); + }); +});
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js index fc1dd9f..abf4030 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output.js
@@ -16,7 +16,9 @@ goog.require('cursors.Range'); goog.require('cursors.Unit'); goog.require('cvox.AbstractEarcons'); +goog.require('cvox.ChromeVox'); goog.require('cvox.NavBraille'); +goog.require('cvox.TtsCategory'); goog.require('cvox.ValueSelectionSpan'); goog.require('cvox.ValueSpan'); goog.require('goog.i18n.MessageFormat');
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.html b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.html index 04e9f34..b21fde2 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.html +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.html
@@ -34,6 +34,9 @@ <div id="braille-text"></div> <div id="braille-cells"></div> </div> + <div id="search-container"> + <input class="i18n" msgid="search_widget_intro" id="search" type="search"></input> + </div> </div> <div id="options_close"> <div hidden id="options_title" class="i18n" msgid="options"></div>
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js index 1bf909b..8010c301 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel.js
@@ -8,6 +8,7 @@ goog.provide('Panel'); +goog.require('ISearchUI'); goog.require('Msgs'); goog.require('PanelCommand'); goog.require('PanelMenu'); @@ -160,6 +161,9 @@ case PanelCommandType.OPEN_MENUS: Panel.onOpenMenus(); break; + case PanelCommandType.SEARCH: + Panel.onSearch(); + break; } }; @@ -300,6 +304,16 @@ Panel.activateMenu(Panel.menus_[0]); }; +/** Open incremental search. */ +Panel.onSearch = function() { + Panel.clearMenus(); + Panel.pendingCallback_ = null; + + window.location = '#focus'; + + ISearchUI.get($('search')); +}; + /** * Clear any previous menus. The menus are all regenerated each time the * menus are opened.
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_command.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_command.js index 3e48a07..39b63e9 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_command.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/panel_command.js
@@ -46,4 +46,5 @@ OPEN_MENUS: 'open_menus', ENABLE_MENUS: 'enable_menus', DISABLE_MENUS: 'disable_menus', + SEARCH: 'search', };
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js b/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js index 94376942..b972aa0 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/tts_background.js
@@ -257,6 +257,8 @@ // any speech very well. Handle empty and whitespace only strings (including // non-breaking space) here to mitigate the issue somewhat. if (/^[\s\u00a0]*$/.test(textString)) { + queueMode = cvox.QueueMode.FLUSH; + // We still want to callback for listeners in our content script. if (properties['startCallback']) { try { @@ -270,9 +272,6 @@ } catch (e) { } } - if (queueMode === cvox.QueueMode.FLUSH) { - this.stop(); - } return this; }
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js index cb7443e2..14d7727 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js
@@ -15,12 +15,27 @@ */ function ChromeVoxNextE2ETest() { ChromeVoxE2ETest.call(this); + + if (this.runtimeDeps.length > 0) { + chrome.extension.getViews().forEach(function(w) { + this.runtimeDeps.forEach(function(dep) { + if (w[dep]) + window[dep] = w[dep]; + }.bind(this)); + }.bind(this)); + } } ChromeVoxNextE2ETest.prototype = { __proto__: ChromeVoxE2ETest.prototype, /** + * Dependencies defined on a background window other than this one. + * @type {!Array<string>} + */ + runtimeDeps: [], + + /** * Gets the desktop from the automation API and Launches a new tab with * the given document, and runs |callback| when a load complete fires. * Arranges to call |testDone()| after |callback| returns.
diff --git a/chrome/browser/resources/chromeos/network_ui/compiled_resources2.gyp b/chrome/browser/resources/chromeos/network_ui/compiled_resources2.gyp new file mode 100644 index 0000000..2f02c48d --- /dev/null +++ b/chrome/browser/resources/chromeos/network_ui/compiled_resources2.gyp
@@ -0,0 +1,18 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'network_ui', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_network_icon_externs', + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', + '<(EXTERNS_GYP):networking_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/history/compiled_resources.gyp b/chrome/browser/resources/history/compiled_resources.gyp deleted file mode 100644 index c52cd76a..0000000 --- a/chrome/browser/resources/history/compiled_resources.gyp +++ /dev/null
@@ -1,39 +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. -{ - 'targets': [ - { - 'target_name': 'history', - 'variables': { - 'depends': [ - '../../../../ui/webui/resources/js/action_link.js', - '../../../../ui/webui/resources/js/assert.js', - '../../../../ui/webui/resources/js/cr.js', - '../../../../ui/webui/resources/js/cr/ui.js', - '../../../../ui/webui/resources/js/cr/ui/alert_overlay.js', - '../../../../ui/webui/resources/js/cr/ui/command.js', - '../../../../ui/webui/resources/js/cr/ui/focus_grid.js', - '../../../../ui/webui/resources/js/cr/ui/focus_manager.js', - '../../../../ui/webui/resources/js/cr/ui/focus_outline_manager.js', - '../../../../ui/webui/resources/js/cr/ui/focus_row.js', - '../../../../ui/webui/resources/js/cr/ui/menu.js', - '../../../../ui/webui/resources/js/cr/ui/menu_button.js', - '../../../../ui/webui/resources/js/cr/ui/menu_item.js', - '../../../../ui/webui/resources/js/cr/ui/overlay.js', - '../../../../ui/webui/resources/js/cr/ui/position_util.js', - '../../../../ui/webui/resources/js/event_tracker.js', - '../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../ui/webui/resources/js/promise_resolver.js', - '../../../../ui/webui/resources/js/util.js', - 'history_focus_manager.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/chrome_send.js', - 'externs.js', - ], - }, - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - } - ], -}
diff --git a/chrome/browser/resources/history/compiled_resources2.gyp b/chrome/browser/resources/history/compiled_resources2.gyp new file mode 100644 index 0000000..6efe6a8 --- /dev/null +++ b/chrome/browser/resources/history/compiled_resources2.gyp
@@ -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. +{ + 'targets': [ + { + 'target_name': 'externs', + 'includes': ['../../../../third_party/closure_compiler/include_js.gypi'], + }, + { + 'target_name': 'history_focus_manager', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_manager', + ], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'history', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:action_link', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:event_tracker', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', + '<(DEPTH)/ui/webui/resources/js/cr/compiled_resources2.gyp:ui', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:alert_overlay', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:command', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_grid', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_outline_manager', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_row', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:menu', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:menu_button', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:menu_item', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:overlay', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:position_util', + 'history_focus_manager', + '<(EXTERNS_GYP):chrome_send', + 'externs', + ], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/history/history.js b/chrome/browser/resources/history/history.js index 71ecae4..e67c903 100644 --- a/chrome/browser/resources/history/history.js +++ b/chrome/browser/resources/history/history.js
@@ -368,7 +368,7 @@ Visit.prototype.addHighlightedText_ = function(node, content, highlightText) { var i = 0; if (highlightText) { - var re = new RegExp(Visit.pregQuote_(highlightText), 'gim'); + var re = new RegExp(quoteString(highlightText), 'gim'); var match; while (match = re.exec(content)) { if (match.index > i) @@ -536,18 +536,6 @@ e.preventDefault(); }; -// Visit, private, static: ---------------------------------------------------- - -/** - * Quote a string so it can be used in a regular expression. - * @param {string} str The source string. - * @return {string} The escaped string. - * @private - */ -Visit.pregQuote_ = function(str) { - return str.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, '\\$1'); -}; - /////////////////////////////////////////////////////////////////////////////// // HistoryModel:
diff --git a/chrome/browser/resources/md_downloads/compiled_resources.gyp b/chrome/browser/resources/md_downloads/compiled_resources.gyp deleted file mode 100644 index 9aa47ef..0000000 --- a/chrome/browser/resources/md_downloads/compiled_resources.gyp +++ /dev/null
@@ -1,42 +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. -{ - 'targets': [ - { - 'target_name': 'manager', - 'variables': { - 'depends': [ - '../../../../ui/webui/resources/cr_elements/cr_search_field/cr_search_field.js', - '../../../../ui/webui/resources/js/action_link.js', - '../../../../ui/webui/resources/js/assert.js', - '../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../ui/webui/resources/js/cr.js', - '../../../../ui/webui/resources/js/event_tracker.js', - '../../../../ui/webui/resources/js/cr/ui.js', - '../../../../ui/webui/resources/js/cr/ui/command.js', - '../../../../ui/webui/resources/js/promise_resolver.js', - '../../../../ui/webui/resources/js/util.js', - '../../../../third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-control-state-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/iron-list/iron-list-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/iron-resizable-behavior/iron-resizable-behavior-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/iron-scroll-target-behavior/iron-scroll-target-behavior-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-inky-focus-behavior-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior-extracted.js', - '../../../../third_party/polymer/v1_0/components-chromium/paper-ripple/paper-ripple-extracted.js', - 'action_service.js', - 'constants.js', - 'item.js', - 'toolbar.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/chrome_send.js', - 'externs.js', - ], - }, - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - } - ], -}
diff --git a/chrome/browser/resources/md_downloads/compiled_resources2.gyp b/chrome/browser/resources/md_downloads/compiled_resources2.gyp index 7b492d12..f4498cf 100644 --- a/chrome/browser/resources/md_downloads/compiled_resources2.gyp +++ b/chrome/browser/resources/md_downloads/compiled_resources2.gyp
@@ -19,7 +19,7 @@ }, { 'target_name': 'externs', - 'includes': ['../../../../third_party/closure_compiler/externs_js.gypi'], + 'includes': ['../../../../third_party/closure_compiler/include_js.gypi'], }, { 'target_name': 'item',
diff --git a/chrome/browser/resources/md_downloads/crisper.js b/chrome/browser/resources/md_downloads/crisper.js index 0c4f256ec..4c031524 100644 --- a/chrome/browser/resources/md_downloads/crisper.js +++ b/chrome/browser/resources/md_downloads/crisper.js
@@ -1061,25 +1061,6 @@ } /** - * Calls chrome.send with a callback and restores the original afterwards. - * @param {string} name The name of the message to send. - * @param {!Array} params The parameters to send. - * @param {string} callbackName The name of the function that the backend calls. - * @param {!Function} callback The function to call. - */ -function chromeSend(name, params, callbackName, callback) { - var old = global[callbackName]; - global[callbackName] = function() { - // restore - global[callbackName] = old; - - var args = Array.prototype.slice.call(arguments); - return callback.apply(global, args); - }; - chrome.send(name, params); -} - -/** * Returns the scale factors supported by this platform for webui * resources. * @return {Array} The supported scale factors.
diff --git a/chrome/browser/resources/md_downloads/downloads.html b/chrome/browser/resources/md_downloads/downloads.html index 750fc621..6b4f4e5 100644 --- a/chrome/browser/resources/md_downloads/downloads.html +++ b/chrome/browser/resources/md_downloads/downloads.html
@@ -3,8 +3,7 @@ <head> <meta charset="utf-8"> <title i18n-content="title"></title> - <link rel="stylesheet" href="chrome://resources/css/roboto.css"> - <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> <style> html { background: rgb(236, 239, 241); @@ -17,8 +16,6 @@ body { display: flex; - font-family: Roboto; - font-size: 81.25%; margin: 0; } </style>
diff --git a/chrome/browser/resources/md_downloads/vulcanize.py b/chrome/browser/resources/md_downloads/vulcanize.py index acb3a5d..3ef22dc 100755 --- a/chrome/browser/resources/md_downloads/vulcanize.py +++ b/chrome/browser/resources/md_downloads/vulcanize.py
@@ -41,6 +41,7 @@ '--exclude', 'load_time_data.js', '--exclude', 'strings.js', '--exclude', 'text_defaults.css', + '--exclude', 'text_defaults_md.css', '--inline-css', '--inline-scripts',
diff --git a/chrome/browser/resources/md_downloads/vulcanized.html b/chrome/browser/resources/md_downloads/vulcanized.html index 1aa9e4e67f..7010722 100644 --- a/chrome/browser/resources/md_downloads/vulcanized.html +++ b/chrome/browser/resources/md_downloads/vulcanized.html
@@ -25,37 +25,7 @@ --> <meta charset="utf-8"> <title i18n-content="title"></title> - <style> -/* 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. */ - -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 300; - src: local('Roboto Light'), local('Roboto-Light'), - url("chrome://resources/roboto/roboto-light.woff2") format('woff2'); -} - -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 400; - src: local('Roboto'), local('Roboto-Regular'), - url("chrome://resources/roboto/roboto-regular.woff2") format('woff2'); -} - -@font-face { - font-family: 'Roboto'; - font-style: normal; - font-weight: 500; - src: local('Roboto Medium'), local('Roboto-Medium'), - url("chrome://resources/roboto/roboto-medium.woff2") format('woff2'); -} - -</style> - <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> <style> html { background: rgb(236, 239, 241); @@ -68,8 +38,6 @@ body { display: flex; - font-family: Roboto; - font-size: 81.25%; margin: 0; } </style>
diff --git a/chrome/browser/resources/md_history/compiled_resources.gyp b/chrome/browser/resources/md_history/compiled_resources.gyp index 9bb654e..0714b040 100644 --- a/chrome/browser/resources/md_history/compiled_resources.gyp +++ b/chrome/browser/resources/md_history/compiled_resources.gyp
@@ -14,9 +14,9 @@ '../../../../third_party/polymer/v1_0/components-chromium/iron-list/iron-list-extracted.js', '../../../../third_party/polymer/v1_0/components-chromium/iron-resizable-behavior/iron-resizable-behavior-extracted.js', '../../../../third_party/polymer/v1_0/components-chromium/iron-scroll-target-behavior/iron-scroll-target-behavior-extracted.js', + '../../../../ui/webui/resources/cr_elements/cr_search_field/cr_search_field.js', + '../../../../ui/webui/resources/cr_elements/cr_shared_menu/compiled_resources.gyp:cr_shared_menu', '../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../ui/webui/resources/js/cr.js', - '../../../../ui/webui/resources/js/cr/ui/position_util.js', '../../../../ui/webui/resources/js/load_time_data.js', '../../../../ui/webui/resources/js/promise_resolver.js', '../../../../ui/webui/resources/js/util.js',
diff --git a/chrome/browser/resources/md_history/history.html b/chrome/browser/resources/md_history/history.html index 4cdb8056..182ac8f 100644 --- a/chrome/browser/resources/md_history/history.html +++ b/chrome/browser/resources/md_history/history.html
@@ -4,8 +4,7 @@ <meta charset="utf8"> <title i18n-content="title"></title> - <link rel="stylesheet" href="chrome://resources/css/roboto.css"> - <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> + <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> <style> html, @@ -18,8 +17,6 @@ background: #f2f2f2; display: flex; flex-direction: column; - font-family: Roboto; - font-size: 13px; } #toolbar {
diff --git a/chrome/browser/resources/md_history/history.js b/chrome/browser/resources/md_history/history.js index dc695a2..dff27c6 100644 --- a/chrome/browser/resources/md_history/history.js +++ b/chrome/browser/resources/md_history/history.js
@@ -50,21 +50,13 @@ chrome.send('removeVisits', toBeRemoved); }); -/** - * Listens for any keyboard presses which will close the overflow menu. - */ -window.addEventListener('keydown', function(e) { - // Escape button on keyboard - if (e.keyCode == 27) { - $('history-list').closeMenu(); - } -}); /** - * Resizing browser window will cause the overflow menu to close. + * When the search is changed refresh the results from the backend. */ -window.addEventListener('resize', function() { - $('history-list').closeMenu(); +window.addEventListener('search-changed', function(e) { + $('history-list').setLoading(); + chrome.send('queryHistory', [e.detail.search, 0, 0, 0, RESULTS_PER_PAGE]); }); // Chrome Callbacks------------------------------------------------------------- @@ -75,7 +67,7 @@ * @param {Array<HistoryEntry>} results A list of results. */ function historyResult(info, results) { - $('history-list').addNewResults(results); + $('history-list').addNewResults(results, info.term); if (info.finished) $('history-list').disableResultLoading(); }
diff --git a/chrome/browser/resources/md_history/history_item.html b/chrome/browser/resources/md_history/history_item.html index a011e449..efd7d9ed 100644 --- a/chrome/browser/resources/md_history/history_item.html +++ b/chrome/browser/resources/md_history/history_item.html
@@ -115,17 +115,17 @@ } </style> <div id="main-container"> - <div id="date-accessed" class="card-title">[[historyDate]]</div> + <div id="date-accessed" class="card-title"> + {{cardTitle_(numberOfItems, historyDate, searchTerm)}} + </div> <div id="item-container"> <paper-checkbox id="checkbox" on-tap="onCheckboxSelected_" checked="{{selected}}" disabled="[[selectionNotAllowed_()]]"> </paper-checkbox> - <span id="time-accessed">{{timeAccessed}}</span> + <span id="time-accessed">{{readableTimestamp}}</span> <div class="website-icon" id="icon"></div> <div id="title-and-domain"> - <a href$="{{websiteUrl}}" id="title" class="website-title"> - {{websiteTitle}} - </a> + <a href$="{{websiteUrl}}" id="title" class="website-title"></a> <span id="domain">{{websiteDomain}}</span> </div> <iron-icon icon="star" id="bookmark-star"></iron-icon>
diff --git a/chrome/browser/resources/md_history/history_item.js b/chrome/browser/resources/md_history/history_item.js index b6af296..1fc49eee 100644 --- a/chrome/browser/resources/md_history/history_item.js +++ b/chrome/browser/resources/md_history/history_item.js
@@ -12,7 +12,7 @@ value: '' }, - timeAccessed: { + readableTimestamp: { type: String, value: '' }, @@ -53,6 +53,12 @@ value: 0 }, + // Search term used to obtain this history-item. + searchTerm: { + type: String, + value: '', + }, + selected: { type: Boolean, value: false, @@ -74,9 +80,18 @@ hasTimeGap: { type: Boolean, value: false + }, + + numberOfItems: { + type: Number, + value: 0 } }, + observers: [ + 'setSearchedTextToBold_(websiteTitle, searchTerm)' + ], + /** * When a history-item is selected the toolbar is notified and increases * or decreases its count of selected items accordingly. @@ -103,19 +118,63 @@ * the history item and where the menu should appear. */ onMenuButtonTap_: function(e) { - var position = this.$['menu-button'].getBoundingClientRect(); - this.fire('toggle-menu', { - x: position.left, - y: position.top, - accessTime: this.timestamp + target: Polymer.dom(e).localTarget, }); // Stops the 'tap' event from closing the menu when it opens. e.stopPropagation(); }, + /** + * If the results shown are search results set the search term to be bold + * where it is displayed in the history-item title. + * @private + */ + setSearchedTextToBold_: function() { + var i = 0; + var title = this.$.title; + + if (this.searchTerm == '' || this.searchTerm == null) { + title.textContent = this.websiteTitle; + return; + } + + var re = new RegExp(quoteString(this.searchTerm), 'gim'); + var match; + title.textContent = ''; + while (match = re.exec(this.websiteTitle)) { + if (match.index > i) + title.appendChild(document.createTextNode( + this.websiteTitle.slice(i, match.index))); + i = re.lastIndex; + // Mark the highlighted text in bold. + var b = document.createElement('b'); + b.textContent = this.websiteTitle.substring(match.index, i); + title.appendChild(b); + } + if (i < this.websiteTitle.length) + title.appendChild(document.createTextNode(this.websiteTitle.slice(i))); + }, + selectionNotAllowed_: function() { return !loadTimeData.getBoolean('allowDeletingHistory'); + }, + + /** + * Generates the title for this history card. + * @param {number} numberOfItems The number of items in the card. + * @param {string} search The search term associated with these results. + * @private + */ + cardTitle_: function(numberOfItems, historyDate, search) { + var resultId = numberOfItems == 1 ? 'searchResult' : 'searchResults'; + + if (search) { + return loadTimeData.getStringF('foundSearchResults', numberOfItems, + loadTimeData.getString(resultId), search); + } else { + return historyDate; + } } });
diff --git a/chrome/browser/resources/md_history/history_list.html b/chrome/browser/resources/md_history/history_list.html index fdb1b1b..8bba131d 100644 --- a/chrome/browser/resources/md_history/history_list.html +++ b/chrome/browser/resources/md_history/history_list.html
@@ -1,31 +1,19 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-list/iron-list.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-item/paper-item.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-menu/paper-menu.html"> -<link rel="import" href="chrome://resources/html/cr/ui/position_util.html"> +<link rel="import" href="chrome://resources/cr_elements/cr_shared_menu/cr_shared_menu.html"> <link rel="import" href="chrome://history/history_item.html"> +<link rel="import" href="chrome://history/shared_style.html"> <dom-module id="history-list"> <template> + <style include="shared-style"></style> <style> :host { display: flex; flex-direction: column; } - #overflow-menu { - @apply(--shadow-elevation-2dp); - border-radius: 2px; - display: none; - left: 0; - position: absolute; - top: 0; - } - - :host([menu-open]) #overflow-menu { - display: block; - } - #infinite-list { flex: 1; padding: 20px 0 0 0; @@ -41,30 +29,37 @@ background: #eaeaea; } </style> + <div id="no-results" class="centered-message" + hidden$="{{hasResults(historyData.length)}}"> + {{noResultsMessage_(searchTerm, loading_)}} + </div> <iron-list items="{{historyData}}" as="historyDay" id="infinite-list" - on-scroll="scrollHandler_"> + on-scroll="scrollHandler_" + hidden$="{{!hasResults(historyData.length)}}"> <template> <history-item history-date="[[historyDay.dateRelativeDay]]" website-title="[[historyDay.title]]" website-url="[[historyDay.url]]" website-domain="[[historyDay.domain]]" - time-accessed="[[historyDay.dateTimeOfDay]]" + readable-timestamp="[[historyDay.readableTimestamp]]" starred="[[historyDay.starred]]" timestamp="[[historyDay.time]]" selected="{{historyDay.selected}}" is-card-start="[[historyDay.isFirstItem]]" is-card-end="[[historyDay.isLastItem]]" - has-time-gap="[[historyDay.needsTimeGap]]"> + has-time-gap="[[historyDay.needsTimeGap]]" + search-term="[[searchTerm]]" + number-of-items="[[historyData.length]]"> </history-item> </template> </iron-list> - <paper-menu id="overflow-menu"> + <cr-shared-menu id="sharedMenu"> <paper-item i18n-content="moreFromSite" on-tap="onMoreFromSiteTap_"> </paper-item> <paper-item i18n-content="removeFromHistory" on-tap="onRemoveFromHistoryTap_"> </paper-item> - </paper-menu> + </cr-shared-menu> </template> <script src="chrome://history/history_list.js"></script> </dom-module>
diff --git a/chrome/browser/resources/md_history/history_list.js b/chrome/browser/resources/md_history/history_list.js index 9375739..76caf44 100644 --- a/chrome/browser/resources/md_history/history_list.js +++ b/chrome/browser/resources/md_history/history_list.js
@@ -18,36 +18,42 @@ value: 0 }, - menuOpen: { - type: Boolean, - value: false, - reflectToAttribute: true + searchTerm: { + type: String, + value: '' }, - menuIdentifier: { - type: Number, - value: 0 + // True if there is a pending request to the backend. + loading_: { + type: Boolean, + value: true }, resultLoadingDisabled_: { type: Boolean, value: false - } + }, }, - /** @const @private */ - X_OFFSET_: 30, - listeners: { - 'tap': 'closeMenu', - 'toggle-menu': 'toggleMenu_' + 'infinite-list.scroll': 'closeMenu_', + 'tap': 'closeMenu_', + 'toggle-menu': 'toggleMenu_', }, /** * Closes the overflow menu. + * @private */ - closeMenu: function() { - this.menuOpen = false; + closeMenu_: function() { + this.$.sharedMenu.closeMenu(); + }, + + /** + * Mark the page as currently loading new data from the back-end. + */ + setLoading: function() { + this.loading_ = true; }, /** @@ -57,20 +63,7 @@ * @private */ toggleMenu_: function(e) { - var menu = this.$['overflow-menu']; - - // Menu closes if the same button is clicked. - if (this.menuOpen && this.menuIdentifier == e.detail.accessTime) { - this.closeMenu(); - } else { - this.menuOpen = true; - this.menuIdentifier = e.detail.accessTime; - - cr.ui.positionPopupAtPoint(e.detail.x + this.X_OFFSET_, e.detail.y, menu, - cr.ui.AnchorType.BEFORE); - - menu.focus(); - } + this.$.sharedMenu.toggleMenu(e.detail.target); }, /** @@ -85,9 +78,17 @@ * for each result. * @param {!Array<!HistoryEntry>} historyResults The new history results. */ - addNewResults: function(historyResults) { - if (historyResults.length == 0) + addNewResults: function(historyResults, searchTerm) { + this.loading_ = false; + + if (this.searchTerm != searchTerm) { + this.splice('historyData', 0, this.historyData.length); + this.searchTerm = searchTerm; + } + + if (historyResults.length == 0) { return; + } // Creates a copy of historyResults to prevent accidentally modifying this // field. @@ -110,6 +111,8 @@ results[i].isLastItem = false; results[i].isFirstItem = false; results[i].needsTimeGap = this.needsTimeGap_(results, i); + results[i].readableTimestamp = + searchTerm == '' ? results[i].dateTimeOfDay : results[i].dateShort; if (results[i].dateRelativeDay != currentDate) { results[i - 1].isLastItem = true; @@ -221,9 +224,6 @@ * @private */ scrollHandler_: function() { - // Close overflow menu on scroll. - this.closeMenu(); - if (this.resultLoadingDisabled_) return; @@ -232,10 +232,11 @@ var scrollOffset = 10; var scrollElem = this.$['infinite-list']; - if (scrollElem.scrollHeight <= + if (!this.loading_ && scrollElem.scrollHeight <= scrollElem.scrollTop + scrollElem.clientHeight + scrollOffset) { + this.loading_ = true; chrome.send('queryHistory', - ['', 0, 0, this.lastVisitedTime, RESULTS_PER_PAGE]); + [this.searchTerm, 0, 0, this.lastVisitedTime, RESULTS_PER_PAGE]); } }, @@ -248,13 +249,29 @@ * @private */ needsTimeGap_: function(results, index) { + // TODO(tsergeant): Allow the final item from one batch of results to have a + // timegap once more results are added. + if (index == results.length - 1) + return false; + var currentItem = results[index]; var nextItem = results[index + 1]; - if (index + 1 >= results.length) - return false; + if (this.searchTerm) + return currentItem.dateShort != nextItem.dateShort; return currentItem.time - nextItem.time > BROWSING_GAP_TIME && - currentItem.dateRelativeDay == nextItem.dateRelativeDay; + currentItem.dateRelativeDay == nextItem.dateRelativeDay; + }, + + hasResults: function(historyDataLength) { + return historyDataLength > 0; + }, + + noResultsMessage_: function(searchTerm, isLoading) { + if (isLoading) + return ''; + var messageId = searchTerm !== '' ? 'noSearchResults' : 'noResults'; + return loadTimeData.getString(messageId); } });
diff --git a/chrome/browser/resources/md_history/history_toolbar.html b/chrome/browser/resources/md_history/history_toolbar.html index b32fc84..139d18f 100644 --- a/chrome/browser/resources/md_history/history_toolbar.html +++ b/chrome/browser/resources/md_history/history_toolbar.html
@@ -77,10 +77,6 @@ #back-padding { flex: 1 1 0; } - - [hidden] { - display: none !important; - } </style> <div id="toolbar-container">
diff --git a/chrome/browser/resources/md_history/history_toolbar.js b/chrome/browser/resources/md_history/history_toolbar.js index 26c04af..dd3beb3b 100644 --- a/chrome/browser/resources/md_history/history_toolbar.js +++ b/chrome/browser/resources/md_history/history_toolbar.js
@@ -11,12 +11,20 @@ value: 0, observer: 'changeToolbarView_' }, + // True if 1 or more history items are selected. When this value changes // the background colour changes. itemsSelected_: { type: Boolean, value: false, reflectToAttribute: true + }, + + // The most recent term entered in the search field. Updated incrementally + // as the user types. + searchTerm: { + type: String, + value: '' } }, @@ -29,6 +37,22 @@ this.itemsSelected_ = this.count > 0; }, + /** + * If the search term has changed reload for the new search. + */ + onSearch: function(searchTerm) { + if (searchTerm != this.searchTerm) + this.fire('search-changed', {search: searchTerm}); + this.searchTerm = searchTerm; + }, + + attached: function() { + this.async(function() { + this.searchFieldDelegate_ = new ToolbarSearchFieldDelegate(this); + this.$['search-input'].setDelegate(this.searchFieldDelegate_); + }); + }, + onClearSelectionTap_: function() { this.fire('unselect-all'); }, @@ -57,3 +81,19 @@ return count > 0 ? loadTimeData.getStringF('itemsSelected', count) : ''; } }); + +/** + * @constructor + * @implements {SearchFieldDelegate} + * @param {!Object} toolbar This history-toolbar. + */ +function ToolbarSearchFieldDelegate(toolbar) { + this.toolbar_ = toolbar; +} + +ToolbarSearchFieldDelegate.prototype = { + /** @override */ + onSearchTermSearch: function(searchTerm) { + this.toolbar_.onSearch(searchTerm); + } +};
diff --git a/chrome/browser/resources/md_history/shared_style.html b/chrome/browser/resources/md_history/shared_style.html index c55e2bb..163e8c6 100644 --- a/chrome/browser/resources/md_history/shared_style.html +++ b/chrome/browser/resources/md_history/shared_style.html
@@ -7,6 +7,10 @@ --card-min-width: 500px; } + [hidden] { + display: none !important; + } + .card-title { @apply(--layout-center); @apply(--layout-horizontal); @@ -20,6 +24,16 @@ height: 48px; } + .centered-message { + align-items: center; + color: #b4b4b4; + display: flex; + flex: 1; + font-size: 14px; + font-weight: 500; + justify-content: center; + } + .website-icon { -webkit-margin-end: 16px; height: 16px;
diff --git a/chrome/browser/resources/print_preview/print_preview.html b/chrome/browser/resources/print_preview/print_preview.html index bbcb5a1..6294da7 100644 --- a/chrome/browser/resources/print_preview/print_preview.html +++ b/chrome/browser/resources/print_preview/print_preview.html
@@ -39,6 +39,7 @@ <link rel="stylesheet" href="search/provisional_destination_resolver.css"> <script src="chrome://resources/js/action_link.js"></script> + <script src="chrome://resources/js/promise_resolver.js"></script> <script src="chrome://resources/js/cr.js"></script> <script src="chrome://resources/js/cr/event_target.js"></script> <script src="chrome://resources/js/cr/ui.js"></script>
diff --git a/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js b/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js index a78732f..b16e474 100644 --- a/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js +++ b/chrome/browser/resources/print_preview/search/provisional_destination_resolver.js
@@ -15,41 +15,6 @@ }; /** - * Utility class for bundling a promise object with it's resolver methods. - * @param {!Promise<!print_preview.Destination>} promise A promise returning - * a destination. - * @param {function(!print_preview.Destination)} resolve Function resolving - * the promise. - * @param {function()} reject Function for rejecting the promise. - * @constructor @struct - */ - function PromiseResolver(promise, resolve, reject) { - /** @type {!Promise<!print_preview.Destination>} */ - this.promise = promise; - /** @type {function(!print_preview.Destination)} */ - this.resolve = resolve; - /** @type {function()} */ - this.reject = reject; - } - - /** - * Create a Promise and an associated PromiseResolver. - * @return {!PromiseResolver} - */ - PromiseResolver.create = function() { - var reject = null; - var resolve = null; - /** @type {!Promise<!print_preview.Destination>} */ - var promise = new Promise(function(resolvePromise, rejectPromise) { - resolve = /** @type {function(!print_preview.Destination)}*/( - resolvePromise); - reject = /** @type {function()} */(rejectPromise); - }); - - return new PromiseResolver(promise, resolve, reject); - }; - - /** * Overlay used to resolve a provisional extension destination. The user is * prompted to allow print preview to grant a USB device access to an * extension associated with the destination. If user agrees destination @@ -78,7 +43,7 @@ /** * Promise resolver for promise returned by {@code this.run}. - * @private {?PromiseResolver} + * @private {?PromiseResolver<!print_preview.Destination>} */ this.promiseResolver_ = null; } @@ -126,7 +91,7 @@ 'Showing overlay while not in initial state.'); assert(!this.promiseResolver_, 'Promise resolver already set.'); this.setState_(ResolverState.ACTIVE); - this.promiseResolver_ = PromiseResolver.create(); + this.promiseResolver_ = new PromiseResolver(); this.getChildElement('.default').focus(); } else if (this.state_ != ResolverState.DONE) { assert(this.state_ != ResolverState.INITIAL, 'Hiding in initial state');
diff --git a/chrome/browser/resources/settings/advanced_page/compiled_resources.gyp b/chrome/browser/resources/settings/advanced_page/compiled_resources.gyp deleted file mode 100644 index 0df7cd54..0000000 --- a/chrome/browser/resources/settings/advanced_page/compiled_resources.gyp +++ /dev/null
@@ -1,20 +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. -{ - 'targets': [ - { - 'target_name': 'advanced_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - '../settings_page/compiled_resources.gyp:settings_page_visibility', - '../site_settings/constants.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/advanced_page/compiled_resources2.gyp b/chrome/browser/resources/settings/advanced_page/compiled_resources2.gyp new file mode 100644 index 0000000..f944f0e --- /dev/null +++ b/chrome/browser/resources/settings/advanced_page/compiled_resources2.gyp
@@ -0,0 +1,15 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'advanced_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '../settings_page/compiled_resources2.gyp:settings_page_visibility', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/appearance_page/compiled_resources.gyp b/chrome/browser/resources/settings/appearance_page/compiled_resources.gyp deleted file mode 100644 index 5e8fff6..0000000 --- a/chrome/browser/resources/settings/appearance_page/compiled_resources.gyp +++ /dev/null
@@ -1,59 +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. -{ - 'targets': [ - { - 'target_name': 'appearance_fonts_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/cr.js', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - '../../../../../ui/webui/resources/js/promise_resolver.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-a11y-keys-behavior/iron-a11y-keys-behavior-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-button-state-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-behaviors/iron-control-state-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-form-element-behavior/iron-form-element-behavior-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-range-behavior/iron-range-behavior-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-inky-focus-behavior-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/paper-behaviors/paper-ripple-behavior-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/paper-ripple/paper-ripple-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/paper-slider/paper-slider-extracted.js', - '../controls/pref_control_behavior.js', - '../controls/settings_dropdown_menu.js', - '../prefs/pref_util.js', - '../prefs/prefs_types.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'appearance_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/cr.js', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - '../../../../../ui/webui/resources/js/promise_resolver.js', - '../controls/pref_control_behavior.js', - '../controls/settings_dropdown_menu.js', - '../prefs/pref_util.js', - '../prefs/prefs_types.js', - '../settings_page/settings_animated_pages.js' - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - '../../../../../third_party/closure_compiler/externs/chrome_send.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/appearance_page/compiled_resources2.gyp b/chrome/browser/resources/settings/appearance_page/compiled_resources2.gyp new file mode 100644 index 0000000..bbdd4eb --- /dev/null +++ b/chrome/browser/resources/settings/appearance_page/compiled_resources2.gyp
@@ -0,0 +1,29 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'appearance_fonts_page', + 'dependencies': [ + '<(DEPTH)/third_party/polymer/v1_0/components-chromium/paper-slider/compiled_resources2.gyp:paper-slider-extracted', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):chrome_send', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'appearance_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):settings_private', + '<(EXTERNS_GYP):chrome_send', + '../controls/compiled_resources2.gyp:settings_dropdown_menu', + '../settings_page/compiled_resources2.gyp:settings_animated_pages' + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/basic_page/compiled_resources.gyp b/chrome/browser/resources/settings/basic_page/compiled_resources.gyp deleted file mode 100644 index 555eba594..0000000 --- a/chrome/browser/resources/settings/basic_page/compiled_resources.gyp +++ /dev/null
@@ -1,18 +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. -{ - 'targets': [ - { - 'target_name': 'basic_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - '../settings_page/compiled_resources.gyp:settings_page_visibility', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp b/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp new file mode 100644 index 0000000..6c0c9d8 --- /dev/null +++ b/chrome/browser/resources/settings/basic_page/compiled_resources2.gyp
@@ -0,0 +1,16 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'basic_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '../settings_page/compiled_resources2.gyp:settings_page_visibility', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/bluetooth_page/compiled_resources.gyp b/chrome/browser/resources/settings/bluetooth_page/compiled_resources.gyp deleted file mode 100644 index 1703205..0000000 --- a/chrome/browser/resources/settings/bluetooth_page/compiled_resources.gyp +++ /dev/null
@@ -1,72 +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. -{ - 'targets': [ - { - 'target_name': 'bluetooth_page', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/bluetooth_interface.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private_interface.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - '../settings_page/settings_animated_pages.js' - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/bluetooth.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'bluetooth_device_list_item', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/bluetooth.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'bluetooth_add_device_dialog', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/bluetooth_interface.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private_interface.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/bluetooth.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'bluetooth_pair_device_dialog', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/bluetooth_interface.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private_interface.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/bluetooth.js', - '../../../../../third_party/closure_compiler/externs/bluetooth_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp b/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp new file mode 100644 index 0000000..3cbd2217 --- /dev/null +++ b/chrome/browser/resources/settings/bluetooth_page/compiled_resources2.gyp
@@ -0,0 +1,43 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'bluetooth_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '<(EXTERNS_GYP):bluetooth', + '<(EXTERNS_GYP):bluetooth_private', + '<(INTERFACES_GYP):bluetooth_interface', + '<(INTERFACES_GYP):bluetooth_private_interface', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'bluetooth_device_list_item', + 'dependencies': [ + '<(EXTERNS_GYP):bluetooth', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'bluetooth_add_device_dialog', + 'dependencies': [ + '<(EXTERNS_GYP):bluetooth', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'bluetooth_pair_device_dialog', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '<(EXTERNS_GYP):bluetooth', + '<(EXTERNS_GYP):bluetooth_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/compiled_resources.gyp b/chrome/browser/resources/settings/compiled_resources.gyp deleted file mode 100644 index 9b0acc4d..0000000 --- a/chrome/browser/resources/settings/compiled_resources.gyp +++ /dev/null
@@ -1,26 +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. -{ - 'targets': [ - { - 'target_name': 'settings_resources', - 'type': 'none', - 'dependencies': [ - 'advanced_page/compiled_resources.gyp:*', - 'appearance_page/compiled_resources.gyp:*', - 'basic_page/compiled_resources.gyp:*', - 'bluetooth_page/compiled_resources.gyp:*', - 'controls/compiled_resources.gyp:*', - 'internet_page/compiled_resources.gyp:*', - 'languages_page/compiled_resources.gyp:*', - 'on_startup_page/compiled_resources.gyp:*', - 'passwords_and_forms_page/compiled_resources.gyp:*', - 'prefs/compiled_resources.gyp:*', - 'settings_page/compiled_resources.gyp:*', - 'site_settings/compiled_resources.gyp:*', - 'site_settings_page/compiled_resources.gyp:*', - ], - }, - ] -}
diff --git a/chrome/browser/resources/settings/compiled_resources2.gyp b/chrome/browser/resources/settings/compiled_resources2.gyp index 81f537bfaa..0fa9872 100644 --- a/chrome/browser/resources/settings/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/compiled_resources2.gyp
@@ -7,10 +7,22 @@ 'target_name': 'settings_resources', 'type': 'none', 'dependencies': [ + 'advanced_page/compiled_resources2.gyp:*', + 'appearance_page/compiled_resources2.gyp:*', + 'basic_page/compiled_resources2.gyp:*', + 'bluetooth_page/compiled_resources2.gyp:*', + 'controls/compiled_resources2.gyp:*', 'device_page/compiled_resources2.gyp:*', + 'internet_page/compiled_resources2.gyp:*', + 'languages_page/compiled_resources2.gyp:*', + 'on_startup_page/compiled_resources2.gyp:*', + 'passwords_and_forms_page/compiled_resources2.gyp:*', 'people_page/compiled_resources2.gyp:*', + 'prefs/compiled_resources2.gyp:*', 'reset_page/compiled_resources2.gyp:*', 'settings_page/compiled_resources2.gyp:*', + 'site_settings/compiled_resources2.gyp:*', + 'site_settings_page/compiled_resources2.gyp:*', ], }, {
diff --git a/chrome/browser/resources/settings/controls/compiled_resources.gyp b/chrome/browser/resources/settings/controls/compiled_resources.gyp deleted file mode 100644 index 15c2b52..0000000 --- a/chrome/browser/resources/settings/controls/compiled_resources.gyp +++ /dev/null
@@ -1,84 +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. -{ - 'targets': [ - { - 'target_name': 'settings_checkbox', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_indicator_behavior.js', - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_pref_behavior.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_types.js', - 'pref_control_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'settings_dropdown_menu', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../../ui/webui/resources/js/i18n_behavior.js', - '../prefs/pref_util.js', - '../prefs/prefs_types.js', - 'pref_control_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'settings_input', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_indicator_behavior.js', - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_pref_behavior.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_types.js', - 'pref_control_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'settings_radio_group', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../prefs/pref_util.js', - '../prefs/prefs_types.js', - 'pref_control_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'pref_control_behavior', - 'variables': { - 'depends': [ - '../prefs/prefs_types.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/controls/compiled_resources2.gyp b/chrome/browser/resources/settings/controls/compiled_resources2.gyp new file mode 100644 index 0000000..962857a --- /dev/null +++ b/chrome/browser/resources/settings/controls/compiled_resources2.gyp
@@ -0,0 +1,62 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'pref_control_behavior', + 'dependencies': [ + '../prefs/compiled_resources2.gyp:prefs_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'settings_checkbox', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_indicator_behavior', + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_pref_behavior', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):settings_private', + 'pref_control_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'settings_dropdown_menu', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:i18n_behavior', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:pref_util', + 'pref_control_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'settings_input', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_indicator_behavior', + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_pref_behavior', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):settings_private', + 'pref_control_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'settings_radio_group', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:pref_util', + 'pref_control_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/internet_page/compiled_resources.gyp b/chrome/browser/resources/settings/internet_page/compiled_resources.gyp deleted file mode 100644 index 0b3580a4..0000000 --- a/chrome/browser/resources/settings/internet_page/compiled_resources.gyp +++ /dev/null
@@ -1,190 +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. -{ - 'targets': [ - { - 'target_name': 'internet_page', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/networking_private_interface.js', - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../settings_page/settings_animated_pages.js' - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'internet_detail_page', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/networking_private_interface.js', - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_network_behavior.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'internet_known_networks_page', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/networking_private_interface.js', - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_apnlist', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_ip_config', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_nameservers', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_property_list', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_network_behavior.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_proxy', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/cr_elements/policy/cr_policy_network_behavior.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_proxy_input', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_proxy_exclusions', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_siminfo', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/networking_private_interface.js', - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_summary', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/networking_private_interface.js', - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'network_summary_item', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/network/cr_onc_types.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp b/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp new file mode 100644 index 0000000..f18ca8a --- /dev/null +++ b/chrome/browser/resources/settings/internet_page/compiled_resources2.gyp
@@ -0,0 +1,111 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'internet_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(INTERFACES_GYP):networking_private_interface', + '../settings_page/compiled_resources2.gyp:settings_animated_pages', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'internet_detail_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_network_behavior', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(EXTERNS_GYP):networking_private', + '<(INTERFACES_GYP):networking_private_interface', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'internet_known_networks_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(EXTERNS_GYP):networking_private', + '<(INTERFACES_GYP):networking_private_interface', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_apnlist', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_ip_config', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_nameservers', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_property_list', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_network_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_proxy', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_network_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_proxy_input', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_proxy_exclusions', + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_siminfo', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(INTERFACES_GYP):networking_private_interface', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_summary', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(INTERFACES_GYP):networking_private_interface', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'network_summary_item', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/network/compiled_resources2.gyp:cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/languages_page/compiled_resources.gyp b/chrome/browser/resources/settings/languages_page/compiled_resources.gyp deleted file mode 100644 index 67b25d33..0000000 --- a/chrome/browser/resources/settings/languages_page/compiled_resources.gyp +++ /dev/null
@@ -1,75 +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. -{ - 'targets': [ - { - 'target_name': 'languages', - 'variables': { - 'depends': [ - '../prefs/prefs_types.js', - '../prefs/compiled_resources.gyp:prefs', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - 'languages_types.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/chrome_send.js', - '<(EXTERNS_DIR)/language_settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'language_detail_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/cr_elements/policy/compiled_resources.gyp:cr_policy_indicator_behavior', - '../../../../../ui/webui/resources/js/chromeos/compiled_resources.gyp:ui_account_tweaks', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/compiled_resources.gyp:prefs', - 'languages_types.js', - 'languages.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/language_settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'languages_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../settings_page/settings_animated_pages.js', - '../prefs/prefs_types.js', - '../prefs/compiled_resources.gyp:prefs', - 'languages_types.js', - 'languages.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/language_settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'manage_languages_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../prefs/compiled_resources.gyp:prefs', - 'languages_types.js', - 'languages.js', - ], - 'externs': [ - '<(EXTERNS_DIR)/language_settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp b/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp new file mode 100644 index 0000000..f98b21a --- /dev/null +++ b/chrome/browser/resources/settings/languages_page/compiled_resources2.gyp
@@ -0,0 +1,59 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'languages', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):chrome_send', + '<(EXTERNS_GYP):language_settings_private', + '../prefs/compiled_resources2.gyp:prefs_types', + '../prefs/compiled_resources2.gyp:prefs', + 'languages_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'language_detail_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp:cr_policy_indicator_behavior', + '<(DEPTH)/ui/webui/resources/js/chromeos/compiled_resources2.gyp:ui_account_tweaks', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):chrome_send', + 'languages_types', + 'languages', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'languages_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '../settings_page/compiled_resources2.gyp:settings_animated_pages', + 'languages_types', + 'languages', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'languages_types', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(EXTERNS_GYP):language_settings_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'manage_languages_page', + 'dependencies': [ + 'languages_types', + 'languages', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/on_startup_page/compiled_resources.gyp b/chrome/browser/resources/settings/on_startup_page/compiled_resources.gyp deleted file mode 100644 index b769ce8..0000000 --- a/chrome/browser/resources/settings/on_startup_page/compiled_resources.gyp +++ /dev/null
@@ -1,35 +0,0 @@ -# Copyright 2015 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -{ - 'targets': [ - { - 'target_name': 'on_startup_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../settings_page/settings_animated_pages.js' - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'startup_urls_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp b/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp new file mode 100644 index 0000000..041ab640 --- /dev/null +++ b/chrome/browser/resources/settings/on_startup_page/compiled_resources2.gyp
@@ -0,0 +1,19 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'on_startup_page', + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'startup_urls_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html b/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html index de5cdfa..f874136 100644 --- a/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html +++ b/chrome/browser/resources/settings/on_startup_page/startup_urls_page.html
@@ -1,13 +1,11 @@ <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog/paper-dialog.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html"> -<link rel="import" href="chrome://md-settings/settings_dialog_css.html"> +<link rel="import" href="chrome://md-settings/settings_dialog.html"> <link rel="import" href="chrome://md-settings/settings_shared_css.html"> <dom-module id="settings-startup-urls-page"> <link rel="import" type="css" href="on_startup_shared.css"> <template> - <style include="settings-dialog"></style> <style include="settings-shared"></style> <div class="list-frame vertical-list"> <template is="dom-repeat" items="[[startupPages_]]"> @@ -29,32 +27,23 @@ </div> </div> - <paper-dialog modal id="addUrlDialog" class="layout vertical"> - <div id="dialog-content"> - <div class="top-row"> - <div class="title" i18n-content="onStartupAddNewPage"></div> - <paper-icon-button icon="clear" on-tap="onCancelTap_" id="close"> - </paper-icon-button> - </div> - <div class="body"> - <div class="explanation"> - <paper-input class="flex" always-float-label - i18n-values="label:onStartupSiteUrl" value="{{newUrl_}}"> - </paper-input> - </div> - <div class="button-container"> - <div class="action-buttons"> - <paper-button class="cancel-button" on-tap="onCancelTap_" - id="cancel" i18n-content="cancel"></paper-button> - <paper-button class="action-button" on-tap="onAddTap_" - i18n-content="add" disabled="[[!isAddEnabled_(newUrl_)]]"> - </paper-button> - </div> - </div> + <settings-dialog id="addUrlDialog"> + <div class="title" i18n-content="onStartupAddNewPage"></div> + <div class="body"> + <paper-input class="flex" always-float-label + i18n-values="label:onStartupSiteUrl" value="{{newUrl_}}"> + </paper-input> + </div> + <div class="button-container"> + <div class="action-buttons"> + <paper-button class="cancel-button" on-tap="onCancelTap_" + id="cancel" i18n-content="cancel"></paper-button> + <paper-button class="action-button" on-tap="onAddTap_" + i18n-content="add" disabled="[[!isAddEnabled_(newUrl_)]]"> + </paper-button> </div> </div> - </paper-dialog> - + </settings-dialog> </template> <script src="startup_urls_page.js"></script> </dom-module>
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources.gyp b/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources.gyp deleted file mode 100644 index b2a4d4c..0000000 --- a/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources.gyp +++ /dev/null
@@ -1,28 +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. -{ - 'targets': [ - { - 'target_name': 'passwords_and_forms_page', - 'variables': { - 'depends': [ - 'compiled_resources.gyp:passwords_section', - '../../../../../third_party/closure_compiler/externs/compiled_resources.gyp:passwords_private', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'passwords_section', - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/compiled_resources.gyp:passwords_private', - ], - }, - }, - ], -}
diff --git a/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp b/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp new file mode 100644 index 0000000..8ccbdec --- /dev/null +++ b/chrome/browser/resources/settings/passwords_and_forms_page/compiled_resources2.gyp
@@ -0,0 +1,24 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'passwords_and_forms_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):passwords_private', + 'passwords_section', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'passwords_section', + 'dependencies': [ + '<(EXTERNS_GYP):passwords_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/people_page/compiled_resources2.gyp b/chrome/browser/resources/settings/people_page/compiled_resources2.gyp index 739785f..dd58217 100644 --- a/chrome/browser/resources/settings/people_page/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/people_page/compiled_resources2.gyp
@@ -1,4 +1,4 @@ -# Copyright 2015 The Chromium Authors. All rights reserved. +# 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. {
diff --git a/chrome/browser/resources/settings/prefs/compiled_resources.gyp b/chrome/browser/resources/settings/prefs/compiled_resources.gyp deleted file mode 100644 index 0738e33..0000000 --- a/chrome/browser/resources/settings/prefs/compiled_resources.gyp +++ /dev/null
@@ -1,24 +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. -{ - 'targets': [ - { - 'target_name': 'prefs', - 'variables': { - 'depends': [ - '../../../../../third_party/closure_compiler/externs/settings_private_interface.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - 'pref_util.js', - 'prefs_behavior.js', - 'prefs_types.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/prefs/compiled_resources2.gyp b/chrome/browser/resources/settings/prefs/compiled_resources2.gyp new file mode 100644 index 0000000..1446acb --- /dev/null +++ b/chrome/browser/resources/settings/prefs/compiled_resources2.gyp
@@ -0,0 +1,39 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'pref_util', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):settings_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'prefs', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):settings_private', + '<(INTERFACES_GYP):settings_private_interface', + 'pref_util', + 'prefs_behavior', + 'prefs_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'prefs_behavior', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(EXTERNS_GYP):settings_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'prefs_types', + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/reset_page/powerwash_dialog.html b/chrome/browser/resources/settings/reset_page/powerwash_dialog.html index ef43287..dd9a300 100644 --- a/chrome/browser/resources/settings/reset_page/powerwash_dialog.html +++ b/chrome/browser/resources/settings/reset_page/powerwash_dialog.html
@@ -2,37 +2,28 @@ <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/classes/iron-flex-layout.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-checkbox/paper-checkbox.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog/paper-dialog.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html"> -<link rel="import" href="chrome://md-settings/settings_dialog_css.html"> +<link rel="import" href="chrome://md-settings/settings_dialog.html"> +<link rel="import" href="chrome://md-settings/settings_shared_css.html"> <dom-module id="settings-powerwash-dialog"> <link rel="import" type="css" href="reset_page_dialog.css"> <template> - <style include="settings-dialog"></style> - <paper-dialog modal id="dialog"> - <div id="dialog-content"> - <div class="top-row"> - <span class="title" i18n-content="powerwashDialogTitle"></span> - <paper-icon-button icon="clear" on-tap="onCancelTap_" id="close"> - </paper-icon-button> - </div> - <div class="body"> - <div class="explanation"> - <span i18n-content="powerwashDialogExplanation"></span> - <a i18n-values="href:powerwashLearnMoreUrl" - i18n-content="learnMore" target="_blank"></a> - </div> - <div class="button-container"> - <paper-button class="cancel-button" on-tap="onCancelTap_" - id="cancel" i18n-content="cancel"></paper-button> - <paper-button class="action-button" id="powerwash" - on-tap="onRestartTap_" i18n-content="powerwashDialogButton"> - </paper-button> - </div> - </div> + <style include="settings-shared"></style> + <settings-dialog id="dialog"> + <div class="title" i18n-content="powerwashDialogTitle"></div> + <div class="body"> + <span i18n-content="powerwashDialogExplanation"></span> + <a i18n-values="href:powerwashLearnMoreUrl" + i18n-content="learnMore" target="_blank"></a> </div> - </paper-dialog> + <div class="button-container"> + <paper-button class="cancel-button" on-tap="onCancelTap_" + id="cancel" i18n-content="cancel"></paper-button> + <paper-button class="action-button" id="powerwash" + on-tap="onRestartTap_" i18n-content="powerwashDialogButton"> + </paper-button> + </div> + </settings-dialog> </template> <script src="powerwash_dialog.js"></script> </dom-module>
diff --git a/chrome/browser/resources/settings/reset_page/reset_page_dialog.css b/chrome/browser/resources/settings/reset_page/reset_page_dialog.css index 43afe64..6a832f3 100644 --- a/chrome/browser/resources/settings/reset_page/reset_page_dialog.css +++ b/chrome/browser/resources/settings/reset_page/reset_page_dialog.css
@@ -2,10 +2,6 @@ * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ -paper-button { - margin: 0; -} - a { color: rgb(66, 133, 244); text-decoration: none;
diff --git a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.css b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.css index e6ab1f7a..37ba0a1 100644 --- a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.css +++ b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.css
@@ -2,11 +2,7 @@ * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ -paper-dialog { - width: 500px; -} - -#feedbackBar { +.footer { background-color: rgb(236, 236, 236); margin: 0; padding: 20px;
diff --git a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html index 4afb5c25..a34a006a 100644 --- a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html +++ b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.html
@@ -2,39 +2,30 @@ <link rel="import" href="chrome://resources/polymer/v1_0/iron-flex-layout/classes/iron-flex-layout.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-checkbox/paper-checkbox.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog/paper-dialog.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner.html"> -<link rel="import" href="chrome://md-settings/settings_dialog_css.html"> +<link rel="import" href="chrome://md-settings/settings_dialog.html"> +<link rel="import" href="chrome://md-settings/settings_shared_css.html"> <dom-module id="settings-reset-profile-dialog"> <link rel="import" type="css" href="reset_page_dialog.css"> <link rel="import" type="css" href="reset_profile_dialog.css"> <template> - <style include="settings-dialog"></style> - <paper-dialog modal id="dialog"> - <div id="dialog-content"> - <div class="top-row"> - <span class="title" i18n-content="resetPageTitle"></span> - <paper-icon-button icon="clear" on-tap="onCancelTap_" id="close"> - </paper-icon-button> - </div> - <div class="body"> - <div class="explanation"> - <span i18n-content="resetPageExplanation"></span> - <a i18n-values="href:resetPageLearnMoreUrl" - i18n-content="learnMore" target="_blank"></a> - </div> - <div class="button-container"> - <paper-spinner id="resetSpinner"></paper-spinner> - <paper-button class="cancel-button" on-tap="onCancelTap_" - id="cancel" i18n-content="cancel"></paper-button> - <paper-button class="action-button" on-tap="onResetTap_" - id="reset" i18n-content="resetPageCommit"></paper-button> - </div> - </div> + <style include="settings-shared"></style> + <settings-dialog id="dialog"> + <div class="title" i18n-content="resetPageTitle"></div> + <div class="body"> + <span i18n-content="resetPageExplanation"></span> + <a i18n-values="href:resetPageLearnMoreUrl" + i18n-content="learnMore" target="_blank"></a> </div> - <div id="feedbackBar"> + <div class="button-container"> + <paper-spinner id="resetSpinner"></paper-spinner> + <paper-button class="cancel-button" on-tap="onCancelTap_" + id="cancel" i18n-content="cancel"></paper-button> + <paper-button class="action-button" on-tap="onResetTap_" + id="reset" i18n-content="resetPageCommit"></paper-button> + </div> + <div class="footer"> <paper-checkbox id="sendSettings" i18n-content="resetPageFeedback" checked on-change="onSendSettingsChange_"></paper-checkbox> <div id="settings"> @@ -43,7 +34,7 @@ </template> </div> </div> - </paper-dialog> + </settings-dialog> </template> <script src="reset_profile_dialog.js"></script> </dom-module>
diff --git a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js index f352ef7..d09faf5a 100644 --- a/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js +++ b/chrome/browser/resources/settings/reset_page/reset_profile_dialog.js
@@ -17,6 +17,7 @@ feedbackInfo_: String, }, + /** @override */ attached: function() { cr.define('SettingsResetPage', function() { return { @@ -33,6 +34,13 @@ }.bind(this)); }, + /** @override */ + ready: function() { + this.addEventListener('iron-overlay-canceled', function() { + chrome.send('onHideResetProfileDialog'); + }); + }, + dispatchResetDoneEvent: function() { this.dispatchEvent(new CustomEvent('reset-done')); }, @@ -44,8 +52,7 @@ /** @private */ onCancelTap_: function() { - this.$.dialog.close(); - chrome.send('onHideResetProfileDialog'); + this.$.dialog.cancel(); }, /** @private */
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html b/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html index e5997ad9..b914c91d 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html +++ b/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.html
@@ -2,52 +2,41 @@ <link rel="import" href="chrome://md-settings/i18n_setup.html"> <link rel="import" href="chrome://md-settings/search_engines_page/search_engines_browser_proxy.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog/paper-dialog.html"> -<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-input/paper-input.html"> <link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> -<link rel="import" href="chrome://md-settings/settings_dialog_css.html"> +<link rel="import" href="chrome://md-settings/settings_dialog.html"> <link rel="import" href="chrome://md-settings/settings_shared_css.html"> <dom-module id="settings-search-engine-dialog"> <template> - <style include="settings-dialog"></style> <style include="settings-shared"></style> - <paper-dialog modal id="dialog"> - <div id="dialog-content"> - <div class="top-row"> - <span class="title">[[dialogTitle_]]</span> - <paper-icon-button icon="clear" on-tap="cancel_" id="close"> - </paper-icon-button> - </div> - <div class="body"> - <div class="explanation"> - <paper-input always-float-label id="searchEngine" - i18n-values="label:searchEnginesSearchEngine;error-message:searchEnginesNotValid" - value="{{searchEngine_}}" on-focus="validate_" - on-input="validate_"> - </paper-input> - <paper-input always-float-label id="keyword" - i18n-values="label:searchEnginesKeyword;error-message:searchEnginesNotValid" - value="{{keyword_}}" on-focus="validate_" on-input="validate_"> - </paper-input> - <paper-input always-float-label id="queryUrl" - i18n-values="label:searchEnginesQueryURLExplanation;error-message:searchEnginesNotValid" - value="{{queryUrl_}}" on-focus="validate_" on-input="validate_" - disabled$="[[model.urlLocked]]"> - </paper-input> - </div> - <div class="button-container"> - <paper-button class="cancel-button" on-tap="cancel_" - i18n-content="cancel" id="cancel"></paper-button> - <paper-button id="actionButton" class="action-button" - on-tap="onActionButtonTap_"> - [[actionButtonText_]] - </paper-button> - </div> - </div> + <settings-dialog id="dialog"> + <div class="title">[[dialogTitle_]]</div> + <div class="body"> + <paper-input always-float-label id="searchEngine" + i18n-values="label:searchEnginesSearchEngine;error-message:searchEnginesNotValid" + value="{{searchEngine_}}" on-focus="validate_" + on-input="validate_"> + </paper-input> + <paper-input always-float-label id="keyword" + i18n-values="label:searchEnginesKeyword;error-message:searchEnginesNotValid" + value="{{keyword_}}" on-focus="validate_" on-input="validate_"> + </paper-input> + <paper-input always-float-label id="queryUrl" + i18n-values="label:searchEnginesQueryURLExplanation;error-message:searchEnginesNotValid" + value="{{queryUrl_}}" on-focus="validate_" on-input="validate_" + disabled$="[[model.urlLocked]]"> + </paper-input> </div> - </paper-dialog> + <div class="button-container"> + <paper-button class="cancel-button" on-tap="cancel_" + i18n-content="cancel" id="cancel"></paper-button> + <paper-button id="actionButton" class="action-button" + on-tap="onActionButtonTap_"> + [[actionButtonText_]] + </paper-button> + </div> + </settings-dialog> </template> <script src="search_engine_dialog.js"></script> </dom-module>
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js b/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js index 10e4e29..06eb4ded 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js +++ b/chrome/browser/resources/settings/search_engines_page/search_engine_dialog.js
@@ -68,6 +68,10 @@ loadTimeData.getString('searchEnginesAddSearchEngine'); this.actionButtonText_ = loadTimeData.getString('add'); } + + this.addEventListener('iron-overlay-canceled', function() { + this.browserProxy_.searchEngineEditCancelled(); + }.bind(this)); }, /** @override */ @@ -80,8 +84,7 @@ /** @private */ cancel_: function() { - this.browserProxy_.searchEngineEditCancelled(); - this.$.dialog.close(); + this.$.dialog.cancel(); }, /** @private */
diff --git a/chrome/browser/resources/settings/search_engines_page/search_engines_page.html b/chrome/browser/resources/settings/search_engines_page/search_engines_page.html index 8cf876b6..682e71ea 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engines_page.html +++ b/chrome/browser/resources/settings/search_engines_page/search_engines_page.html
@@ -3,13 +3,13 @@ <link rel="import" href="chrome://resources/html/cr.html"> <link rel="import" href="chrome://resources/cr_elements/cr_expand_button/cr_expand_button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/iron-collapse/iron-collapse.html"> +<link rel="import" href="chrome://resources/html/web_ui_listener_behavior.html"> +<link rel="import" href="chrome://resources/html/action_link.html"> <link rel="import" href="chrome://md-settings/search_engines_page/search_engines_browser_proxy.html"> <link rel="import" href="chrome://md-settings/search_engines_page/search_engine_dialog.html"> <link rel="import" href="chrome://md-settings/search_engines_page/search_engines_list.html"> <link rel="import" href="chrome://md-settings/search_engines_page/omnibox_extension_entry.html"> <link rel="import" href="chrome://md-settings/settings_shared_css.html"> -<link rel="import" href="chrome://md-settings/web_ui_listener_behavior.html"> -<link rel="import" href="chrome://resources/html/action_link.html"> <dom-module id="settings-search-engines-page"> <template>
diff --git a/chrome/browser/resources/settings/settings_dialog.html b/chrome/browser/resources/settings/settings_dialog.html new file mode 100644 index 0000000..3b2cc93 --- /dev/null +++ b/chrome/browser/resources/settings/settings_dialog.html
@@ -0,0 +1,83 @@ +<link rel="import" href="chrome://resources/html/polymer_config.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/iron-icons/iron-icons.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog-behavior/paper-dialog-behavior.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-dialog-behavior/paper-dialog-shared-styles.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> + +<dom-module id="settings-dialog"> + <template> + <style include="paper-dialog-shared-styles"></style> + <style> + .dialog-content { + -webkit-padding-end: 0; + -webkit-padding-start: 0; + margin-bottom: 0; + margin-top: 0; + } + + .footer-container { + margin: 0; + padding: 0; + } + + .top-row { + align-items: center; + border-bottom: 1px solid gainsboro; + display: flex; + padding-bottom: 5px; + padding-top: 5px; + } + + .body-content { + font-size: 1em; + margin: 20px 0; + } + + :host { + max-width: 800px; + min-width: 500px; + } + + :host ::content .title { + flex: 1; + font-size: 1.13em; + } + + :host ::content .title, + .body-content { + -webkit-padding-end: 24px; + -webkit-padding-start: 24px; + } + + :host ::content .body { + margin-bottom: 35px; + } + + :host ::content .button-container { + display: flex; + justify-content: flex-end; + } + + :host ::content .button-container .cancel-button { + color: rgb(109, 109, 109); + font-weight: 500; + } + </style> + <div class="dialog-content"> + <div class="top-row"> + <content select=".title"></content> + <paper-icon-button icon="clear" on-tap="cancel" id="close"> + </paper-icon-button> + </div> + <div class="body-content"> + <content select=".body"></content> + <content select=".button-container"></content> + </div> + </div> + <div class="footer-container"> + <content select=".footer"></content> + </div> + </template> + <script src="settings_dialog.js"></script> +</dom-module>
diff --git a/chrome/browser/resources/settings/settings_dialog.js b/chrome/browser/resources/settings/settings_dialog.js new file mode 100644 index 0000000..0322044 --- /dev/null +++ b/chrome/browser/resources/settings/settings_dialog.js
@@ -0,0 +1,28 @@ +// 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. + +/** + * @fileoverview 'settings-dialog' is a component for showing a modal dialog. + * + * @group Chrome Settings Elements + * @element settings-dialog + */ +Polymer({ + is: 'settings-dialog', + + properties: { + /** @override */ + modal: { + type: Boolean, + value: true, + }, + }, + + behaviors: [Polymer.PaperDialogBehavior], + + /** @return {!PaperIconButtonElement} */ + getCloseButton: function() { + return this.$.close; + }, +});
diff --git a/chrome/browser/resources/settings/settings_dialog_css.html b/chrome/browser/resources/settings/settings_dialog_css.html deleted file mode 100644 index 5e0cc79..0000000 --- a/chrome/browser/resources/settings/settings_dialog_css.html +++ /dev/null
@@ -1,65 +0,0 @@ -<!-- Common dialog styles for Material Design settings. --> -<dom-module id="settings-dialog"> - <template> - <style> - paper-dialog { - max-width: 800px; - min-width: 500px; - } - - #dialog-content { - -webkit-padding-end: 0; - -webkit-padding-start: 0; - margin-bottom: 0; - margin-top: 0; - } - - paper-dialog .top-row { - align-items: center; - border-bottom: 1px solid gainsboro; - display: flex; - padding-bottom: 5px; - padding-top: 5px; - } - - paper-dialog .title { - flex: 1; - font-size: 1.13em; - } - - paper-dialog .body { - font-size: 1em; - margin: 20px 0; - } - - paper-dialog .title, - paper-dialog .body { - -webkit-padding-end: 24px; - -webkit-padding-start: 24px; - } - - paper-dialog .cancel-button { - color: rgb(109, 109, 109); - font-weight: 500; - } - - paper-dialog .explanation { - margin-bottom: 35px; - } - - paper-dialog .button-container { - display: flex; - justify-content: flex-end; - } - - paper-dialog paper-button { - margin: 0; - min-width: auto; - } - - paper-dialog paper-button[toggles][active] { - background-color: LightGray; - } - </style> - </template> -</dom-module>
diff --git a/chrome/browser/resources/settings/settings_page/compiled_resources.gyp b/chrome/browser/resources/settings/settings_page/compiled_resources.gyp deleted file mode 100644 index a36c51a8..0000000 --- a/chrome/browser/resources/settings/settings_page/compiled_resources.gyp +++ /dev/null
@@ -1,21 +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. -{ - 'targets': [ - { - 'target_name': 'settings_page_visibility', - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'settings_router', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/settings_page/compiled_resources2.gyp b/chrome/browser/resources/settings/settings_page/compiled_resources2.gyp index 42cd2ac0..c422dff 100644 --- a/chrome/browser/resources/settings/settings_page/compiled_resources2.gyp +++ b/chrome/browser/resources/settings/settings_page/compiled_resources2.gyp
@@ -11,5 +11,17 @@ ], 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, + { + 'target_name': 'settings_page_visibility', + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'settings_router', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, ], }
diff --git a/chrome/browser/resources/settings/settings_resources.grd b/chrome/browser/resources/settings/settings_resources.grd index 3baa6b8..8754c7bb 100644 --- a/chrome/browser/resources/settings/settings_resources.grd +++ b/chrome/browser/resources/settings/settings_resources.grd
@@ -130,8 +130,11 @@ <structure name="IDR_SETTINGS_CR_SETTINGS_SUBHEADER_JS" file="settings_page/settings_subheader.js" type="chrome_html" /> - <structure name="IDR_SETTINGS_CR_SETTINGS_DIALOG_CSS_HTML" - file="settings_dialog_css.html" + <structure name="IDR_SETTINGS_CR_SETTINGS_DIALOG_HTML" + file="settings_dialog.html" + type="chrome_html" /> + <structure name="IDR_SETTINGS_CR_SETTINGS_DIALOG_JS" + file="settings_dialog.js" type="chrome_html" /> <structure name="IDR_SETTINGS_CR_SETTINGS_PAGE_CSS" file="settings_page.css" @@ -559,12 +562,6 @@ type="chrome_html" flattenhtml="true" allowexternalscript="true" /> - <structure name="IDR_SETTINGS_WEB_UI_LISTENER_BEHAVIOR_HTML" - file="web_ui_listener_behavior.html" - type="chrome_html" /> - <structure name="IDR_SETTINGS_WEB_UI_LISTENER_BEHAVIOR_JS" - file="web_ui_listener_behavior.js" - type="chrome_html" /> <structure name="IDR_SETTINGS_SEARCH_PAGE_JS" file="search_page/search_page.js" type="chrome_html" />
diff --git a/chrome/browser/resources/settings/site_settings/compiled_resources.gyp b/chrome/browser/resources/settings/site_settings/compiled_resources.gyp deleted file mode 100644 index 647c2d7..0000000 --- a/chrome/browser/resources/settings/site_settings/compiled_resources.gyp +++ /dev/null
@@ -1,114 +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. -{ - 'targets': [ - { - 'target_name': 'all_sites', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - 'constants.js', - 'site_settings_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'site_details', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - 'constants.js', - 'site_settings_behavior.js', - 'site_details_permission.js', - 'website_usage_private_api.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'site_details_permission', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - 'constants.js', - 'site_settings_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'site_list', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - '../prefs/prefs_types.js', - 'constants.js', - 'site_settings_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'site_settings_behavior', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - 'constants.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'site_settings_category', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - '../prefs/prefs_types.js', - '../settings_page/settings_animated_pages.js', - 'constants.js', - 'site_settings_behavior.js', - 'site_settings_prefs_browser_proxy.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp b/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp new file mode 100644 index 0000000..6151fea --- /dev/null +++ b/chrome/browser/resources/settings/site_settings/compiled_resources2.gyp
@@ -0,0 +1,111 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'all_sites', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:prefs_behavior', + 'constants', + 'site_settings_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'constants', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'site_details', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:prefs_behavior', + 'constants', + 'site_settings_behavior', + 'site_details_permission', + 'website_usage_private_api', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'site_details_permission', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '../prefs/compiled_resources2.gyp:prefs_behavior', + 'constants', + 'site_settings_behavior', + ], + 'externs': [ + '<(EXTERNS_GYP):settings_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'site_list', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:prefs_behavior', + '../prefs/compiled_resources2.gyp:prefs_types', + 'constants', + 'site_settings_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'site_settings_behavior', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:prefs_behavior', + 'constants', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'site_settings_category', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):settings_private', + '../prefs/compiled_resources2.gyp:prefs_behavior', + '../prefs/compiled_resources2.gyp:prefs_types', + '../settings_page/compiled_resources2.gyp:settings_animated_pages', + 'constants', + 'site_settings_behavior', + 'site_settings_prefs_browser_proxy', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'site_settings_prefs_browser_proxy', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):chrome_send', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'website_usage_private_api', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(EXTERNS_GYP):chrome_send', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/site_settings_page/compiled_resources.gyp b/chrome/browser/resources/settings/site_settings_page/compiled_resources.gyp deleted file mode 100644 index 953d45c4..0000000 --- a/chrome/browser/resources/settings/site_settings_page/compiled_resources.gyp +++ /dev/null
@@ -1,27 +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. -{ - 'targets': [ - { - 'target_name': 'site_settings_page', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:cr', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../prefs/prefs_behavior.js', - '../prefs/prefs_types.js', - '../settings_page/settings_animated_pages.js', - '../site_settings/constants.js', - '../site_settings/site_settings_behavior.js', - '../site_settings/site_settings_prefs_browser_proxy.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/settings/site_settings_page/compiled_resources2.gyp b/chrome/browser/resources/settings/site_settings_page/compiled_resources2.gyp new file mode 100644 index 0000000..32230405 --- /dev/null +++ b/chrome/browser/resources/settings/site_settings_page/compiled_resources2.gyp
@@ -0,0 +1,21 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'site_settings_page', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '../prefs/compiled_resources2.gyp:prefs_behavior', + '../prefs/compiled_resources2.gyp:prefs_types', + '../site_settings/compiled_resources2.gyp:constants', + '../site_settings/compiled_resources2.gyp:site_settings_behavior', + '../site_settings/compiled_resources2.gyp:site_settings_prefs_browser_proxy', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/settings/web_ui_listener_behavior.html b/chrome/browser/resources/settings/web_ui_listener_behavior.html deleted file mode 100644 index d021bebc..0000000 --- a/chrome/browser/resources/settings/web_ui_listener_behavior.html +++ /dev/null
@@ -1,2 +0,0 @@ -<link rel="import" href="chrome://resources/html/cr.html"> -<script src="web_ui_listener_behavior.js"></script>
diff --git a/chrome/browser/resources/sync_confirmation/sync_confirmation.css b/chrome/browser/resources/sync_confirmation/sync_confirmation.css index ab041f3..912f717 100644 --- a/chrome/browser/resources/sync_confirmation/sync_confirmation.css +++ b/chrome/browser/resources/sync_confirmation/sync_confirmation.css
@@ -3,7 +3,6 @@ * found in the LICENSE file. */ body { - font-size: 100%; margin: 0; padding: 0; } @@ -32,8 +31,8 @@ border-bottom: 1px solid lightgray; color: #333; display: flex; - font-size: 1em; - height: 56px; + font-size: 16px; + height: 52px; } .details { @@ -43,7 +42,6 @@ .sync-message { color: #595959; - font-size: 0.8125em; line-height: 150%; padding-bottom: 32px; } @@ -74,9 +72,14 @@ } paper-button { - font-size: 0.8125em; - padding-left: 12px; - padding-right: 12px; + font-weight: 500; + line-height: 16px; + margin: 0; + padding: 8px 16px; +} + +paper-button + paper-button { + -webkit-margin-start: 8px; } #confirmButton {
diff --git a/chrome/browser/resources/uber/compiled_resources.gyp b/chrome/browser/resources/uber/compiled_resources.gyp deleted file mode 100644 index e21a6e6..0000000 --- a/chrome/browser/resources/uber/compiled_resources.gyp +++ /dev/null
@@ -1,34 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -{ - 'targets': [ - { - 'target_name': 'uber_utils', - 'variables': { - 'depends': [ - '../../../../ui/webui/resources/js/cr.js', - '../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../ui/webui/resources/js/promise_resolver.js', - '../../../../ui/webui/resources/js/util.js', - ], - 'externs': ['<(EXTERNS_DIR)/chrome_send.js'], - }, - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'uber', - 'variables': { - 'depends': [ - '../../../../ui/webui/resources/js/cr.js', - '../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../../../../ui/webui/resources/js/promise_resolver.js', - '../../../../ui/webui/resources/js/util.js', - 'uber_utils.js', - ], - 'externs': ['<(EXTERNS_DIR)/chrome_send.js'], - }, - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/chrome/browser/resources/uber/compiled_resources2.gyp b/chrome/browser/resources/uber/compiled_resources2.gyp new file mode 100644 index 0000000..960d088 --- /dev/null +++ b/chrome/browser/resources/uber/compiled_resources2.gyp
@@ -0,0 +1,41 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'uber_frame', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', + '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:focus_outline_manager', + 'uber_utils', + ], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'uber_utils', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', + '<(EXTERNS_GYP):chrome_send', + ], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'uber', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:util', + 'uber_utils', + '<(EXTERNS_GYP):chrome_send', + ], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/chrome/browser/resources/uber/uber_frame.js b/chrome/browser/resources/uber/uber_frame.js index 1b3e967f..cf3f3a4 100644 --- a/chrome/browser/resources/uber/uber_frame.js +++ b/chrome/browser/resources/uber/uber_frame.js
@@ -53,7 +53,7 @@ uber.invokeMethodOnParent('showPage', {pageId: e.currentTarget.getAttribute('controls')}); - setSelection(e.currentTarget); + setSelection(/** @type {Element} */(e.currentTarget)); } /** @@ -116,7 +116,7 @@ * Adjusts this frame's content to scrolls from the outer frame. This is done * to obscure text in RTL as a user scrolls over the content of this frame (as * currently RTL scrollbars still draw on the right). - * @param {number} scroll document.body.scrollLeft of the content frame. + * @param {number} scrollLeft document.body.scrollLeft of the content frame. */ function adjustToScroll(scrollLeft) { assert(isRTL());
diff --git a/chrome/browser/supervised_user/supervised_user_site_list.cc b/chrome/browser/supervised_user/supervised_user_site_list.cc index f7d1851..94264cc4 100644 --- a/chrome/browser/supervised_user/supervised_user_site_list.cc +++ b/chrome/browser/supervised_user/supervised_user_site_list.cc
@@ -86,6 +86,7 @@ void SupervisedUserSiteList::Load(const std::string& id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& path, const LoadedCallback& callback) { base::PostTaskAndReplyWithResult( @@ -94,19 +95,21 @@ base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN) .get(), FROM_HERE, base::Bind(&ReadFileOnBlockingThread, path), - base::Bind(&SupervisedUserSiteList::OnJsonLoaded, id, title, path, - base::TimeTicks::Now(), callback)); + base::Bind(&SupervisedUserSiteList::OnJsonLoaded, id, title, + large_icon_path, path, base::TimeTicks::Now(), callback)); } SupervisedUserSiteList::SupervisedUserSiteList( const std::string& id, const base::string16& title, const GURL& entry_point, + const base::FilePath& large_icon_path, const base::ListValue* patterns, const base::ListValue* hostname_hashes) : SupervisedUserSiteList(id, title, entry_point, + large_icon_path, ConvertListValues(patterns), ConvertListValues(hostname_hashes)) {} @@ -114,9 +117,14 @@ const std::string& id, const base::string16& title, const GURL& entry_point, + const base::FilePath& large_icon_path, const std::vector<std::string>& patterns, const std::vector<std::string>& hostname_hashes) - : id_(id), title_(title), entry_point_(entry_point), patterns_(patterns) { + : id_(id), + title_(title), + entry_point_(entry_point), + large_icon_path_(large_icon_path), + patterns_(patterns) { for (const std::string& hostname_hash : hostname_hashes) { std::vector<uint8_t> hash_bytes; if (hostname_hash.size() != 2 * base::kSHA1Length || @@ -136,6 +144,7 @@ void SupervisedUserSiteList::OnJsonLoaded( const std::string& id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& path, base::TimeTicks start_time, const SupervisedUserSiteList::LoadedCallback& callback, @@ -183,6 +192,7 @@ base::ListValue* hostname_hashes = nullptr; dict->GetList(kHostnameHashesKey, &hostname_hashes); - callback.Run(make_scoped_refptr(new SupervisedUserSiteList( - id, title, GURL(entry_point_url), patterns, hostname_hashes))); + callback.Run(make_scoped_refptr( + new SupervisedUserSiteList(id, title, GURL(entry_point_url), + large_icon_path, patterns, hostname_hashes))); }
diff --git a/chrome/browser/supervised_user/supervised_user_site_list.h b/chrome/browser/supervised_user/supervised_user_site_list.h index 8d2c6ead..74f16ed 100644 --- a/chrome/browser/supervised_user/supervised_user_site_list.h +++ b/chrome/browser/supervised_user/supervised_user_site_list.h
@@ -65,12 +65,14 @@ // the newly created object. static void Load(const std::string& id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& file, const LoadedCallback& callback); const std::string& id() const { return id_; } const base::string16& title() const { return title_; } const GURL& entry_point() const { return entry_point_; } + const base::FilePath& large_icon_path() const { return large_icon_path_; } const std::vector<std::string>& patterns() const { return patterns_; } const std::vector<HostnameHash>& hostname_hashes() const { return hostname_hashes_; @@ -86,12 +88,14 @@ SupervisedUserSiteList(const std::string& id, const base::string16& title, const GURL& entry_point, + const base::FilePath& large_icon_path, const base::ListValue* patterns, const base::ListValue* hostname_hashes); // Used for testing. SupervisedUserSiteList(const std::string& id, const base::string16& title, const GURL& entry_point, + const base::FilePath& large_icon_path, const std::vector<std::string>& patterns, const std::vector<std::string>& hostname_hashes); ~SupervisedUserSiteList(); @@ -100,6 +104,7 @@ static void OnJsonLoaded( const std::string& id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& path, base::TimeTicks start_time, const SupervisedUserSiteList::LoadedCallback& callback, @@ -108,6 +113,7 @@ std::string id_; base::string16 title_; GURL entry_point_; + base::FilePath large_icon_path_; // A list of URL patterns that should be whitelisted. std::vector<std::string> patterns_;
diff --git a/chrome/browser/supervised_user/supervised_user_url_filter_unittest.cc b/chrome/browser/supervised_user/supervised_user_url_filter_unittest.cc index 358bb55..339b197 100644 --- a/chrome/browser/supervised_user/supervised_user_url_filter_unittest.cc +++ b/chrome/browser/supervised_user/supervised_user_url_filter_unittest.cc
@@ -361,12 +361,12 @@ const std::vector<std::string> hostname_hashes; const GURL entry_point("https://entry.com"); - scoped_refptr<SupervisedUserSiteList> site_list1 = - make_scoped_refptr(new SupervisedUserSiteList( - id1, title1, entry_point, patterns1, hostname_hashes)); - scoped_refptr<SupervisedUserSiteList> site_list2 = - make_scoped_refptr(new SupervisedUserSiteList( - id2, title2, entry_point, patterns2, hostname_hashes)); + scoped_refptr<SupervisedUserSiteList> site_list1 = make_scoped_refptr( + new SupervisedUserSiteList(id1, title1, entry_point, base::FilePath(), + patterns1, hostname_hashes)); + scoped_refptr<SupervisedUserSiteList> site_list2 = make_scoped_refptr( + new SupervisedUserSiteList(id2, title2, entry_point, base::FilePath(), + patterns2, hostname_hashes)); std::vector<scoped_refptr<SupervisedUserSiteList>> site_lists; site_lists.push_back(site_list1); @@ -418,15 +418,15 @@ const base::string16 title3 = base::ASCIIToUTF16("Title 3"); const GURL entry_point("htttps://entry.com"); - scoped_refptr<SupervisedUserSiteList> site_list1 = - make_scoped_refptr(new SupervisedUserSiteList( - id1, title1, entry_point, patterns1, hostname_hashes1)); - scoped_refptr<SupervisedUserSiteList> site_list2 = - make_scoped_refptr(new SupervisedUserSiteList( - id2, title2, entry_point, patterns2, hostname_hashes2)); - scoped_refptr<SupervisedUserSiteList> site_list3 = - make_scoped_refptr(new SupervisedUserSiteList( - id3, title3, entry_point, patterns3, hostname_hashes3)); + scoped_refptr<SupervisedUserSiteList> site_list1 = make_scoped_refptr( + new SupervisedUserSiteList(id1, title1, entry_point, base::FilePath(), + patterns1, hostname_hashes1)); + scoped_refptr<SupervisedUserSiteList> site_list2 = make_scoped_refptr( + new SupervisedUserSiteList(id2, title2, entry_point, base::FilePath(), + patterns2, hostname_hashes2)); + scoped_refptr<SupervisedUserSiteList> site_list3 = make_scoped_refptr( + new SupervisedUserSiteList(id3, title3, entry_point, base::FilePath(), + patterns3, hostname_hashes3)); std::vector<scoped_refptr<SupervisedUserSiteList>> site_lists; site_lists.push_back(site_list1);
diff --git a/chrome/browser/supervised_user/supervised_user_whitelist_service.cc b/chrome/browser/supervised_user/supervised_user_whitelist_service.cc index 84379c9..91df9bf 100644 --- a/chrome/browser/supervised_user/supervised_user_whitelist_service.cc +++ b/chrome/browser/supervised_user/supervised_user_whitelist_service.cc
@@ -117,7 +117,7 @@ const base::FilePath& path) { bool result = registered_whitelists_.insert(id).second; DCHECK(result); - OnWhitelistReady(id, title, path); + OnWhitelistReady(id, title, base::FilePath(), path); } void SupervisedUserWhitelistService::UnloadWhitelist(const std::string& id) { @@ -332,6 +332,7 @@ void SupervisedUserWhitelistService::OnWhitelistReady( const std::string& id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& whitelist_path) { // If we did not register the whitelist or it has been unregistered in the // mean time, ignore it. @@ -339,7 +340,7 @@ return; SupervisedUserSiteList::Load( - id, title, whitelist_path, + id, title, large_icon_path, whitelist_path, base::Bind(&SupervisedUserWhitelistService::OnWhitelistLoaded, weak_ptr_factory_.GetWeakPtr(), id, base::TimeTicks::Now())); }
diff --git a/chrome/browser/supervised_user/supervised_user_whitelist_service.h b/chrome/browser/supervised_user/supervised_user_whitelist_service.h index a1f57e0..d77f0d7 100644 --- a/chrome/browser/supervised_user/supervised_user_whitelist_service.h +++ b/chrome/browser/supervised_user/supervised_user_whitelist_service.h
@@ -115,6 +115,7 @@ void OnWhitelistReady(const std::string& id, const base::string16& title, + const base::FilePath& large_icon_path, const base::FilePath& whitelist_path); void OnWhitelistLoaded( const std::string& id,
diff --git a/chrome/browser/supervised_user/supervised_user_whitelist_service_unittest.cc b/chrome/browser/supervised_user/supervised_user_whitelist_service_unittest.cc index e33d379..e8704ab 100644 --- a/chrome/browser/supervised_user/supervised_user_whitelist_service_unittest.cc +++ b/chrome/browser/supervised_user/supervised_user_whitelist_service_unittest.cc
@@ -48,9 +48,10 @@ void NotifyWhitelistReady(const std::string& crx_id, const base::string16& title, - const base::FilePath& path) { + const base::FilePath& large_icon_path, + const base::FilePath& whitelist_path) { for (const auto& callback : ready_callbacks_) - callback.Run(crx_id, title, path); + callback.Run(crx_id, title, large_icon_path, whitelist_path); } // SupervisedUserWhitelistInstaller implementation: @@ -200,7 +201,7 @@ base::FilePath whitelist_path = test_data_dir.AppendASCII("whitelists/content_pack/site_list.json"); installer_->NotifyWhitelistReady("aaaa", base::ASCIIToUTF16("Title"), - whitelist_path); + base::FilePath(), whitelist_path); run_loop.Run(); ASSERT_EQ(1u, site_lists_.size()); @@ -260,7 +261,7 @@ // If whitelist A now becomes ready, it should be ignored. installer_->NotifyWhitelistReady( - "aaaa", base::ASCIIToUTF16("Title"), + "aaaa", base::ASCIIToUTF16("Title"), base::FilePath(), base::FilePath(FILE_PATH_LITERAL("/path/to/aaaa"))); EXPECT_EQ(0u, site_lists_.size());
diff --git a/chrome/browser/sync/chrome_sync_client.cc b/chrome/browser/sync/chrome_sync_client.cc index e6fe2c3..802fc8d64 100644 --- a/chrome/browser/sync/chrome_sync_client.cc +++ b/chrome/browser/sync/chrome_sync_client.cc
@@ -12,6 +12,7 @@ #include "build/build_config.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" @@ -19,6 +20,7 @@ #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/prefs/pref_service_syncable_util.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/sync/glue/sync_start_util.h" @@ -481,6 +483,28 @@ component_factory_ = std::move(component_factory); } +// static +void ChromeSyncClient::GetDeviceInfoTrackers( + std::vector<const sync_driver::DeviceInfoTracker*>* trackers) { + DCHECK(trackers); + ProfileManager* profile_manager = g_browser_process->profile_manager(); + std::vector<Profile*> profile_list = profile_manager->GetLoadedProfiles(); + for (Profile* profile : profile_list) { + const ProfileSyncService* profile_sync_service = + ProfileSyncServiceFactory::GetForProfile(profile); + if (profile_sync_service != nullptr) { + const sync_driver::DeviceInfoTracker* tracker = + profile_sync_service->GetDeviceInfoTracker(); + if (tracker != nullptr) { + // Even when sync is disabled and/or user is signed out, a tracker will + // still be present. It will only be missing when the ProfileSyncService + // has not sufficiently initialized yet. + trackers->push_back(tracker); + } + } + } +} + void ChromeSyncClient::RegisterDesktopDataTypes( sync_driver::SyncService* sync_service, syncer::ModelTypeSet disabled_types,
diff --git a/chrome/browser/sync/chrome_sync_client.h b/chrome/browser/sync/chrome_sync_client.h index f94c669..6786f31 100644 --- a/chrome/browser/sync/chrome_sync_client.h +++ b/chrome/browser/sync/chrome_sync_client.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_SYNC_CHROME_SYNC_CLIENT_H__ #define CHROME_BROWSER_SYNC_CHROME_SYNC_CLIENT_H__ +#include <vector> + #include "base/macros.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" #include "chrome/browser/sync/glue/extensions_activity_monitor.h" @@ -21,6 +23,7 @@ } namespace sync_driver { +class DeviceInfoTracker; class SyncApiComponentFactory; class SyncService; } @@ -62,6 +65,12 @@ void SetSyncApiComponentFactoryForTesting( scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory); + // Iterates over all of the profiles that have been loaded so far, and + // extracts their tracker if present. If some profiles don't have trackers, no + // indication is given in the passed vector. + static void GetDeviceInfoTrackers( + std::vector<const sync_driver::DeviceInfoTracker*>* trackers); + private: // Register data types which are enabled on desktop platforms only. // |disabled_types| and |enabled_types| correspond only to those types
diff --git a/chrome/browser/sync/test/integration/sync_app_helper.cc b/chrome/browser/sync/test/integration/sync_app_helper.cc index 30f26f9..6752ed3 100644 --- a/chrome/browser/sync/test/integration/sync_app_helper.cc +++ b/chrome/browser/sync/test/integration/sync_app_helper.cc
@@ -168,8 +168,7 @@ DVLOG(2) << "Apps for profile " << profile2->GetDebugName() << " are not valid."; return false; - } else if (!sync_datatype_helper::test()->UsingExternalServers() && - !it1->second.Equals(it2->second)) { + } else if (!it1->second.Equals(it2->second)) { // If this test is run against real backend servers then we do not expect // to install pending apps. So, we don't check equality of AppStates of // each app per profile.
diff --git a/chrome/browser/sync/test/integration/sync_extension_helper.cc b/chrome/browser/sync/test/integration/sync_extension_helper.cc index 2b10e2d..36edbbe 100644 --- a/chrome/browser/sync/test/integration/sync_extension_helper.cc +++ b/chrome/browser/sync/test/integration/sync_extension_helper.cc
@@ -276,11 +276,7 @@ DVLOG(1) << "Extensions for profile " << profile1->GetDebugName() << " do not match profile " << profile2->GetDebugName(); return false; - } else if (!sync_datatype_helper::test()->UsingExternalServers() && - !it1->second.Equals(it2->second)) { - // If this test is run against real backend servers then we do not expect - // to install pending extensions. So, we don't check equality of - // ExtensionState of each extension per profile. + } else if (!it1->second.Equals(it2->second)) { DVLOG(1) << "Extension states for profile " << profile1->GetDebugName() << " do not match profile " << profile2->GetDebugName(); return false;
diff --git a/chrome/browser/sync/test/integration/sync_extension_installer.cc b/chrome/browser/sync/test/integration/sync_extension_installer.cc index 0f1a5d50..59d8225 100644 --- a/chrome/browser/sync/test/integration/sync_extension_installer.cc +++ b/chrome/browser/sync/test/integration/sync_extension_installer.cc
@@ -45,11 +45,5 @@ } void SyncedExtensionInstaller::DoInstallSyncedExtensions() { - // Do not try to install any extensions when running against real servers. - // We can not assume that we have a clean slate of extensions installed per - // profile before running the test cases. - if (!sync_datatype_helper::test()->UsingExternalServers()) { - SyncExtensionHelper::GetInstance()-> - InstallExtensionsPendingForSync(profile_); - } + SyncExtensionHelper::GetInstance()->InstallExtensionsPendingForSync(profile_); }
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index 3722d61..b36cefb 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -487,6 +487,14 @@ invalidation_forwarders_.resize(num_clients_); sync_refreshers_.resize(num_clients_); fake_server_invalidation_services_.resize(num_clients_); + + if (create_gaia_account_at_runtime_) { + CHECK(UsingExternalServers()) << + "Cannot create Gaia accounts without external authentication servers"; + if (!CreateGaiaAccount(username_, password_)) + LOG(FATAL) << "Could not create Gaia account."; + } + for (int i = 0; i < num_clients_; ++i) { CreateProfile(i); } @@ -593,12 +601,6 @@ } bool SyncTest::SetupSync() { - if (create_gaia_account_at_runtime_) { - CHECK(UsingExternalServers()) << - "Cannot create Gaia accounts without external authentication servers"; - if (!CreateGaiaAccount(username_, password_)) - LOG(FATAL) << "Could not create Gaia account."; - } // Create sync profiles and clients if they haven't already been created. if (profiles_.empty()) { if (!SetupClients())
diff --git a/chrome/browser/sync/test/integration/two_client_apps_sync_test.cc b/chrome/browser/sync/test/integration/two_client_apps_sync_test.cc index 650d5bf0..0dae46c 100644 --- a/chrome/browser/sync/test/integration/two_client_apps_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_apps_sync_test.cc
@@ -21,6 +21,7 @@ #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "extensions/browser/app_sorting.h" +#include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/common/constants.h" @@ -66,20 +67,20 @@ DISALLOW_COPY_AND_ASSIGN(TwoClientAppsSyncTest); }; -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, StartWithNoApps) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(StartWithNoApps)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, StartWithSameApps) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(StartWithSameApps)) { + DisableVerifier(); ASSERT_TRUE(SetupClients()); const int kNumApps = 5; for (int i = 0; i < kNumApps; ++i) { InstallApp(GetProfile(0), i); InstallApp(GetProfile(1), i); - InstallApp(verifier(), i); } ASSERT_TRUE(SetupSync()); @@ -134,7 +135,9 @@ // Install some apps on both clients, then sync. Then install some apps on only // one client, some on only the other, and then sync again. Both clients should // end up with all apps, and the app and page ordinals should be identical. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, InstallDifferentApps) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, + E2E_ENABLED(InstallDifferentApps)) { + DisableVerifier(); ASSERT_TRUE(SetupClients()); int i = 0; @@ -143,7 +146,6 @@ for (int j = 0; j < kNumCommonApps; ++i, ++j) { InstallApp(GetProfile(0), i); InstallApp(GetProfile(1), i); - InstallApp(verifier(), i); } ASSERT_TRUE(SetupSync()); @@ -151,44 +153,37 @@ const int kNumProfile0Apps = 10; for (int j = 0; j < kNumProfile0Apps; ++i, ++j) { InstallApp(GetProfile(0), i); - InstallApp(verifier(), i); - CopyNTPOrdinals(GetProfile(0), verifier(), i); } const int kNumProfile1Apps = 10; for (int j = 0; j < kNumProfile1Apps; ++i, ++j) { InstallApp(GetProfile(1), i); - InstallApp(verifier(), i); - CopyNTPOrdinals(GetProfile(1), verifier(), i); } - FixNTPOrdinalCollisions(verifier()); - ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // TCM ID - 3711279. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, Add) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(Add)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // TCM ID - 3706267. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, Uninstall) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(Uninstall)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); UninstallApp(GetProfile(0), 0); - UninstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } @@ -196,125 +191,104 @@ // client and sync again. Now install a new app on the first client and sync. // Both client should only have the second app, with identical app and page // ordinals. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UninstallThenInstall) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, + E2E_ENABLED(UninstallThenInstall)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); UninstallApp(GetProfile(0), 0); - UninstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 1); - InstallApp(verifier(), 1); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // TCM ID - 3699295. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, Merge) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(Merge)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); UninstallApp(GetProfile(0), 0); - UninstallApp(verifier(), 0); InstallApp(GetProfile(0), 1); - InstallApp(verifier(), 1); - InstallApp(GetProfile(0), 2); - InstallApp(GetProfile(1), 2); - InstallApp(verifier(), 2); + InstallApp(GetProfile(1), 2); InstallApp(GetProfile(1), 3); - InstallApp(verifier(), 3); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // TCM ID - 7723126. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UpdateEnableDisableApp) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, + E2E_ENABLED(UpdateEnableDisableApp)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); DisableApp(GetProfile(0), 0); - DisableApp(verifier(), 0); - ASSERT_TRUE(HasSameAppsAsVerifier(0)); - ASSERT_FALSE(HasSameAppsAsVerifier(1)); - ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); EnableApp(GetProfile(1), 0); - EnableApp(verifier(), 0); - ASSERT_TRUE(HasSameAppsAsVerifier(1)); - ASSERT_FALSE(HasSameAppsAsVerifier(0)); - ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // TCM ID - 7706637. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UpdateIncognitoEnableDisable) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, + E2E_ENABLED(UpdateIncognitoEnableDisable)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); IncognitoEnableApp(GetProfile(0), 0); - IncognitoEnableApp(verifier(), 0); - ASSERT_TRUE(HasSameAppsAsVerifier(0)); - ASSERT_FALSE(HasSameAppsAsVerifier(1)); - ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); IncognitoDisableApp(GetProfile(1), 0); - IncognitoDisableApp(verifier(), 0); - ASSERT_TRUE(HasSameAppsAsVerifier(1)); - ASSERT_FALSE(HasSameAppsAsVerifier(0)); - ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // Install the same app on both clients, then sync. Change the page ordinal on // one client and sync. Both clients should have the updated page ordinal for // the app. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UpdatePageOrdinal) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(UpdatePageOrdinal)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); syncer::StringOrdinal initial_page = syncer::StringOrdinal::CreateInitialOrdinal(); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); syncer::StringOrdinal second_page = initial_page.CreateAfter(); SetPageOrdinalForApp(GetProfile(0), 0, second_page); - SetPageOrdinalForApp(verifier(), 0, second_page); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // Install the same app on both clients, then sync. Change the app launch // ordinal on one client and sync. Both clients should have the updated app // launch ordinal for the app. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UpdateAppLaunchOrdinal) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, + E2E_ENABLED(UpdateAppLaunchOrdinal)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); InstallApp(GetProfile(0), 0); - InstallApp(verifier(), 0); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); syncer::StringOrdinal initial_position = @@ -322,16 +296,16 @@ syncer::StringOrdinal second_position = initial_position.CreateAfter(); SetAppLaunchOrdinalForApp(GetProfile(0), 0, second_position); - SetAppLaunchOrdinalForApp(verifier(), 0, second_position); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // Adjust the CWS location within a page on the first client and sync. Adjust // which page the CWS appears on and sync. Both clients should have the same // page and app launch ordinal values for the CWS. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UpdateCWSOrdinals) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(UpdateCWSOrdinals)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); // Change the app launch ordinal. syncer::StringOrdinal cws_app_launch_ordinal = @@ -342,10 +316,6 @@ ->app_sorting() ->SetAppLaunchOrdinal(extensions::kWebStoreAppId, cws_app_launch_ordinal.CreateAfter()); - extensions::ExtensionSystem::Get(verifier()) - ->app_sorting() - ->SetAppLaunchOrdinal(extensions::kWebStoreAppId, - cws_app_launch_ordinal.CreateAfter()); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); // Change the page ordinal. @@ -357,33 +327,36 @@ ->app_sorting() ->SetPageOrdinal(extensions::kWebStoreAppId, cws_page_ordinal.CreateAfter()); - extensions::ExtensionSystem::Get(verifier()) - ->app_sorting() - ->SetPageOrdinal(extensions::kWebStoreAppId, - cws_page_ordinal.CreateAfter()); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); } // Adjust the launch type on the first client and sync. Both clients should // have the same launch type values for the CWS. -IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UpdateLaunchType) { +IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, E2E_ENABLED(UpdateLaunchType)) { + DisableVerifier(); ASSERT_TRUE(SetupSync()); - ASSERT_TRUE(AllProfilesHaveSameAppsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); // Change the launch type to window. extensions::SetLaunchType(GetProfile(1), extensions::kWebStoreAppId, extensions::LAUNCH_TYPE_WINDOW); - extensions::SetLaunchType(verifier(), extensions::kWebStoreAppId, - extensions::LAUNCH_TYPE_WINDOW); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); + ASSERT_EQ( + extensions::GetLaunchTypePrefValue( + extensions::ExtensionPrefs::Get(GetProfile(0)), + extensions::kWebStoreAppId), + extensions::LAUNCH_TYPE_WINDOW); // Change the launch type to regular tab. extensions::SetLaunchType(GetProfile(1), extensions::kWebStoreAppId, extensions::LAUNCH_TYPE_REGULAR); - ASSERT_FALSE(HasSameAppsAsVerifier(1)); - extensions::SetLaunchType(verifier(), extensions::kWebStoreAppId, - extensions::LAUNCH_TYPE_REGULAR); ASSERT_TRUE(AwaitAllProfilesHaveSameApps()); + + ASSERT_EQ( + extensions::GetLaunchTypePrefValue( + extensions::ExtensionPrefs::Get(GetProfile(0)), + extensions::kWebStoreAppId), + extensions::LAUNCH_TYPE_REGULAR); } IN_PROC_BROWSER_TEST_F(TwoClientAppsSyncTest, UnexpectedLaunchType) {
diff --git a/chrome/browser/sync/test/integration/two_client_dictionary_sync_test.cc b/chrome/browser/sync/test/integration/two_client_dictionary_sync_test.cc index 85a4c8c0..e00030e 100644 --- a/chrome/browser/sync/test/integration/two_client_dictionary_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_dictionary_sync_test.cc
@@ -27,7 +27,7 @@ DISALLOW_COPY_AND_ASSIGN(TwoClientDictionarySyncTest); }; -IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, Sanity) { +IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, E2E_ENABLED(Sanity)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; dictionary_helper::LoadDictionaries(); ASSERT_TRUE(dictionary_helper::AwaitDictionariesMatch()); @@ -56,7 +56,8 @@ ASSERT_EQ(words.size(), dictionary_helper::GetDictionarySize(0)); } -IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, SimultaneousAdd) { +IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, + E2E_ENABLED(SimultaneousAdd)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; dictionary_helper::LoadDictionaries(); ASSERT_TRUE(dictionary_helper::AwaitDictionariesMatch()); @@ -67,7 +68,8 @@ ASSERT_EQ(1UL, dictionary_helper::GetDictionarySize(0)); } -IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, SimultaneousRemove) { +IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, + E2E_ENABLED(SimultaneousRemove)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; dictionary_helper::LoadDictionaries(); ASSERT_TRUE(dictionary_helper::AwaitDictionariesMatch()); @@ -83,7 +85,8 @@ ASSERT_EQ(0UL, dictionary_helper::GetDictionarySize(0)); } -IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, AddDifferentToEach) { +IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, + E2E_ENABLED(AddDifferentToEach)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; dictionary_helper::LoadDictionaries(); ASSERT_TRUE(dictionary_helper::AwaitDictionariesMatch()); @@ -96,7 +99,8 @@ static_cast<int>(dictionary_helper::GetDictionarySize(0))); } -IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, RemoveOnAAddOnB) { +IN_PROC_BROWSER_TEST_F(TwoClientDictionarySyncTest, + E2E_ENABLED(RemoveOnAAddOnB)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; dictionary_helper::LoadDictionaries(); ASSERT_TRUE(dictionary_helper::AwaitDictionariesMatch());
diff --git a/chrome/browser/sync/test/integration/two_client_extensions_sync_test.cc b/chrome/browser/sync/test/integration/two_client_extensions_sync_test.cc index 5dca55b..5367ceac 100644 --- a/chrome/browser/sync/test/integration/two_client_extensions_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_extensions_sync_test.cc
@@ -59,7 +59,6 @@ static_cast<int>(GetInstalledExtensions(GetProfile(0)).size())); } -// Disabled as an E2ETest crbug.com/532202 // Flaky on Mac: http://crbug.com/535996 #if defined(OS_MACOSX) #define MAYBE_StartWithDifferentExtensions DISABLED_StartWithDifferentExtensions @@ -67,7 +66,7 @@ #define MAYBE_StartWithDifferentExtensions StartWithDifferentExtensions #endif IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, - MAYBE_StartWithDifferentExtensions) { + E2E_ENABLED(MAYBE_StartWithDifferentExtensions)) { ASSERT_TRUE(SetupClients()); int extension_index = 0; @@ -95,9 +94,8 @@ static_cast<int>(GetInstalledExtensions(GetProfile(0)).size())); } -// Disabled as an E2ETest crbug.com/532202 IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, - InstallDifferentExtensions) { + E2E_ENABLED(InstallDifferentExtensions)) { ASSERT_TRUE(SetupClients()); int extension_index = 0; @@ -139,7 +137,7 @@ } // TCM ID - 3724281. -IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, Uninstall) { +IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, E2E_ENABLED(Uninstall)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AllProfilesHaveSameExtensions()); @@ -153,7 +151,7 @@ // TCM ID - 3605300. IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, - UpdateEnableDisableExtension) { + E2E_ENABLED(UpdateEnableDisableExtension)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AllProfilesHaveSameExtensions()); @@ -173,7 +171,7 @@ // TCM ID - 3728322. IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, - UpdateIncognitoEnableDisable) { + E2E_ENABLED(UpdateIncognitoEnableDisable)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AllProfilesHaveSameExtensions()); @@ -194,7 +192,7 @@ // Regression test for bug 104399: ensure that an extension installed prior to // setting up sync, when uninstalled, is also uninstalled from sync. IN_PROC_BROWSER_TEST_F(TwoClientExtensionsSyncTest, - UninstallPreinstalledExtensions) { + E2E_ENABLED(UninstallPreinstalledExtensions)) { ASSERT_TRUE(SetupClients()); ASSERT_TRUE(AllProfilesHaveSameExtensions());
diff --git a/chrome/browser/sync/test/integration/two_client_password_manager_setting_migrator_service_sync_test.cc b/chrome/browser/sync/test/integration/two_client_password_manager_setting_migrator_service_sync_test.cc index 232e112b..6bd917a 100644 --- a/chrome/browser/sync/test/integration/two_client_password_manager_setting_migrator_service_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_password_manager_setting_migrator_service_sync_test.cc
@@ -68,7 +68,7 @@ }; IN_PROC_BROWSER_TEST_F(TwoClientsPasswordManagerSettingMigratorServiceSyncTest, - ChangeLegacyPrefTestBothClientsWithMigration) { + E2E_ENABLED(ChangeLegacyPrefTestBothClientsWithMigration)) { ASSERT_TRUE(SetupSync()); EnsureMigrationStartsForClient(0); EnsureMigrationStartsForClient(1); @@ -76,7 +76,7 @@ } IN_PROC_BROWSER_TEST_F(TwoClientsPasswordManagerSettingMigratorServiceSyncTest, - ChangeNewPrefTestBothClientsWithMigration) { + E2E_ENABLED(ChangeNewPrefTestBothClientsWithMigration)) { ASSERT_TRUE(SetupClients()); EnsureMigrationStartsForClient(0); EnsureMigrationStartsForClient(1); @@ -86,7 +86,7 @@ IN_PROC_BROWSER_TEST_F( TwoClientsPasswordManagerSettingMigratorServiceSyncTest, - ChangeLegacyPrefOnMigratedClientOneClientsWithMigration) { + E2E_ENABLED(ChangeLegacyPrefOnMigratedClientOneClientsWithMigration)) { ASSERT_TRUE(SetupSync()); EnsureMigrationStartsForClient(0); TestPrefChangeOnClient(0, kPasswordManagerSavingEnabled); @@ -95,7 +95,7 @@ IN_PROC_BROWSER_TEST_F( TwoClientsPasswordManagerSettingMigratorServiceSyncTest, - ChangeLegacyPrefOnNonMigratedClientOneClientsWithMigration) { + E2E_ENABLED(ChangeLegacyPrefOnNonMigratedClientOneClientsWithMigration)) { ASSERT_TRUE(SetupSync()); EnsureMigrationStartsForClient(0); TestPrefChangeOnClient(1, kPasswordManagerSavingEnabled); @@ -103,7 +103,7 @@ } IN_PROC_BROWSER_TEST_F(TwoClientsPasswordManagerSettingMigratorServiceSyncTest, - ChangeNewPrefOnMigratedClientOneClientsWithMigration) { + E2E_ENABLED(ChangeNewPrefOnMigratedClientOneClientsWithMigration)) { ASSERT_TRUE(SetupSync()); EnsureMigrationStartsForClient(0); TestPrefChangeOnClient(0, kCredentialsEnableService); @@ -112,7 +112,7 @@ IN_PROC_BROWSER_TEST_F( TwoClientsPasswordManagerSettingMigratorServiceSyncTest, - ChangeNewPrefOnNonMigratedClientOneClientsWithMigration) { + E2E_ENABLED(ChangeNewPrefOnNonMigratedClientOneClientsWithMigration)) { ASSERT_TRUE(SetupSync()); EnsureMigrationStartsForClient(0); TestPrefChangeOnClient(1, kCredentialsEnableService);
diff --git a/chrome/browser/sync/test/integration/two_client_passwords_sync_test.cc b/chrome/browser/sync/test/integration/two_client_passwords_sync_test.cc index d625d03..36642cc 100644 --- a/chrome/browser/sync/test/integration/two_client_passwords_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_passwords_sync_test.cc
@@ -53,20 +53,19 @@ }; // TCM ID - 3732277 -IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, Add) { +IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, E2E_ENABLED(Add)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - ASSERT_TRUE(AllProfilesContainSamePasswordFormsAsVerifier()); + ASSERT_TRUE(AwaitAllProfilesContainSamePasswordForms()); PasswordForm form = CreateTestPasswordForm(0); - AddLogin(GetVerifierPasswordStore(), form); - ASSERT_EQ(1, GetVerifierPasswordCount()); AddLogin(GetPasswordStore(0), form); ASSERT_EQ(1, GetPasswordCount(0)); ASSERT_TRUE(AwaitAllProfilesContainSamePasswordForms()); + ASSERT_EQ(1, GetPasswordCount(1)); } -IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, Race) { +IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, E2E_ENABLED(Race)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(AllProfilesContainSamePasswordForms()); @@ -81,7 +80,7 @@ } IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, - SetPassphraseAndAddPassword) { + E2E_ENABLED(SetPassphraseAndAddPassword)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; SetEncryptionPassphrase(0, kValidPassphrase, ProfileSyncService::EXPLICIT); @@ -228,7 +227,7 @@ } // TCM ID - 3694311 -IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, Merge) { +IN_PROC_BROWSER_TEST_F(TwoClientPasswordsSyncTest, E2E_ENABLED(Merge)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(AllProfilesContainSamePasswordForms());
diff --git a/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc b/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc index 6c84479..b4a6f48 100644 --- a/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_preferences_sync_test.cc
@@ -49,7 +49,7 @@ } } -IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, BooleanPref) { +IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, E2E_ENABLED(BooleanPref)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitBooleanPrefMatches(prefs::kHomePageIsNewTabPage)); @@ -57,7 +57,8 @@ ASSERT_TRUE(AwaitBooleanPrefMatches(prefs::kHomePageIsNewTabPage)); } -IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, Bidirectional) { +IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, + E2E_ENABLED(Bidirectional)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitStringPrefMatches(prefs::kHomePage)); @@ -71,7 +72,8 @@ EXPECT_EQ("http://www.google.com/1", GetPrefs(0)->GetString(prefs::kHomePage)); } -IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, UnsyncableBooleanPref) { +IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, + E2E_ENABLED(UnsyncableBooleanPref)) { ASSERT_TRUE(SetupSync()); DisableVerifier(); ASSERT_TRUE(AwaitStringPrefMatches(prefs::kHomePage)); @@ -89,7 +91,7 @@ ASSERT_FALSE(BooleanPrefMatches(prefs::kCheckDefaultBrowser)); } -IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, StringPref) { +IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, E2E_ENABLED(StringPref)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitStringPrefMatches(prefs::kHomePage)); @@ -97,7 +99,8 @@ ASSERT_TRUE(AwaitStringPrefMatches(prefs::kHomePage)); } -IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, ComplexPrefs) { +IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, + E2E_ENABLED(ComplexPrefs)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitIntegerPrefMatches(prefs::kRestoreOnStartup)); ASSERT_TRUE(AwaitListPrefMatches(prefs::kURLsToRestoreOnStartup)); @@ -115,7 +118,7 @@ } IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, - SingleClientEnabledEncryptionBothChanged) { + E2E_ENABLED(SingleClientEnabledEncryptionBothChanged)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitBooleanPrefMatches(prefs::kHomePageIsNewTabPage)); ASSERT_TRUE(AwaitStringPrefMatches(prefs::kHomePage)); @@ -130,7 +133,7 @@ } IN_PROC_BROWSER_TEST_F(TwoClientPreferencesSyncTest, - BothClientsEnabledEncryptionAndChangedMultipleTimes) { + E2E_ENABLED(BothClientsEnabledEncryptionAndChangedMultipleTimes)) { ASSERT_TRUE(SetupSync()); ASSERT_TRUE(AwaitBooleanPrefMatches(prefs::kHomePageIsNewTabPage));
diff --git a/chrome/browser/sync/test/integration/two_client_search_engines_sync_test.cc b/chrome/browser/sync/test/integration/two_client_search_engines_sync_test.cc index 4a44202..404adc69 100644 --- a/chrome/browser/sync/test/integration/two_client_search_engines_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_search_engines_sync_test.cc
@@ -61,7 +61,8 @@ } // TCM ID - 8912240. -IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, AddMultiple) { +IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, + E2E_ENABLED(AddMultiple)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(search_engines_helper::AllServicesMatch()); @@ -91,7 +92,8 @@ } // TCM ID - 9004201. -IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, UpdateKeyword) { +IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, + E2E_ENABLED(UpdateKeyword)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(search_engines_helper::AllServicesMatch()); @@ -108,7 +110,7 @@ } // TCM ID - 8894859. -IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, UpdateUrl) { +IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, E2E_ENABLED(UpdateUrl)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(search_engines_helper::AllServicesMatch()); @@ -125,7 +127,8 @@ } // TCM ID - 8910490. -IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, UpdateName) { +IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, + E2E_ENABLED(UpdateName)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(search_engines_helper::AllServicesMatch()); @@ -205,7 +208,8 @@ } // TCM ID - 8891809. -IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, SyncDefault) { +IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, + E2E_ENABLED(SyncDefault)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(search_engines_helper::AllServicesMatch()); @@ -221,7 +225,8 @@ // Ensure that we can change the search engine and immediately delete it // without putting the clients out of sync. -IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, DeleteSyncedDefault) { +IN_PROC_BROWSER_TEST_F(TwoClientSearchEnginesSyncTest, + E2E_ENABLED(DeleteSyncedDefault)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; ASSERT_TRUE(search_engines_helper::AllServicesMatch());
diff --git a/chrome/browser/sync/test/integration/two_client_themes_sync_test.cc b/chrome/browser/sync/test/integration/two_client_themes_sync_test.cc index b0df58c..9203659 100644 --- a/chrome/browser/sync/test/integration/two_client_themes_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_themes_sync_test.cc
@@ -34,17 +34,15 @@ // Starts with default themes, then sets up sync and uses it to set all // profiles to use a custom theme. Does not actually install any themes, but // instead verifies the custom theme is pending for install. -IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, DefaultThenSyncCustom) { +IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, + E2E_ENABLED(DefaultThenSyncCustom)) { ASSERT_TRUE(SetupSync()); ASSERT_FALSE(UsingCustomTheme(GetProfile(0))); ASSERT_FALSE(UsingCustomTheme(GetProfile(1))); - ASSERT_FALSE(UsingCustomTheme(verifier())); UseCustomTheme(GetProfile(0), 0); - UseCustomTheme(verifier(), 0); ASSERT_EQ(GetCustomTheme(0), GetThemeID(GetProfile(0))); - ASSERT_EQ(GetCustomTheme(0), GetThemeID(verifier())); // TODO(sync): Add functions to simulate when a pending extension // is installed as well as when a pending extension fails to @@ -53,87 +51,72 @@ EXPECT_EQ(GetCustomTheme(0), GetThemeID(GetProfile(0))); EXPECT_FALSE(UsingCustomTheme(GetProfile(1))); - EXPECT_EQ(GetCustomTheme(0), GetThemeID(verifier())); } // Starts with custom themes, then sets up sync and uses it to set all profiles // to the system theme. -IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, CustomThenSyncNative) { +IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, + E2E_ENABLED(CustomThenSyncNative)) { ASSERT_TRUE(SetupClients()); UseCustomTheme(GetProfile(0), 0); UseCustomTheme(GetProfile(1), 0); - UseCustomTheme(verifier(), 0); ASSERT_TRUE(SetupSync()); UseSystemTheme(GetProfile(0)); - UseSystemTheme(verifier()); ASSERT_TRUE(UsingSystemTheme(GetProfile(0))); - ASSERT_TRUE(UsingSystemTheme(verifier())); ASSERT_TRUE(AwaitUsingSystemTheme(GetProfile(1))); EXPECT_TRUE(UsingSystemTheme(GetProfile(0))); EXPECT_TRUE(UsingSystemTheme(GetProfile(1))); - EXPECT_TRUE(UsingSystemTheme(verifier())); } // Starts with custom themes, then sets up sync and uses it to set all profiles // to the default theme. -IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, CustomThenSyncDefault) { +IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, + E2E_ENABLED(CustomThenSyncDefault)) { ASSERT_TRUE(SetupClients()); UseCustomTheme(GetProfile(0), 0); UseCustomTheme(GetProfile(1), 0); - UseCustomTheme(verifier(), 0); ASSERT_TRUE(SetupSync()); UseDefaultTheme(GetProfile(0)); - UseDefaultTheme(verifier()); EXPECT_TRUE(UsingDefaultTheme(GetProfile(0))); - EXPECT_TRUE(UsingDefaultTheme(verifier())); ASSERT_TRUE(AwaitUsingDefaultTheme(GetProfile(1))); EXPECT_TRUE(UsingDefaultTheme(GetProfile(0))); EXPECT_TRUE(UsingDefaultTheme(GetProfile(1))); - EXPECT_TRUE(UsingDefaultTheme(verifier())); } // Cycles through a set of options. // // Most other tests have significant coverage of model association. This test // is intended to test steady-state scenarios. -IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, CycleOptions) { +IN_PROC_BROWSER_TEST_F(TwoClientThemesSyncTest, E2E_ENABLED(CycleOptions)) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; UseCustomTheme(GetProfile(0), 0); - UseCustomTheme(verifier(), 0); ASSERT_TRUE(AwaitThemeIsPendingInstall(GetProfile(1), GetCustomTheme(0))); EXPECT_EQ(GetCustomTheme(0), GetThemeID(GetProfile(0))); - EXPECT_EQ(GetCustomTheme(0), GetThemeID(verifier())); UseSystemTheme(GetProfile(0)); - UseSystemTheme(verifier()); ASSERT_TRUE(AwaitUsingSystemTheme(GetProfile(1))); EXPECT_TRUE(UsingSystemTheme(GetProfile(0))); EXPECT_TRUE(UsingSystemTheme(GetProfile(1))); - EXPECT_TRUE(UsingSystemTheme(verifier())); UseDefaultTheme(GetProfile(0)); - UseDefaultTheme(verifier()); ASSERT_TRUE(AwaitUsingDefaultTheme(GetProfile(1))); EXPECT_TRUE(UsingDefaultTheme(GetProfile(0))); EXPECT_TRUE(UsingDefaultTheme(GetProfile(1))); - EXPECT_TRUE(UsingDefaultTheme(verifier())); UseCustomTheme(GetProfile(0), 1); - UseCustomTheme(verifier(), 1); ASSERT_TRUE(AwaitThemeIsPendingInstall(GetProfile(1), GetCustomTheme(1))); EXPECT_EQ(GetCustomTheme(1), GetThemeID(GetProfile(0))); - EXPECT_EQ(GetCustomTheme(1), GetThemeID(verifier())); }
diff --git a/chrome/browser/sync/test/integration/two_client_typed_urls_sync_test.cc b/chrome/browser/sync/test/integration/two_client_typed_urls_sync_test.cc index 09f60cc..a73aa4cb 100644 --- a/chrome/browser/sync/test/integration/two_client_typed_urls_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_typed_urls_sync_test.cc
@@ -194,7 +194,8 @@ } // TCM: 3643277 -IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, DisableEnableSync) { +IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, + E2E_ENABLED(DisableEnableSync)) { const base::string16 kUrl1(ASCIIToUTF16("http://history1.google.com/")); const base::string16 kUrl2(ASCIIToUTF16("http://history2.google.com/")); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; @@ -389,7 +390,7 @@ } IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, - DontSyncUpdatedNonTypedURLs) { + E2E_ENABLED(DontSyncUpdatedNonTypedURLs)) { // Checks if a non-typed URL that has been updated (modified) doesn't get // synced. This is a regression test after fixing a bug where adding a // non-typed URL was guarded against but later modifying it was not. Since @@ -426,7 +427,8 @@ ui::PAGE_TRANSITION_TYPED)); } -IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, SyncTypedRedirects) { +IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, + E2E_ENABLED(SyncTypedRedirects)) { const base::string16 kHistoryUrl(ASCIIToUTF16("http://typed.google.com/")); const base::string16 kRedirectedHistoryUrl( ASCIIToUTF16("http://www.typed.google.com/"));
diff --git a/chrome/browser/ui/browser_focus_uitest.cc b/chrome/browser/ui/browser_focus_uitest.cc index 142b522..37f4147 100644 --- a/chrome/browser/ui/browser_focus_uitest.cc +++ b/chrome/browser/ui/browser_focus_uitest.cc
@@ -738,4 +738,29 @@ EXPECT_FALSE(IsViewFocused(VIEW_ID_OMNIBOX)); } +// Ensure that crbug.com/567445 does not regress. This test checks that the +// Omnibox does not get focused when loading about:blank in a case where it's +// not the startup URL, e.g. when a page opens a popup to about:blank, with a +// null opener, and then navigates it. This is a potential security issue; see +// comments in |WebContentsImpl::FocusLocationBarByDefault|. +IN_PROC_BROWSER_TEST_F(BrowserFocusTest, AboutBlankNavigationLocationTest) { + const GURL url1(embedded_test_server()->GetURL("/title1.html")); + ui_test_utils::NavigateToURL(browser(), url1); + + TabStripModel* tab_strip = browser()->tab_strip_model(); + WebContents* web_contents = tab_strip->GetActiveWebContents(); + + const GURL url2(embedded_test_server()->GetURL("/title2.html")); + const std::string spoof("var w = window.open('about:blank'); w.opener = null;" + "w.document.location = '" + url2.spec() + "';"); + + ASSERT_TRUE(content::ExecuteScript(web_contents, spoof)); + EXPECT_EQ(url1, web_contents->GetVisibleURL()); + // After running the spoof code, |GetActiveWebContents| returns the new tab, + // not the same as |web_contents|. + ASSERT_NO_FATAL_FAILURE(content::WaitForLoadStop( + browser()->tab_strip_model()->GetActiveWebContents())); + EXPECT_FALSE(IsViewFocused(VIEW_ID_OMNIBOX)); +} + } // namespace
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.h b/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.h index 27113dfc..9fcd262 100644 --- a/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.h +++ b/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_UI_COCOA_AUTOFILL_AUTOFILL_DIALOG_COCOA_H_ #include "base/mac/scoped_nsobject.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/autofill/autofill_dialog_types.h" #include "chrome/browser/ui/autofill/autofill_dialog_view.h" @@ -65,7 +64,7 @@ // Closes the sheet and ends the modal loop. Triggers cleanup sequence. void CloseNow(); - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; base::scoped_nsobject<AutofillDialogWindowController> sheet_delegate_; // The delegate |this| queries for logic and state.
diff --git a/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.mm b/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.mm index 4a80bbd..1731bb3 100644 --- a/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.mm +++ b/chrome/browser/ui/cocoa/autofill/autofill_dialog_cocoa.mm
@@ -38,8 +38,8 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:[sheet_delegate_ window]]); - constrained_window_.reset( - new ConstrainedWindowMac(this, delegate_->GetWebContents(), sheet)); + constrained_window_ = + CreateAndShowWebModalDialogMac(this, delegate_->GetWebContents(), sheet); [sheet_delegate_ show]; }
diff --git a/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.h b/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.h index 64faef1..e9358d3 100644 --- a/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.h +++ b/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_UI_COCOA_AUTOFILL_CARD_UNMASK_PROMPT_VIEW_BRIDGE_H_ #include "base/mac/scoped_nsobject.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h" #include "components/autofill/core/browser/ui/card_unmask_prompt_view.h" @@ -41,7 +40,7 @@ void PerformClose(); private: - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; base::scoped_nsobject<CardUnmaskPromptViewCocoa> view_controller_; // The controller |this| queries for logic and state.
diff --git a/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.mm b/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.mm index 2a9d770..b4f949e 100644 --- a/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.mm +++ b/chrome/browser/ui/cocoa/autofill/card_unmask_prompt_view_bridge.mm
@@ -87,8 +87,8 @@ [window setContentView:[view_controller_ view]]; base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:window]); - constrained_window_.reset( - new ConstrainedWindowMac(this, web_contents_, sheet)); + constrained_window_ = + CreateAndShowWebModalDialogMac(this, web_contents_, sheet); } void CardUnmaskPromptViewBridge::ControllerGone() {
diff --git a/chrome/browser/ui/cocoa/certificate_viewer_mac.h b/chrome/browser/ui/cocoa/certificate_viewer_mac.h index f33bef2d..7990758 100644 --- a/chrome/browser/ui/cocoa/certificate_viewer_mac.h +++ b/chrome/browser/ui/cocoa/certificate_viewer_mac.h
@@ -24,7 +24,7 @@ base::scoped_nsobject<NSArray> certificates_; scoped_ptr<SSLCertificateViewerCocoaBridge> observer_; base::scoped_nsobject<SFCertificatePanel> panel_; - scoped_ptr<ConstrainedWindowMac> constrainedWindow_; + std::unique_ptr<ConstrainedWindowMac> constrainedWindow_; base::scoped_nsobject<NSWindow> overlayWindow_; BOOL closePending_; // A copy of the sheet's frame used to restore on show.
diff --git a/chrome/browser/ui/cocoa/certificate_viewer_mac.mm b/chrome/browser/ui/cocoa/certificate_viewer_mac.mm index 5c41b94f..1adb0f1 100644 --- a/chrome/browser/ui/cocoa/certificate_viewer_mac.mm +++ b/chrome/browser/ui/cocoa/certificate_viewer_mac.mm
@@ -134,8 +134,8 @@ panel_.reset([[SFCertificatePanel alloc] init]); [panel_ setPolicies:(id) policies.get()]; - constrainedWindow_.reset( - new ConstrainedWindowMac(observer_.get(), webContents, self)); + constrainedWindow_ = + CreateAndShowWebModalDialogMac(observer_.get(), webContents, self); } - (NSWindow*)overlayWindow { @@ -189,6 +189,10 @@ // NOOP } +- (void)resizeWithNewSize:(NSSize)preferredSize { + // NOOP +} + - (NSWindow*)sheetWindow { return panel_; }
diff --git a/chrome/browser/ui/cocoa/constrained_web_dialog_delegate_mac.mm b/chrome/browser/ui/cocoa/constrained_web_dialog_delegate_mac.mm index 0ce4df8d..5dc49ab 100644 --- a/chrome/browser/ui/cocoa/constrained_web_dialog_delegate_mac.mm +++ b/chrome/browser/ui/cocoa/constrained_web_dialog_delegate_mac.mm
@@ -11,7 +11,11 @@ #import "chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_window.h" #import "chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h" #import "chrome/browser/ui/cocoa/constrained_window/constrained_window_web_dialog_sheet.h" +#include "chrome/browser/ui/webui/chrome_web_contents_handler.h" +#include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_observer.h" +#include "ui/base/cocoa/window_size_constants.h" #include "ui/gfx/geometry/size.h" #include "ui/web_dialogs/web_dialog_delegate.h" #include "ui/web_dialogs/web_dialog_ui.h" @@ -23,19 +27,61 @@ namespace { +class ConstrainedWebDialogDelegateMac; + +// This class is to trigger a resize to the dialog window when +// ResizeDueToAutoResize() is invoked. +class WebDialogWebContentsDelegateMac + : public ui::WebDialogWebContentsDelegate { + public: + WebDialogWebContentsDelegateMac(content::BrowserContext* browser_context, + content::WebContentsObserver* observer, + ConstrainedWebDialogDelegateBase* delegate) + : ui::WebDialogWebContentsDelegate(browser_context, + new ChromeWebContentsHandler()), + observer_(observer), + delegate_(delegate) { + } + ~WebDialogWebContentsDelegateMac() override {} + + void ResizeDueToAutoResize(content::WebContents* source, + const gfx::Size& preferred_size) override { + if (!observer_->web_contents()) + return; + delegate_->ResizeToGivenSize(preferred_size); + } + + private: + // These members must outlive the instance. + content::WebContentsObserver* const observer_; + ConstrainedWebDialogDelegateBase* delegate_; + + DISALLOW_COPY_AND_ASSIGN(WebDialogWebContentsDelegateMac); +}; + class ConstrainedWebDialogDelegateMac : public ConstrainedWebDialogDelegateBase { public: ConstrainedWebDialogDelegateMac( content::BrowserContext* browser_context, - WebDialogDelegate* delegate) - : ConstrainedWebDialogDelegateBase(browser_context, delegate, NULL) {} + WebDialogDelegate* delegate, + content::WebContentsObserver* observer) + : ConstrainedWebDialogDelegateBase(browser_context, delegate, + new WebDialogWebContentsDelegateMac(browser_context, observer, + this)) {} // WebDialogWebContentsDelegate interface. void CloseContents(WebContents* source) override { window_->CloseWebContentsModalDialog(); } + // ConstrainedWebDialogDelegateBase: + void ResizeToGivenSize(const gfx::Size size) override { + NSSize updated_preferred_size = NSMakeSize(size.width(), + size.height()); + [window_->sheet() resizeWithNewSize:updated_preferred_size]; + } + void set_window(ConstrainedWindowMac* window) { window_ = window; } ConstrainedWindowMac* window() const { return window_; } @@ -50,13 +96,16 @@ class ConstrainedWebDialogDelegateViewMac : public ConstrainedWindowMacDelegate, - public ConstrainedWebDialogDelegate { + public ConstrainedWebDialogDelegate, + public content::WebContentsObserver { public: ConstrainedWebDialogDelegateViewMac( content::BrowserContext* browser_context, WebDialogDelegate* delegate, - content::WebContents* web_contents); + content::WebContents* web_contents, + const gfx::Size& min_size, + const gfx::Size& max_size); ~ConstrainedWebDialogDelegateViewMac() override {} // ConstrainedWebDialogDelegate interface @@ -75,16 +124,37 @@ gfx::NativeWindow GetNativeDialog() override { return window_; } WebContents* GetWebContents() override { return impl_->GetWebContents(); } gfx::Size GetMinimumSize() const override { - NOTIMPLEMENTED(); - return gfx::Size(); + return min_size_; } gfx::Size GetMaximumSize() const override { - NOTIMPLEMENTED(); - return gfx::Size(); + return max_size_; } gfx::Size GetPreferredSize() const override { - NOTIMPLEMENTED(); - return gfx::Size(); + gfx::Size size; + if (!impl_->closed_via_webui()) { + NSRect frame = [window_ frame]; + size = gfx::Size(frame.size.width, frame.size.height); + } + return size; + } + + // content::WebContentsObserver: + void RenderViewCreated(content::RenderViewHost* render_view_host) override { + if (IsDialogAutoResizable()) + EnableAutoResize(); + } + void RenderViewHostChanged(content::RenderViewHost* old_host, + content::RenderViewHost* new_host) override { + if (IsDialogAutoResizable()) + EnableAutoResize(); + } + void DocumentOnLoadCompletedInMainFrame() override { + if (!IsDialogAutoResizable()) + return; + + EnableAutoResize(); + if (GetWebContents()) + constrained_window_->ShowWebContentsModalDialog(); } // ConstrainedWindowMacDelegate interface @@ -95,25 +165,53 @@ } private: + void EnableAutoResize() { + if (!GetWebContents()) + return; + + content::RenderViewHost* render_view_host = + GetWebContents()->GetRenderViewHost(); + render_view_host->EnableAutoResize(min_size_, max_size_); + } + + // Whether or not the dialog is autoresizable is determined based on whether + // |max_size_| was specified. + bool IsDialogAutoResizable() { + return !max_size_.IsEmpty(); + } + scoped_ptr<ConstrainedWebDialogDelegateMac> impl_; - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; base::scoped_nsobject<NSWindow> window_; + // Minimum and maximum sizes to determine dialog bounds for auto-resizing. + const gfx::Size min_size_; + const gfx::Size max_size_; + DISALLOW_COPY_AND_ASSIGN(ConstrainedWebDialogDelegateViewMac); }; ConstrainedWebDialogDelegateViewMac::ConstrainedWebDialogDelegateViewMac( content::BrowserContext* browser_context, WebDialogDelegate* delegate, - content::WebContents* web_contents) - : impl_(new ConstrainedWebDialogDelegateMac(browser_context, delegate)) { + content::WebContents* web_contents, + const gfx::Size& min_size, + const gfx::Size& max_size) + : content::WebContentsObserver(web_contents), + impl_(new ConstrainedWebDialogDelegateMac(browser_context, delegate, + this)), + min_size_(min_size), + max_size_(max_size) { + if (IsDialogAutoResizable()) + Observe(GetWebContents()); + // Create a window to hold web_contents in the constrained sheet: gfx::Size size; delegate->GetDialogSize(&size); NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); - window_.reset( - [[ConstrainedWindowCustomWindow alloc] initWithContentRect:frame]); + window_.reset([[ConstrainedWindowCustomWindow alloc] + initWithContentRect:ui::kWindowSizeDeterminedLater]); [GetWebContents()->GetNativeView() setFrame:frame]; [GetWebContents()->GetNativeView() setAutoresizingMask: NSViewWidthSizable|NSViewHeightSizable]; @@ -122,8 +220,14 @@ base::scoped_nsobject<WebDialogConstrainedWindowSheet> sheet( [[WebDialogConstrainedWindowSheet alloc] initWithCustomWindow:window_ webDialogDelegate:delegate]); - constrained_window_.reset(new ConstrainedWindowMac( - this, web_contents, sheet)); + + if (IsDialogAutoResizable()) { + constrained_window_ = CreateWebModalDialogMac( + this, web_contents, sheet); + } else { + constrained_window_ = CreateAndShowWebModalDialogMac( + this, web_contents, sheet); + } impl_->set_window(constrained_window_.get()); } @@ -135,6 +239,23 @@ // Deleted when the dialog closes. ConstrainedWebDialogDelegateViewMac* constrained_delegate = new ConstrainedWebDialogDelegateViewMac( - browser_context, delegate, web_contents); + browser_context, delegate, web_contents, + gfx::Size(), gfx::Size()); + return constrained_delegate; +} + +ConstrainedWebDialogDelegate* ShowConstrainedWebDialogWithAutoResize( + content::BrowserContext* browser_context, + WebDialogDelegate* delegate, + content::WebContents* web_contents, + const gfx::Size& min_size, + const gfx::Size& max_size) { + DCHECK(!min_size.IsEmpty()); + DCHECK(!max_size.IsEmpty()); + // Deleted when the dialog closes. + ConstrainedWebDialogDelegateViewMac* constrained_delegate = + new ConstrainedWebDialogDelegateViewMac( + browser_context, delegate, web_contents, + min_size, max_size); return constrained_delegate; }
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_sheet.mm b/chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_sheet.mm index aac59467..ab67fc6 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_sheet.mm +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_custom_sheet.mm
@@ -73,6 +73,10 @@ [customWindow_ setFrameOrigin:origin]; } +- (void)resizeWithNewSize:(NSSize)size { + // NOOP +} + - (NSWindow*)sheetWindow { return customWindow_; }
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h b/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h index e3d981e..3b60a39 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h
@@ -7,6 +7,9 @@ #import <Cocoa/Cocoa.h> +#include "base/mac/scoped_nsobject.h" +#include "components/web_modal/web_contents_modal_dialog_manager.h" + namespace content { class WebContents; } @@ -21,6 +24,18 @@ virtual void OnConstrainedWindowClosed(ConstrainedWindowMac* window) = 0; }; +// Creates a ConstrainedWindowMac, shows the dialog, and returns it. +std::unique_ptr<ConstrainedWindowMac> CreateAndShowWebModalDialogMac( + ConstrainedWindowMacDelegate* delegate, + content::WebContents* web_contents, + id<ConstrainedWindowSheet> sheet); + +// Creates a ConstrainedWindowMac and returns it. +std::unique_ptr<ConstrainedWindowMac> CreateWebModalDialogMac( + ConstrainedWindowMacDelegate* delegate, + content::WebContents* web_contents, + id<ConstrainedWindowSheet> sheet); + // Constrained window implementation for Mac. // Normally an instance of this class is owned by the delegate. The delegate // should delete the instance when the window is closed. @@ -31,6 +46,9 @@ id<ConstrainedWindowSheet> sheet); ~ConstrainedWindowMac(); + // Shows the constrained window. + void ShowWebContentsModalDialog(); + // Closes the constrained window. void CloseWebContentsModalDialog(); @@ -38,13 +56,24 @@ void set_manager(SingleWebContentsDialogManagerCocoa* manager) { manager_ = manager; } + id<ConstrainedWindowSheet> sheet() const { return sheet_.get(); } // Called by |manager_| when the dialog is closing. void OnDialogClosing(); + // Whether or not the dialog was shown. If the dialog is auto-resizable, it + // is hidden until its WebContents initially loads. + bool DialogWasShown(); + + // Gets the dialog manager for |web_contents_|. + web_modal::WebContentsModalDialogManager* GetDialogManager(); + private: ConstrainedWindowMacDelegate* delegate_; // weak, owns us. SingleWebContentsDialogManagerCocoa* manager_; // weak, owned by WCMDM. + content::WebContents* web_contents_; // weak, owned by dialog initiator. + base::scoped_nsprotocol<id<ConstrainedWindowSheet>> sheet_; + scoped_ptr<SingleWebContentsDialogManagerCocoa> native_manager_; }; #endif // CHROME_BROWSER_UI_COCOA_CONSTRAINED_WINDOW_CONSTRAINED_WINDOW_MAC_
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.mm b/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.mm index 16f755c..510402e8 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.mm +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.mm
@@ -11,35 +11,59 @@ #import "chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet.h" #import "chrome/browser/ui/cocoa/single_web_contents_dialog_manager_cocoa.h" #include "components/guest_view/browser/guest_view_base.h" -#include "components/web_modal/web_contents_modal_dialog_manager.h" #include "content/public/browser/browser_thread.h" using web_modal::WebContentsModalDialogManager; +std::unique_ptr<ConstrainedWindowMac> CreateAndShowWebModalDialogMac( + ConstrainedWindowMacDelegate* delegate, + content::WebContents* web_contents, + id<ConstrainedWindowSheet> sheet) { + ConstrainedWindowMac* window = + new ConstrainedWindowMac(delegate, web_contents, sheet); + window->ShowWebContentsModalDialog(); + return std::unique_ptr<ConstrainedWindowMac>(window); +} + +std::unique_ptr<ConstrainedWindowMac> CreateWebModalDialogMac( + ConstrainedWindowMacDelegate* delegate, + content::WebContents* web_contents, + id<ConstrainedWindowSheet> sheet) { + return std::unique_ptr<ConstrainedWindowMac>( + new ConstrainedWindowMac(delegate, web_contents, sheet)); +} + ConstrainedWindowMac::ConstrainedWindowMac( ConstrainedWindowMacDelegate* delegate, content::WebContents* web_contents, id<ConstrainedWindowSheet> sheet) - : delegate_(delegate) { + : delegate_(delegate), + sheet_([sheet retain]) { DCHECK(sheet); // |web_contents| may be embedded within a chain of nested GuestViews. If it // is, follow the chain of embedders to the outermost WebContents and use it. - web_contents = + web_contents_ = guest_view::GuestViewBase::GetTopLevelWebContents(web_contents); - auto manager = WebContentsModalDialogManager::FromWebContents(web_contents); - scoped_ptr<SingleWebContentsDialogManagerCocoa> native_manager( - new SingleWebContentsDialogManagerCocoa(this, sheet, manager)); - manager->ShowDialogWithManager([sheet sheetWindow], - std::move(native_manager)); + native_manager_.reset( + new SingleWebContentsDialogManagerCocoa(this, sheet_.get(), + GetDialogManager())); } ConstrainedWindowMac::~ConstrainedWindowMac() { CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); + native_manager_.reset(); DCHECK(!manager_); } +void ConstrainedWindowMac::ShowWebContentsModalDialog() { + scoped_ptr<SingleWebContentsDialogManagerCocoa> dialog_manager; + dialog_manager.reset(native_manager_.release()); + GetDialogManager()->ShowDialogWithManager( + [sheet_.get() sheetWindow], std::move(dialog_manager)); +} + void ConstrainedWindowMac::CloseWebContentsModalDialog() { if (manager_) manager_->Close(); @@ -49,3 +73,13 @@ if (delegate_) delegate_->OnConstrainedWindowClosed(this); } + +bool ConstrainedWindowMac::DialogWasShown() { + // If the dialog was shown, |native_manager_| would have been released. + return !native_manager_; +} + +WebContentsModalDialogManager* ConstrainedWindowMac::GetDialogManager() { + DCHECK(web_contents_); + return WebContentsModalDialogManager::FromWebContents(web_contents_); +}
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac_browsertest.mm b/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac_browsertest.mm index 8e6ceda..d8ffb1e 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac_browsertest.mm +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_mac_browsertest.mm
@@ -79,14 +79,15 @@ IN_PROC_BROWSER_TEST_F(ConstrainedWindowMacTest, ShowInInactiveTab) { // Show dialog in non active tab. NiceMock<ConstrainedWindowDelegateMock> delegate; - ConstrainedWindowMac dialog(&delegate, tab0_, sheet_); + std::unique_ptr<ConstrainedWindowMac> dialog( + CreateAndShowWebModalDialogMac(&delegate, tab0_, sheet_)); EXPECT_EQ(0.0, [sheet_window_ alphaValue]); // Switch to inactive tab. browser()->tab_strip_model()->ActivateTabAt(0, true); EXPECT_EQ(1.0, [sheet_window_ alphaValue]); - dialog.CloseWebContentsModalDialog(); + dialog->CloseWebContentsModalDialog(); } // If a tab has never been shown then the associated tab view for the web @@ -105,7 +106,8 @@ // Show dialog and verify that it's not visible yet. NiceMock<ConstrainedWindowDelegateMock> delegate; - ConstrainedWindowMac dialog(&delegate, tab2, sheet_); + std::unique_ptr<ConstrainedWindowMac> dialog( + CreateAndShowWebModalDialogMac(&delegate, tab2, sheet_)); EXPECT_FALSE([sheet_window_ isVisible]); // Activate the tab and verify that the constrained window is shown. @@ -114,25 +116,27 @@ EXPECT_TRUE([sheet_window_ isVisible]); EXPECT_EQ(1.0, [sheet_window_ alphaValue]); - dialog.CloseWebContentsModalDialog(); + dialog->CloseWebContentsModalDialog(); } // Test that adding a sheet disables tab dragging. IN_PROC_BROWSER_TEST_F(ConstrainedWindowMacTest, TabDragging) { NiceMock<ConstrainedWindowDelegateMock> delegate; - ConstrainedWindowMac dialog(&delegate, tab1_, sheet_); + std::unique_ptr<ConstrainedWindowMac> dialog( + CreateAndShowWebModalDialogMac(&delegate, tab1_, sheet_)); // Verify that the dialog disables dragging. EXPECT_TRUE([controller_ isTabDraggable:tab_view0_]); EXPECT_FALSE([controller_ isTabDraggable:tab_view1_]); - dialog.CloseWebContentsModalDialog(); + dialog->CloseWebContentsModalDialog(); } // Test that closing a browser window with a sheet works. IN_PROC_BROWSER_TEST_F(ConstrainedWindowMacTest, BrowserWindowClose) { NiceMock<ConstrainedWindowDelegateMock> delegate; - ConstrainedWindowMac dialog(&delegate, tab1_, sheet_); + std::unique_ptr<ConstrainedWindowMac> dialog( + CreateAndShowWebModalDialogMac(&delegate, tab1_, sheet_)); EXPECT_EQ(1.0, [sheet_window_ alphaValue]); // Close the browser window. @@ -146,7 +150,8 @@ // Test that closing a tab with a sheet works. IN_PROC_BROWSER_TEST_F(ConstrainedWindowMacTest, TabClose) { NiceMock<ConstrainedWindowDelegateMock> delegate; - ConstrainedWindowMac dialog(&delegate, tab1_, sheet_); + std::unique_ptr<ConstrainedWindowMac> dialog( + CreateAndShowWebModalDialogMac(&delegate, tab1_, sheet_)); EXPECT_EQ(1.0, [sheet_window_ alphaValue]); // Close the tab. @@ -160,7 +165,8 @@ // Test that the sheet is still visible after entering and exiting fullscreen. IN_PROC_BROWSER_TEST_F(ConstrainedWindowMacTest, BrowserWindowFullscreen) { NiceMock<ConstrainedWindowDelegateMock> delegate; - ConstrainedWindowMac dialog(&delegate, tab1_, sheet_); + std::unique_ptr<ConstrainedWindowMac> dialog( + CreateAndShowWebModalDialogMac(&delegate, tab1_, sheet_)); EXPECT_EQ(1.0, [sheet_window_ alphaValue]); // Toggle fullscreen twice: one for entering and one for exiting. @@ -180,5 +186,5 @@ EXPECT_EQ(1.0, [sheet_window_ alphaValue]); } - dialog.CloseWebContentsModalDialog(); + dialog->CloseWebContentsModalDialog(); }
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet.h b/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet.h index 4549556..cf24f7d 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet.h +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet.h
@@ -24,6 +24,8 @@ - (void)updateSheetPosition; +- (void)resizeWithNewSize:(NSSize)size; + @property(readonly, nonatomic) NSWindow* sheetWindow; @end
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet_controller_unittest.mm b/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet_controller_unittest.mm index 05038cf..6566d21 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet_controller_unittest.mm
@@ -59,6 +59,10 @@ - (void)updateSheetPosition { } +- (void)resizeWithNewSize:(NSSize)size { + // NOOP +} + - (NSWindow*)sheetWindow { return [alert_ window]; }
diff --git a/chrome/browser/ui/cocoa/constrained_window/constrained_window_web_dialog_sheet.mm b/chrome/browser/ui/cocoa/constrained_window/constrained_window_web_dialog_sheet.mm index 3c71f00..6e7d3f19 100644 --- a/chrome/browser/ui/cocoa/constrained_window/constrained_window_web_dialog_sheet.mm +++ b/chrome/browser/ui/cocoa/constrained_window/constrained_window_web_dialog_sheet.mm
@@ -27,4 +27,14 @@ [super updateSheetPosition]; } +- (void)resizeWithNewSize:(NSSize)size { + [customWindow_ setContentSize:size]; + + // self's updateSheetPosition() sets |customWindow_|'s contentSize to a + // fixed dialog size. Here, we want to resize to |size| instead. Use + // super rather than self to bypass the setContentSize() call for the fixed + // size. + [super updateSheetPosition]; +} + @end
diff --git a/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.h b/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.h index e895491e..55b55c9 100644 --- a/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.h +++ b/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.h
@@ -47,7 +47,7 @@ content::NotificationRegistrar registrar_; - scoped_ptr<ConstrainedWindowMac> window_; + std::unique_ptr<ConstrainedWindowMac> window_; base::scoped_nsobject<CollectedCookiesWindowController> sheet_controller_;
diff --git a/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.mm b/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.mm index 679c212..7c85ffe8 100644 --- a/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.mm +++ b/chrome/browser/ui/cocoa/content_settings/collected_cookies_mac.mm
@@ -66,8 +66,7 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:[sheet_controller_ window]]); - window_.reset(new ConstrainedWindowMac( - this, web_contents, sheet)); + window_ = CreateAndShowWebModalDialogMac(this, web_contents, sheet); } CollectedCookiesMac::~CollectedCookiesMac() {
diff --git a/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.h b/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.h index 73e04f7..19e5f3c 100644 --- a/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.h +++ b/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.h
@@ -39,7 +39,7 @@ private: scoped_refptr<extensions::DevicePermissionsPrompt::Prompt> prompt_; base::scoped_nsobject<DevicePermissionsViewController> view_controller_; - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; }; #endif // CHROME_BROWSER_UI_COCOA_EXTENSIONS_DEVICE_PERMISSIONS_DIALOG_CONTROLER_H_
diff --git a/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.mm b/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.mm index 6babaf28..881aff0 100644 --- a/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.mm +++ b/chrome/browser/ui/cocoa/extensions/device_permissions_dialog_controller.mm
@@ -33,8 +33,8 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:window]); - constrained_window_.reset( - new ConstrainedWindowMac(this, web_contents, sheet)); + constrained_window_ = + CreateAndShowWebModalDialogMac(this, web_contents, sheet); } DevicePermissionsDialogController::~DevicePermissionsDialogController() {
diff --git a/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.h b/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.h index 26143ea..455062c6 100644 --- a/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.h +++ b/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.h
@@ -57,7 +57,7 @@ ExtensionInstallPrompt::DoneCallback done_callback_; base::scoped_nsobject<ExtensionInstallViewController> view_controller_; - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; scoped_ptr<extensions::ExperienceSamplingEvent> sampling_event_; DISALLOW_COPY_AND_ASSIGN(ExtensionInstallDialogController);
diff --git a/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.mm b/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.mm index 826a3bc..4685a25b 100644 --- a/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.mm +++ b/chrome/browser/ui/cocoa/extensions/extension_install_dialog_controller.mm
@@ -60,8 +60,8 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:window]); - constrained_window_.reset(new ConstrainedWindowMac( - this, show_params->GetParentWebContents(), sheet)); + constrained_window_ = CreateAndShowWebModalDialogMac( + this, show_params->GetParentWebContents(), sheet); std::string event_name = ExperienceSamplingEvent::kExtensionInstallDialog; event_name.append(
diff --git a/chrome/browser/ui/cocoa/extensions/extension_installed_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/extensions/extension_installed_bubble_controller_unittest.mm index 12c0018..6ce3866 100644 --- a/chrome/browser/ui/cocoa/extensions/extension_installed_bubble_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/extensions/extension_installed_bubble_controller_unittest.mm
@@ -29,6 +29,7 @@ #include "content/public/browser/web_contents.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" +#include "extensions/common/feature_switch.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/value_builder.h" #import "third_party/ocmock/OCMock/OCMock.h" @@ -288,6 +289,9 @@ // Test the layout of a bubble for an unpacked extension (which is not syncable) // and verify that the page action preview is enabled. TEST_F(ExtensionInstalledBubbleControllerTest, BubbleLayoutPageActionUnpacked) { + // Tests legacy behavior. + extensions::FeatureSwitch::ScopedOverride extension_action_override( + extensions::FeatureSwitch::extension_action_redesign(), false); // Page actions need a web contents (for the location bar to not break). AddWebContents();
diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h index 9b3553a..6faeff65 100644 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h +++ b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.h
@@ -69,7 +69,7 @@ CGFloat CreateCheckboxSeparator(CGFloat y_pos, NSString* header); MediaGalleriesDialogController* controller_; // weak - scoped_ptr<ConstrainedWindowMac> window_; + std::unique_ptr<ConstrainedWindowMac> window_; // The alert that the dialog is being displayed as. base::scoped_nsobject<ConstrainedWindowAlert> alert_;
diff --git a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm index 01cf67c0..e3fe7a8 100644 --- a/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm +++ b/chrome/browser/ui/cocoa/extensions/media_galleries_dialog_cocoa.mm
@@ -102,8 +102,8 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:[alert_ window]]); - window_.reset(new ConstrainedWindowMac( - this, controller->WebContents(), sheet)); + window_ = CreateAndShowWebModalDialogMac( + this, controller->WebContents(), sheet); } }
diff --git a/chrome/browser/ui/cocoa/login_prompt_cocoa.mm b/chrome/browser/ui/cocoa/login_prompt_cocoa.mm index 2c24253b..4d72782 100644 --- a/chrome/browser/ui/cocoa/login_prompt_cocoa.mm +++ b/chrome/browser/ui/cocoa/login_prompt_cocoa.mm
@@ -80,8 +80,8 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:[sheet_controller_ window]]); - constrained_window_.reset(new ConstrainedWindowMac( - this, requesting_contents, sheet)); + constrained_window_ = CreateAndShowWebModalDialogMac( + this, requesting_contents, sheet); NotifyAuthNeeded(); } @@ -126,7 +126,7 @@ // The Cocoa controller of the GUI. base::scoped_nsobject<LoginHandlerSheet> sheet_controller_; - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; DISALLOW_COPY_AND_ASSIGN(LoginHandlerMac); };
diff --git a/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.h b/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.h index d56dfdd..b4f82d4 100644 --- a/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.h +++ b/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.h
@@ -8,7 +8,6 @@ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h" @@ -42,7 +41,7 @@ private: void PerformClose(); - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; base::scoped_nsobject<OneClickSigninViewController> view_controller_; };
diff --git a/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.mm b/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.mm index f0156f2..a8f9a84 100644 --- a/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.mm +++ b/chrome/browser/ui/cocoa/one_click_signin_dialog_controller.mm
@@ -30,15 +30,15 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:window]); - constrained_window_.reset(new ConstrainedWindowMac( - this, web_contents, sheet)); + constrained_window_ = + CreateAndShowWebModalDialogMac(this, web_contents, sheet); } OneClickSigninDialogController::~OneClickSigninDialogController() { } void OneClickSigninDialogController::OnConstrainedWindowClosed( - ConstrainedWindowMac* window) { + ConstrainedWindowMac* window) { [view_controller_ viewWillClose]; base::MessageLoop::current()->DeleteSoon(FROM_HERE, this); }
diff --git a/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.h b/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.h index 6f27470..192f6ce0 100644 --- a/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.h +++ b/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.h
@@ -13,7 +13,6 @@ #include "base/compiler_specific.h" #include "base/mac/scoped_nsobject.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/cocoa/constrained_window/constrained_window_mac.h" #include "chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_view_controller.h" @@ -60,7 +59,7 @@ base::scoped_nsobject<ProfileSigninConfirmationViewController> controller_; // The constrained window that contains the dialog view. - scoped_ptr<ConstrainedWindowMac> window_; + std::unique_ptr<ConstrainedWindowMac> window_; DISALLOW_COPY_AND_ASSIGN(ProfileSigninConfirmationDialogCocoa); };
diff --git a/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.mm b/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.mm index a46b4eb..e600717 100644 --- a/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.mm +++ b/chrome/browser/ui/cocoa/profiles/profile_signin_confirmation_dialog_cocoa.mm
@@ -59,7 +59,7 @@ [[window contentView] addSubview:[controller_ view]]; base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:window]); - window_.reset(new ConstrainedWindowMac(this, web_contents, sheet)); + window_ = CreateAndShowWebModalDialogMac(this, web_contents, sheet); } ProfileSigninConfirmationDialogCocoa::~ProfileSigninConfirmationDialogCocoa() {
diff --git a/chrome/browser/ui/cocoa/profiles/user_manager_mac.h b/chrome/browser/ui/cocoa/profiles/user_manager_mac.h index dd1c1c6c..d8346b8 100644 --- a/chrome/browser/ui/cocoa/profiles/user_manager_mac.h +++ b/chrome/browser/ui/cocoa/profiles/user_manager_mac.h
@@ -9,7 +9,6 @@ #include "base/mac/scoped_nsobject.h" #include "base/macros.h" -#include "base/memory/scoped_ptr.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_window.h"
diff --git a/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm b/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm index 48a02249..cdae282 100644 --- a/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm +++ b/chrome/browser/ui/cocoa/profiles/user_manager_mac.mm
@@ -167,7 +167,7 @@ std::string emailAddress_; content::WebContents* webContents_; scoped_ptr<ReauthDialogDelegate> webContentsDelegate_; - scoped_ptr<ConstrainedWindowMac> constrained_window_; + std::unique_ptr<ConstrainedWindowMac> constrained_window_; scoped_ptr<content::WebContents> reauthWebContents_; } - (id)initWithProfile:(Profile*)profile @@ -203,9 +203,9 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:[self window]]); - constrained_window_.reset( - new ConstrainedWindowMac( - webContentsDelegate_.get(), webContents_, sheet)); + constrained_window_ = + CreateAndShowWebModalDialogMac( + webContentsDelegate_.get(), webContents_, sheet); // The close button needs to call CloseWebContentsModalDialog() on the // constrained window isntead of just [window close] so grab a reference to
diff --git a/chrome/browser/ui/cocoa/single_web_contents_dialog_manager_cocoa.mm b/chrome/browser/ui/cocoa/single_web_contents_dialog_manager_cocoa.mm index 6b1d507..1cbaec8 100644 --- a/chrome/browser/ui/cocoa/single_web_contents_dialog_manager_cocoa.mm +++ b/chrome/browser/ui/cocoa/single_web_contents_dialog_manager_cocoa.mm
@@ -58,8 +58,12 @@ [[ConstrainedWindowSheetController controllerForSheet:sheet_] closeSheet:sheet_]; client_->set_manager(nullptr); + + bool dialog_was_open = client_->DialogWasShown(); client_->OnDialogClosing(); // |client_| might delete itself here. - delegate_->WillClose(dialog()); // Deletes |this|. + + if (dialog_was_open) + delegate_->WillClose(dialog()); // Deletes |this|. } void SingleWebContentsDialogManagerCocoa::Focus() {
diff --git a/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.h b/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.h index f1fe2e3..4e3b307b 100644 --- a/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.h +++ b/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.h
@@ -35,7 +35,7 @@ // A C++ object to bridge SSLClientAuthObserver notifications to us. scoped_ptr<SSLClientAuthObserverCocoaBridge> observer_; base::scoped_nsobject<SFChooseIdentityPanel> panel_; - scoped_ptr<ConstrainedWindowMac> constrainedWindow_; + std::unique_ptr<ConstrainedWindowMac> constrainedWindow_; base::scoped_nsobject<NSWindow> overlayWindow_; BOOL closePending_; // A copy of the sheet's frame used to restore on show.
diff --git a/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.mm b/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.mm index 8c7d66d..4a06708 100644 --- a/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.mm +++ b/chrome/browser/ui/cocoa/ssl_client_certificate_selector_cocoa.mm
@@ -179,8 +179,8 @@ CFRelease(sslPolicy); } - constrainedWindow_.reset( - new ConstrainedWindowMac(observer_.get(), webContents, self)); + constrainedWindow_ = + CreateAndShowWebModalDialogMac(observer_.get(), webContents, self); observer_->StartObserving(); } @@ -260,6 +260,10 @@ // NOOP } +- (void)resizeWithNewSize:(NSSize)size { + // NOOP +} + - (NSWindow*)sheetWindow { return panel_; }
diff --git a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h b/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h index 1eed74f..c7e32951 100644 --- a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h +++ b/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.h
@@ -48,7 +48,7 @@ bool closing_; - scoped_ptr<ConstrainedWindowMac> window_; + std::unique_ptr<ConstrainedWindowMac> window_; scoped_ptr<TabModalConfirmDialogDelegate> delegate_; base::scoped_nsobject<ConstrainedWindowAlert> alert_; base::scoped_nsobject<TabModalConfirmDialogMacBridge> bridge_;
diff --git a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm b/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm index 6935ce1..e0e7f547 100644 --- a/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm +++ b/chrome/browser/ui/cocoa/tab_modal_confirm_dialog_mac.mm
@@ -94,7 +94,7 @@ base::scoped_nsobject<CustomConstrainedWindowSheet> sheet( [[CustomConstrainedWindowSheet alloc] initWithCustomWindow:[alert_ window]]); - window_.reset(new ConstrainedWindowMac(this, web_contents, sheet)); + window_ = CreateAndShowWebModalDialogMac(this, web_contents, sheet); delegate_->set_close_delegate(this); }
diff --git a/chrome/browser/ui/cocoa/web_contents_modal_dialog_manager_views_mac.mm b/chrome/browser/ui/cocoa/web_contents_modal_dialog_manager_views_mac.mm index 1eefbd15..31f057fa 100644 --- a/chrome/browser/ui/cocoa/web_contents_modal_dialog_manager_views_mac.mm +++ b/chrome/browser/ui/cocoa/web_contents_modal_dialog_manager_views_mac.mm
@@ -96,6 +96,10 @@ [customWindow_ setFrameOrigin:origin]; } +- (void)resizeWithNewSize:(NSSize)size { + // NOOP +} + - (NSWindow*)sheetWindow { return customWindow_; }
diff --git a/chrome/browser/ui/ime/ime_window.cc b/chrome/browser/ui/ime/ime_window.cc index a8d1a75..993ffa2 100644 --- a/chrome/browser/ui/ime/ime_window.cc +++ b/chrome/browser/ui/ime/ime_window.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/ui/ime/ime_window_observer.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" @@ -22,12 +23,16 @@ // The vertical margin between the cursor and the follow-cursor window. const int kFollowCursorMargin = 3; +// The offset from the left of follow cursor window to the left of cursor. +const int kFollowCursorOffset = 32; + } // namespace namespace ui { ImeWindow::ImeWindow(Profile* profile, const extensions::Extension* extension, + content::RenderFrameHost* opener_render_frame_host, const std::string& url, Mode mode, const gfx::Rect& bounds) @@ -36,7 +41,7 @@ title_ = extension->name(); icon_.reset(new extensions::IconImage( profile, extension, extensions::IconsInfo::GetIcons(extension), - extension_misc::EXTENSION_ICON_SMALL, gfx::ImageSkia(), this)); + extension_misc::EXTENSION_ICON_BITTY, gfx::ImageSkia(), this)); } registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, @@ -46,9 +51,19 @@ if (!gurl.is_valid()) gurl = extension->GetResourceURL(url); - content::SiteInstance* instance = - content::SiteInstance::CreateForURL(profile, gurl); - content::WebContents::CreateParams create_params(profile, instance); + content::SiteInstance* site_instance = opener_render_frame_host + ? opener_render_frame_host->GetSiteInstance() : nullptr; + if (!site_instance || + site_instance->GetSiteURL().GetOrigin() != gurl.GetOrigin()) { + site_instance = content::SiteInstance::CreateForURL(profile, gurl); + } + content::WebContents::CreateParams create_params(profile, site_instance); + if (opener_render_frame_host) { + create_params.opener_render_process_id = + opener_render_frame_host->GetProcess()->GetID(); + create_params.opener_render_frame_id = + opener_render_frame_host->GetRoutingID(); + } web_contents_.reset(content::WebContents::Create(create_params)); web_contents_->SetDelegate(this); content::OpenURLParams params(gurl, content::Referrer(), SINGLETON_TAB, @@ -85,13 +100,13 @@ int screen_height = screen_bounds.height(); int width = window_bounds.width(); int height = window_bounds.height(); - // By default, aligns the left of the window to the left of the cursor, and - // aligns the top of the window to the bottom of the cursor. + // By default, aligns the left of the window client area to the left of the + // cursor, and aligns the top of the window to the bottom of the cursor. // If the right of the window would go beyond the screen bounds, aligns the // right of the window to the screen bounds. // If the bottom of the window would go beyond the screen bounds, aligns the // bottom of the window to the cursor top. - int x = cursor_bounds.x(); + int x = cursor_bounds.x() - kFollowCursorOffset; int y = cursor_bounds.y() + cursor_bounds.height() + kFollowCursorMargin; if (width < screen_width && x + width > screen_width) x = screen_width - width; @@ -155,8 +170,20 @@ void ImeWindow::MoveContents(content::WebContents* source, const gfx::Rect& pos) { - if (native_window_) + if (!native_window_) + return; + + if (mode_ == NORMAL) { native_window_->SetBounds(pos); + return; + } + + // Follow-cursor window needs to remain the x/y and only allow JS to + // change the size. + gfx::Rect bounds = native_window_->GetBounds(); + bounds.set_width(pos.width()); + bounds.set_height(pos.height()); + native_window_->SetBounds(bounds); } bool ImeWindow::IsPopupOrPanel(const content::WebContents* source) const {
diff --git a/chrome/browser/ui/ime/ime_window.h b/chrome/browser/ui/ime/ime_window.h index 77ffd24d..7faec32 100644 --- a/chrome/browser/ui/ime/ime_window.h +++ b/chrome/browser/ui/ime/ime_window.h
@@ -23,6 +23,7 @@ class Profile; namespace content { +class RenderFrameHost; class WebContents; } @@ -58,8 +59,11 @@ // Takes |url| as string instead of GURL because resolving GURL requires // |extension|. As the client code already passes in |extension|, it'd be // better to simply the client code. + // |opener_render_frame_host| is the RenderFrameHost from where the IME window + // is opened so that the security origin can be correctly set. ImeWindow(Profile* profile, const extensions::Extension* extension, + content::RenderFrameHost* opener_render_frame_host, const std::string& url, Mode mode, const gfx::Rect& bounds);
diff --git a/chrome/browser/ui/input_method/input_method_engine.cc b/chrome/browser/ui/input_method/input_method_engine.cc index 6966f31..6d5a1595 100644 --- a/chrome/browser/ui/input_method/input_method_engine.cc +++ b/chrome/browser/ui/input_method/input_method_engine.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/input_method/input_method_engine.h" +#include "content/public/browser/render_frame_host.h" #include "ui/base/ime/composition_text.h" #include "ui/base/ime/ime_bridge.h" #include "ui/base/ime/ime_input_context_handler_interface.h" @@ -44,11 +45,13 @@ return extension_id_; } -int InputMethodEngine::CreateImeWindow(const extensions::Extension* extension, - const std::string& url, - ui::ImeWindow::Mode mode, - const gfx::Rect& bounds, - std::string* error) { +int InputMethodEngine::CreateImeWindow( + const extensions::Extension* extension, + content::RenderFrameHost* render_frame_host, + const std::string& url, + ui::ImeWindow::Mode mode, + const gfx::Rect& bounds, + std::string* error) { if (mode == ui::ImeWindow::FOLLOW_CURSOR) { if (follow_cursor_window_) { *error = kErrorFollowCursorWindowExists; @@ -67,8 +70,8 @@ } // ui::ImeWindow manages its own lifetime. - ui::ImeWindow* ime_window = - new ui::ImeWindow(profile_, extension, url, mode, bounds); + ui::ImeWindow* ime_window = new ui::ImeWindow( + profile_, extension, render_frame_host, url, mode, bounds); ime_window->AddObserver(this); ime_window->Show(); if (mode == ui::ImeWindow::FOLLOW_CURSOR) {
diff --git a/chrome/browser/ui/input_method/input_method_engine.h b/chrome/browser/ui/input_method/input_method_engine.h index 05586d9d..14e5ac5e 100644 --- a/chrome/browser/ui/input_method/input_method_engine.h +++ b/chrome/browser/ui/input_method/input_method_engine.h
@@ -12,6 +12,10 @@ #include "chrome/browser/ui/ime/ime_window_observer.h" #include "chrome/browser/ui/input_method/input_method_engine_base.h" +namespace content { +class RenderFrameHost; +} // namespace content + namespace input_method { class InputMethodEngine : public InputMethodEngineBase, @@ -30,6 +34,7 @@ // Creates and shows the IME window. // Returns 0 for errors and |error| will contains the error message. int CreateImeWindow(const extensions::Extension* extension, + content::RenderFrameHost* render_frame_host, const std::string& url, ui::ImeWindow::Mode mode, const gfx::Rect& bounds,
diff --git a/chrome/browser/ui/libgtk2ui/gtk2_ui.h b/chrome/browser/ui/libgtk2ui/gtk2_ui.h index 2e6210a0..3dda6d2 100644 --- a/chrome/browser/ui/libgtk2ui/gtk2_ui.h +++ b/chrome/browser/ui/libgtk2ui/gtk2_ui.h
@@ -66,7 +66,7 @@ int* style_out, gfx::FontRenderParams* params_out) const override; - // ui::LinuxShellDialog: + // ui::ShellDialogLinux: ui::SelectFileDialog* CreateSelectFileDialog( ui::SelectFileDialog::Listener* listener, ui::SelectFilePolicy* policy) const override;
diff --git a/chrome/browser/ui/startup/startup_browser_creator.cc b/chrome/browser/ui/startup/startup_browser_creator.cc index a03c8e0..3eb74b0 100644 --- a/chrome/browser/ui/startup/startup_browser_creator.cc +++ b/chrome/browser/ui/startup/startup_browser_creator.cc
@@ -87,6 +87,7 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chromeos/chromeos_switches.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "components/user_manager/user_manager.h" #endif @@ -662,7 +663,9 @@ // possible. We should instead cleanly exit and go back to the OOBE screen, // where we will launch again after the timeout has expired. if (chromeos::DemoAppLauncher::IsDemoAppSession( - command_line.GetSwitchValueASCII(chromeos::switches::kLoginUser))) { + cryptohome::Identification::FromString( + command_line.GetSwitchValueASCII(chromeos::switches::kLoginUser)) + .GetAccountId())) { chrome::AttemptUserExit(); return false; }
diff --git a/chrome/browser/ui/toolbar/app_menu_model.cc b/chrome/browser/ui/toolbar/app_menu_model.cc index 62db93dd..070381126 100644 --- a/chrome/browser/ui/toolbar/app_menu_model.cc +++ b/chrome/browser/ui/toolbar/app_menu_model.cc
@@ -880,8 +880,9 @@ void AppMenuModel::CreateActionToolbarOverflowMenu() { // We only add the extensions overflow container if there are any icons that // aren't shown in the main container. - // browser_->window() can return null during startup. - if (browser_->window() && + // browser_->window() can return null during startup, and + // GetToolbarActionsBar() can be null in testing. + if (browser_->window() && browser_->window()->GetToolbarActionsBar() && browser_->window()->GetToolbarActionsBar()->NeedsOverflow()) { #if defined(OS_MACOSX) // There's a bug in AppKit menus, where if a menu item with a custom view
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_bar_unittest.cc b/chrome/browser/ui/toolbar/toolbar_actions_bar_unittest.cc index 64ef450..a84530b 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_bar_unittest.cc +++ b/chrome/browser/ui/toolbar/toolbar_actions_bar_unittest.cc
@@ -96,10 +96,8 @@ ToolbarActionsBarUnitTest::~ToolbarActionsBarUnitTest() {} void ToolbarActionsBarUnitTest::SetUp() { - if (use_redesign_) { - redesign_switch_.reset(new extensions::FeatureSwitch::ScopedOverride( - extensions::FeatureSwitch::extension_action_redesign(), true)); - } + redesign_switch_.reset(new extensions::FeatureSwitch::ScopedOverride( + extensions::FeatureSwitch::extension_action_redesign(), use_redesign_)); BrowserWithTestWindowTest::SetUp(); // The toolbar typically displays extension icons, so create some extension
diff --git a/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc b/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc index ad31804..0523060 100644 --- a/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc +++ b/chrome/browser/ui/toolbar/toolbar_actions_model_unittest.cc
@@ -419,37 +419,26 @@ TEST_F(ToolbarActionsModelUnitTest, BasicToolbarActionsModelTest) { Init(); - // Load an extension with no browser action. - scoped_refptr<const extensions::Extension> extension1 = - extensions::extension_action_test_util::CreateActionExtension( - "no_action", extensions::extension_action_test_util::NO_ACTION); - ASSERT_TRUE(AddExtension(extension1)); - - // This extension should not be in the model (has no browser action). - EXPECT_EQ(0u, observer()->inserted_count()); - EXPECT_EQ(0u, num_toolbar_items()); - EXPECT_EQ(std::string(), GetActionIdAtIndex(0u)); - // Load an extension with a browser action. - scoped_refptr<const extensions::Extension> extension2 = + scoped_refptr<const extensions::Extension> extension = extensions::extension_action_test_util::CreateActionExtension( "browser_action", extensions::extension_action_test_util::BROWSER_ACTION); - ASSERT_TRUE(AddExtension(extension2)); + ASSERT_TRUE(AddExtension(extension)); // We should now find our extension in the model. EXPECT_EQ(1u, observer()->inserted_count()); EXPECT_EQ(1u, num_toolbar_items()); - EXPECT_EQ(extension2->id(), GetActionIdAtIndex(0u)); + EXPECT_EQ(extension->id(), GetActionIdAtIndex(0u)); // Should be a no-op, but still fires the events. - toolbar_model()->MoveActionIcon(extension2->id(), 0); + toolbar_model()->MoveActionIcon(extension->id(), 0); EXPECT_EQ(1u, observer()->moved_count()); EXPECT_EQ(1u, num_toolbar_items()); - EXPECT_EQ(extension2->id(), GetActionIdAtIndex(0u)); + EXPECT_EQ(extension->id(), GetActionIdAtIndex(0u)); // Remove the extension and verify. - ASSERT_TRUE(RemoveExtension(extension2)); + ASSERT_TRUE(RemoveExtension(extension)); EXPECT_EQ(1u, observer()->removed_count()); EXPECT_EQ(0u, num_toolbar_items()); EXPECT_EQ(std::string(), GetActionIdAtIndex(0u)); @@ -910,7 +899,9 @@ // Test that, in the absence of the extension-action-redesign switch, the // model only contains extensions with browser actions and component actions. -TEST_F(ToolbarActionsModelUnitTest, TestToolbarExtensionTypesNoSwitch) { +TEST_F(ToolbarActionsModelUnitTest, TestToolbarExtensionTypesDisabledSwitch) { + extensions::FeatureSwitch::ScopedOverride enable_redesign( + extensions::FeatureSwitch::extension_action_redesign(), false); Init(); ASSERT_TRUE(AddActionExtensions()); @@ -921,7 +912,7 @@ // Test that, with the extension-action-redesign switch, the model contains // all types of extensions, except those which should not be displayed on the // toolbar (like component extensions). -TEST_F(ToolbarActionsModelUnitTest, TestToolbarExtensionTypesSwitch) { +TEST_F(ToolbarActionsModelUnitTest, TestToolbarExtensionTypesEnabledSwitch) { extensions::FeatureSwitch::ScopedOverride enable_redesign( extensions::FeatureSwitch::extension_action_redesign(), true); Init(); @@ -977,6 +968,8 @@ // Test that hiding actions on the toolbar results in their removal from the // model when the redesign switch is not enabled. TEST_F(ToolbarActionsModelUnitTest, ActionsToolbarActionsVisibilityNoSwitch) { + extensions::FeatureSwitch::ScopedOverride enable_redesign( + extensions::FeatureSwitch::extension_action_redesign(), false); Init(); extensions::ExtensionActionAPI* action_api =
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc index b62d4091..ec40da0 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc
@@ -23,11 +23,18 @@ #include "ui/base/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/base/theme_provider.h" +#include "ui/gfx/color_palette.h" #include "ui/gfx/image/image.h" +#include "ui/gfx/paint_vector_icon.h" +#include "ui/gfx/vector_icons_public.h" #include "ui/resources/grit/ui_resources.h" #include "ui/views/background.h" #include "ui/views/resources/grit/views_resources.h" +#if defined(OS_WIN) +#include "base/win/windows_version.h" +#endif + BrowserNonClientFrameView::BrowserNonClientFrameView(BrowserFrame* frame, BrowserView* browser_view) : frame_(frame), @@ -49,6 +56,20 @@ void BrowserNonClientFrameView::OnBrowserViewInitViewsComplete() {} +gfx::ImageSkia BrowserNonClientFrameView::GetOTRAvatarIcon() const { + if (!ui::MaterialDesignController::IsModeMaterial()) + return *GetThemeProviderForProfile()->GetImageSkiaNamed(IDR_OTR_ICON); + SkColor icon_color = SK_ColorWHITE; +#if defined(OS_WIN) + // On Windows 10+, we assume the native frame color is white. + // TODO(pkasting): Read the correct frame color from the registry or APIs. + if (GetWidget() && GetWidget()->ShouldUseNativeFrame() && + (base::win::GetVersion() >= base::win::VERSION_WIN10)) + icon_color = gfx::kChromeIconGrey; +#endif + return gfx::CreateVectorIcon(gfx::VectorIconId::INCOGNITO, 24, icon_color); +} + void BrowserNonClientFrameView::UpdateToolbar() { } @@ -62,29 +83,12 @@ void BrowserNonClientFrameView::VisibilityChanged(views::View* starting_from, bool is_visible) { - if (!is_visible) - return; - -#if defined(OS_CHROMEOS) - // On ChromeOS we always need to give the old avatar button a chance to update - // in case we're in a teleported window. On desktop, the old avatar button - // only shows up when in incognito mode. - UpdateOldAvatarButton(); - OnProfileAvatarChanged(base::FilePath()); -#else - if (!browser_view_->IsRegularOrGuestSession()) { - // The first time UpdateOldAvatarButton() is called the window is not - // visible so DrawTaskBarDecoration() has no effect. Therefore we need to - // call it again once the window is visible. - UpdateOldAvatarButton(); - } - - // Call OnProfileAvatarChanged() in this case to make sure the task bar icon - // is correctly updated. Guest profiles don't badge the icon so no need to do - // this in guest mode. - if (!browser_view_->IsGuestSession()) + // UpdateTaskbarDecoration() calls DrawTaskbarDecoration(), but that does + // nothing if the window is not visible. So even if we've already gotten the + // up-to-date decoration, we need to run the update procedure again here when + // the window becomes visible. + if (is_visible) OnProfileAvatarChanged(base::FilePath()); -#endif } bool BrowserNonClientFrameView::ShouldPaintAsThemed() const { @@ -167,11 +171,9 @@ bool should_show_avatar_menu = avatar_button_ || AvatarMenu::ShouldShowAvatarMenu(); - if (!AvatarMenuButton::GetAvatarImages(browser_view_, should_show_avatar_menu, - &avatar, &taskbar_badge_avatar, - &is_rectangle)) { + if (!AvatarMenuButton::GetAvatarImages(this, should_show_avatar_menu, &avatar, + &taskbar_badge_avatar, &is_rectangle)) return; - } // Disable the menu when we should not show the menu. if (avatar_button_ && !AvatarMenu::ShouldShowAvatarMenu()) @@ -182,26 +184,26 @@ void BrowserNonClientFrameView::OnProfileAdded( const base::FilePath& profile_path) { - UpdateTaskbarDecoration(); - UpdateAvatar(); + OnProfileAvatarChanged(profile_path); } void BrowserNonClientFrameView::OnProfileWasRemoved( const base::FilePath& profile_path, const base::string16& profile_name) { - UpdateTaskbarDecoration(); - UpdateAvatar(); + OnProfileAvatarChanged(profile_path); } void BrowserNonClientFrameView::OnProfileAvatarChanged( const base::FilePath& profile_path) { UpdateTaskbarDecoration(); - // Profile avatars are only displayed in incognito or on ChromeOS teleported - // windows. -#if !defined(OS_CHROMEOS) - if (!browser_view()->IsGuestSession() && browser_view()->IsOffTheRecord()) -#endif - UpdateOldAvatarButton(); + UpdateAvatar(); +} + +const ui::ThemeProvider* +BrowserNonClientFrameView::GetThemeProviderForProfile() const { + // Because the frame's accessor reads the ThemeProvider from the profile and + // not the widget, it can be called even before we're in a view hierarchy. + return frame_->GetThemeProvider(); } void BrowserNonClientFrameView::UpdateTaskbarDecoration() { @@ -213,7 +215,7 @@ // the returned images are not initialized. This can happen if the user // deletes the current profile. if (AvatarMenuButton::GetAvatarImages( - browser_view_, AvatarMenu::ShouldShowAvatarMenu(), &avatar, + this, AvatarMenu::ShouldShowAvatarMenu(), &avatar, &taskbar_badge_avatar, &is_rectangle)) { // For popups and panels which don't have the avatar button, we still // need to draw the taskbar decoration. Even though we have an icon on the
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view.h b/chrome/browser/ui/views/frame/browser_non_client_frame_view.h index a7b4578..f7f277b 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view.h +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view.h
@@ -42,6 +42,9 @@ // Returns the amount that the theme background should be inset. virtual int GetThemeBackgroundXInset() const = 0; + // Retrieves the icon to use in the frame to indicate an OTR window. + gfx::ImageSkia GetOTRAvatarIcon() const; + // Updates the throbber. virtual void UpdateThrobber(bool running) = 0; @@ -83,12 +86,16 @@ void UpdateOldAvatarButton(); private: - // Overriden from ProfileAttributesStorage::Observer. + // ProfileAttributesStorage::Observer: void OnProfileAdded(const base::FilePath& profile_path) override; void OnProfileWasRemoved(const base::FilePath& profile_path, const base::string16& profile_name) override; void OnProfileAvatarChanged(const base::FilePath& profile_path) override; + // Gets a theme provider that should be non-null even before we're added to a + // view hierarchy. + const ui::ThemeProvider* GetThemeProviderForProfile() const; + // Draws a taskbar icon if avatars are enabled, erases it otherwise. void UpdateTaskbarDecoration(); @@ -101,6 +108,8 @@ // Menu button that displays the incognito icon. May be null for some frame // styles. TODO(anthonyvd): simplify/rename. AvatarMenuButton* avatar_button_ = nullptr; + + DISALLOW_COPY_AND_ASSIGN(BrowserNonClientFrameView); }; namespace chrome {
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc index a41a8939e..7904459 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_ash.cc
@@ -419,8 +419,8 @@ int BrowserNonClientFrameViewAsh::GetTabStripLeftInset() const { const gfx::Insets insets(GetLayoutInsets(AVATAR_ICON)); - const int avatar_right = avatar_button() ? - (insets.left() + browser_view()->GetOTRAvatarIcon().width()) : 0; + const int avatar_right = + avatar_button() ? (insets.left() + GetOTRAvatarIcon().width()) : 0; return avatar_right + insets.right(); } @@ -457,7 +457,7 @@ DCHECK(browser_view()->IsTabStripVisible()); #endif - const gfx::ImageSkia incognito_icon = browser_view()->GetOTRAvatarIcon(); + const gfx::ImageSkia incognito_icon = GetOTRAvatarIcon(); const gfx::Insets avatar_insets = GetLayoutInsets(AVATAR_ICON); const int avatar_bottom = GetTopInset(false) + browser_view()->GetTabStripHeight() - avatar_insets.bottom();
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_mus.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_mus.cc index da75bb99..f6d60c8 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_mus.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_mus.cc
@@ -411,9 +411,7 @@ int BrowserNonClientFrameViewMus::GetTabStripLeftInset() const { const gfx::Insets insets(GetLayoutInsets(AVATAR_ICON)); const int avatar_right = - avatar_button() - ? (insets.left() + browser_view()->GetOTRAvatarIcon().width()) - : 0; + avatar_button() ? (insets.left() + GetOTRAvatarIcon().width()) : 0; return avatar_right + insets.right() + frame_values().normal_insets.left(); } @@ -462,7 +460,7 @@ // ChromeOS shows avatar on V1 app. DCHECK(browser_view()->IsTabStripVisible()); #endif - gfx::ImageSkia incognito_icon = browser_view()->GetOTRAvatarIcon(); + gfx::ImageSkia incognito_icon = GetOTRAvatarIcon(); gfx::Insets avatar_insets = GetLayoutInsets(AVATAR_ICON); int avatar_bottom = GetTopInset(false) + browser_view()->GetTabStripHeight() - avatar_insets.bottom();
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 303a31b..b772e9f 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -139,10 +139,8 @@ #include "ui/gfx/canvas.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/rect_conversions.h" -#include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/scoped_canvas.h" #include "ui/gfx/screen.h" -#include "ui/gfx/vector_icons_public.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/textfield/textfield.h" @@ -166,7 +164,6 @@ #endif #if defined(OS_WIN) -#include "base/win/windows_version.h" #include "chrome/browser/jumplist_win.h" #include "ui/gfx/color_palette.h" #include "ui/native_theme/native_theme_dark_win.h" @@ -673,24 +670,6 @@ return browser_->tab_strip_model()->GetActiveWebContents(); } -gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const { - if (ui::MaterialDesignController::IsModeMaterial()) { - SkColor icon_color = SK_ColorWHITE; -#if defined(OS_WIN) - // On Windows 10+, we assume the native frame color is white. - // TODO(pkasting): Read the correct frame color from the registry or APIs. - if (GetWidget() && GetWidget()->ShouldUseNativeFrame() && - (base::win::GetVersion() >= base::win::VERSION_WIN10)) - icon_color = gfx::kChromeIconGrey; -#endif - return gfx::CreateVectorIcon(gfx::VectorIconId::INCOGNITO, 24, icon_color); - } - - // GetThemeProvider() can return null if this view is not yet part of the - // widget hierarchy, but the frame's theme provider is always valid. - return *frame_->GetThemeProvider()->GetImageSkiaNamed(IDR_OTR_ICON); -} - /////////////////////////////////////////////////////////////////////////////// // BrowserView, BrowserWindow implementation:
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index 94a8cf91..685a6732 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -225,9 +225,6 @@ // move it to a WindowDelegate subclass. content::WebContents* GetActiveWebContents() const; - // Retrieves the icon to use in the frame to indicate an OTR window. - gfx::ImageSkia GetOTRAvatarIcon() const; - // Returns true if the Browser object associated with this BrowserView is a // tabbed-type window (i.e. a browser window, not an app or popup). bool IsBrowserTypeNormal() const {
diff --git a/chrome/browser/ui/views/frame/glass_browser_frame_view.cc b/chrome/browser/ui/views/frame/glass_browser_frame_view.cc index 8cb28d8b..3d37c785 100644 --- a/chrome/browser/ui/views/frame/glass_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/glass_browser_frame_view.cc
@@ -529,15 +529,7 @@ void GlassBrowserFrameView::LayoutIncognitoIcon() { const bool md = ui::MaterialDesignController::IsModeMaterial(); const gfx::Insets insets(GetLayoutInsets(AVATAR_ICON)); - gfx::Size size; - // During startup it's possible to reach here before the browser view has been - // added to the view hierarchy. In this case it won't have a widget and thus - // can't access the theme provider, which is required to get the incognito - // icon. Use an empty size in this case, which will still place the tabstrip - // at the correct coordinates for a non-incognito window. We should get - // another layout call after the browser view has a widget anyway. - if (browser_view()->GetWidget()) - size = browser_view()->GetOTRAvatarIcon().size(); + const gfx::Size size(GetOTRAvatarIcon().size()); int x = NonClientBorderThickness(false); // In RTL, the icon needs to start after the caption buttons. if (base::i18n::IsRTL()) {
diff --git a/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc b/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc index 4b32171b..53e69df1 100644 --- a/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/opaque_browser_frame_view.cc
@@ -392,7 +392,7 @@ } gfx::ImageSkia OpaqueBrowserFrameView::GetOTRAvatarIcon() const { - return browser_view()->GetOTRAvatarIcon(); + return BrowserNonClientFrameView::GetOTRAvatarIcon(); } bool OpaqueBrowserFrameView::IsMaximized() const {
diff --git a/chrome/browser/ui/views/ime/ime_window_browsertest.cc b/chrome/browser/ui/views/ime/ime_window_browsertest.cc index 2b8bbf7..9534900e 100644 --- a/chrome/browser/ui/views/ime/ime_window_browsertest.cc +++ b/chrome/browser/ui/views/ime/ime_window_browsertest.cc
@@ -40,7 +40,7 @@ void CreateImeWindow(const gfx::Rect& bounds, bool follow_cursor) { ime_window_ = new ImeWindow( - browser()->profile(), nullptr, "about:blank", + browser()->profile(), nullptr, nullptr, "about:blank", follow_cursor ? ImeWindow::FOLLOW_CURSOR : ImeWindow::NORMAL, bounds); ime_window_->AddObserver(this); EXPECT_FALSE(ime_window_->ime_native_window()->IsVisible()); @@ -76,9 +76,9 @@ IN_PROC_BROWSER_TEST_F(ImeWindowBrowserTest, FollowCursor) { gfx::Rect expected_bounds(100, 200, 100, 100); CreateImeWindow(expected_bounds, true); - ime_window_->FollowCursor(gfx::Rect(10, 20, 1, 10)); - expected_bounds.set_x(10); // cursor left. - expected_bounds.set_y(33); // cursor top + cursor height + margin(3). + ime_window_->FollowCursor(gfx::Rect(50, 50, 1, 10)); + expected_bounds.set_x(18); // cursor left - titlebar width(32). + expected_bounds.set_y(63); // cursor top + cursor height + margin(3). VerifyImeWindow(expected_bounds); }
diff --git a/chrome/browser/ui/views/ime/ime_window_frame_view.cc b/chrome/browser/ui/views/ime/ime_window_frame_view.cc index bd3ec0f..5fef5d9 100644 --- a/chrome/browser/ui/views/ime/ime_window_frame_view.cc +++ b/chrome/browser/ui/views/ime/ime_window_frame_view.cc
@@ -29,8 +29,8 @@ const int kBorderThickness = 1; const int kIconSize = 16; const int kTitleAndButtonPadding = 11; -const int kTitlebarHeight = 36; -const int kTitlebarLeftPadding = 10; +const int kTitlebarHeight = 32; +const int kTitlebarLeftPadding = 8; const int kTitlebarRightPadding = 6; // Colors used to draw border, titlebar background and title text.
diff --git a/chrome/browser/ui/views/profiles/avatar_menu_button.cc b/chrome/browser/ui/views/profiles/avatar_menu_button.cc index 67a7403d..21cb2e5 100644 --- a/chrome/browser/ui/views/profiles/avatar_menu_button.cc +++ b/chrome/browser/ui/views/profiles/avatar_menu_button.cc
@@ -97,17 +97,18 @@ } // static -bool AvatarMenuButton::GetAvatarImages(const BrowserView* browser_view, - bool should_show_avatar_menu, - gfx::Image* avatar, - gfx::Image* taskbar_badge_avatar, - bool* is_rectangle) { - const Profile* profile = browser_view->browser()->profile(); +bool AvatarMenuButton::GetAvatarImages( + const BrowserNonClientFrameView* frame_view, + bool should_show_avatar_menu, + gfx::Image* avatar, + gfx::Image* taskbar_badge_avatar, + bool* is_rectangle) { + const Profile* profile = frame_view->browser_view()->browser()->profile(); if (profile->GetProfileType() == Profile::GUEST_PROFILE) { *avatar = ui::ResourceBundle::GetSharedInstance().GetImageNamed( profiles::GetPlaceholderAvatarIconResourceID()); } else if (profile->GetProfileType() == Profile::INCOGNITO_PROFILE) { - *avatar = gfx::Image(browser_view->GetOTRAvatarIcon()); + *avatar = gfx::Image(frame_view->GetOTRAvatarIcon()); // TODO(nkostylev): Allow this on ChromeOS once the ChromeOS test // environment handles profile directories correctly. #if !defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/views/profiles/avatar_menu_button.h b/chrome/browser/ui/views/profiles/avatar_menu_button.h index d3dcab31..ced1411 100644 --- a/chrome/browser/ui/views/profiles/avatar_menu_button.h +++ b/chrome/browser/ui/views/profiles/avatar_menu_button.h
@@ -18,6 +18,7 @@ class Canvas; class Image; } +class BrowserNonClientFrameView; class BrowserView; class Profile; @@ -46,12 +47,12 @@ // to Chrome avatar icons, will be resized and modified for the title bar. virtual void SetAvatarIcon(const gfx::Image& icon, bool is_rectangle); - // Get avatar images for the BrowserView. |avatar| is used in the browser - // window whereas |taskbar_badge_avatar| is used for the OS taskbar. If + // Get avatar images. |avatar| is used in the browser window whereas + // |taskbar_badge_avatar| is used for the OS taskbar. If // |taskbar_badge_avatar| is empty then |avatar| should be used for the // taskbar as well. Returns false if the cache doesn't have an entry for a // Profile::REGULAR_PROFILE type Profile, otherwise return true. - static bool GetAvatarImages(const BrowserView* browser_view, + static bool GetAvatarImages(const BrowserNonClientFrameView* frame_view, bool should_show_avatar_menu, gfx::Image* avatar, gfx::Image* taskbar_badge_avatar,
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index c25df97..57fdb115 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
@@ -441,7 +441,6 @@ Delegate()->SetDisplayEmail(sanitized_email); UserContext user_context(GetAccountId(email, gaia_id)); - user_context.SetGaiaID(gaia_id); user_context.SetKey(Key(password)); user_context.SetAuthCode(auth_code); user_context.SetAuthFlow(using_saml @@ -525,7 +524,6 @@ const std::string sanitized_email = gaia::SanitizeEmail(typed_email); Delegate()->SetDisplayEmail(sanitized_email); UserContext user_context(GetAccountId(typed_email, gaia_id)); - user_context.SetGaiaID(gaia_id); user_context.SetKey(Key(password)); user_context.SetAuthFlow(using_saml ? UserContext::AUTH_FLOW_GAIA_WITH_SAML
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc index fcd55d96..14b18344 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
@@ -1003,7 +1003,7 @@ } void SigninScreenHandler::HandleLaunchIncognito() { - UserContext context(user_manager::USER_TYPE_GUEST, std::string()); + UserContext context(user_manager::USER_TYPE_GUEST, EmptyAccountId()); if (delegate_) delegate_->Login(context, SigninSpecifics()); } @@ -1024,8 +1024,7 @@ if (!delegate_) return; - UserContext context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, - account_id.GetUserEmail()); + UserContext context(user_manager::USER_TYPE_PUBLIC_ACCOUNT, account_id); context.SetPublicSessionLocale(locale), context.SetPublicSessionInputMethod(input_method); delegate_->Login(context, SigninSpecifics()); @@ -1278,8 +1277,7 @@ void SigninScreenHandler::HandleLaunchKioskApp(const AccountId& app_account_id, bool diagnostic_mode) { - UserContext context(user_manager::USER_TYPE_KIOSK_APP, - app_account_id.GetUserEmail()); + UserContext context(user_manager::USER_TYPE_KIOSK_APP, app_account_id); SigninSpecifics specifics; specifics.kiosk_diagnostic_mode = diagnostic_mode; if (delegate_)
diff --git a/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc b/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc index fd60a4b..db4c547 100644 --- a/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc +++ b/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.cc
@@ -113,3 +113,8 @@ NOTREACHED(); return gfx::Size(); } + +void ConstrainedWebDialogDelegateBase::ResizeToGivenSize( + const gfx::Size size) { + NOTREACHED(); +}
diff --git a/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h b/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h index fee4931..a43814a 100644 --- a/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h +++ b/chrome/browser/ui/webui/constrained_web_dialog_delegate_base.h
@@ -24,6 +24,8 @@ : public ConstrainedWebDialogDelegate, public ui::WebDialogWebContentsDelegate { public: + // |browser_context| and |delegate| must outlive |this| instance, whereas + // |this| will take ownership of |tab_delegate|. ConstrainedWebDialogDelegateBase(content::BrowserContext* browser_context, ui::WebDialogDelegate* delegate, WebDialogWebContentsDelegate* tab_delegate); @@ -47,6 +49,9 @@ content::WebContents* source, const content::NativeWebKeyboardEvent& event) override; + // Resize the dialog to the given size. + virtual void ResizeToGivenSize(const gfx::Size size); + private: scoped_ptr<ui::WebDialogDelegate> web_dialog_delegate_;
diff --git a/chrome/browser/ui/webui/constrained_web_dialog_ui.h b/chrome/browser/ui/webui/constrained_web_dialog_ui.h index 4f7159e5..39cc74b 100644 --- a/chrome/browser/ui/webui/constrained_web_dialog_ui.h +++ b/chrome/browser/ui/webui/constrained_web_dialog_ui.h
@@ -51,6 +51,8 @@ // Returns the maximum size for the dialog. virtual gfx::Size GetMaximumSize() const = 0; + // Returns the preferred size for the dialog, or an empty size if + // the dialog has been closed. virtual gfx::Size GetPreferredSize() const = 0; protected:
diff --git a/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc b/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc index fbdf04f8..f7d39e55 100644 --- a/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc +++ b/chrome/browser/ui/webui/constrained_web_dialog_ui_browsertest.cc
@@ -26,7 +26,6 @@ namespace { -#if !defined(OS_MACOSX) static const char kTestDataURL[] = "data:text/html,<!doctype html>" "<body></body>" "<style>" @@ -42,7 +41,6 @@ return base::StringPrintf("window.document.body.style.width = %d + 'px';" "window.document.body.style.height = %d + 'px';", dimension, dimension); } -#endif class ConstrainedWebDialogBrowserTestObserver : public content::WebContentsObserver { @@ -147,7 +145,6 @@ EXPECT_TRUE(observer.contents_destroyed()); } -#if !defined(OS_MACOSX) // Tests that dialog autoresizes based on web contents when autoresizing // is enabled. IN_PROC_BROWSER_TEST_F(ConstrainedWebDialogBrowserTest, @@ -173,6 +170,12 @@ gfx::Size min_size = gfx::Size(100, 100); gfx::Size max_size = gfx::Size(200, 200); gfx::Size initial_dialog_size; +// OSX windows are initially created with non-empty dimensions. The +// autoresizeable dialog's window dimensions are determined after initial +// creation. +#if defined(OS_MACOSX) + initial_dialog_size = gfx::Size(1, 1); +#endif delegate->GetDialogSize(&initial_dialog_size); ConstrainedWebDialogDelegate* dialog_delegate = @@ -186,7 +189,6 @@ EXPECT_EQ(max_size, dialog_delegate->GetMaximumSize()); // Check for initial sizing. Dialog was created as a 400x400 dialog. - EXPECT_EQ(gfx::Size(), web_contents->GetPreferredSize()); ASSERT_EQ(initial_dialog_size, dialog_delegate->GetPreferredSize()); observer.Wait(); @@ -250,7 +252,6 @@ delegate->GetDialogSize(&initial_dialog_size); // Check for initial sizing. Dialog was created as a 400x400 dialog. - EXPECT_EQ(gfx::Size(), web_contents->GetPreferredSize()); ASSERT_EQ(initial_dialog_size, dialog_delegate->GetPreferredSize()); // Resize <body> to dimension smaller than dialog. @@ -269,4 +270,3 @@ initial_dialog_size, dialog_delegate))); } -#endif // !OS_MACOSX
diff --git a/chrome/browser/ui/webui/flags_ui.cc b/chrome/browser/ui/webui/flags_ui.cc index 943a77f..4827404 100644 --- a/chrome/browser/ui/webui/flags_ui.cc +++ b/chrome/browser/ui/webui/flags_ui.cc
@@ -44,6 +44,7 @@ #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos_factory.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/settings/owner_flags_storage.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "components/pref_registry/pref_registry_syncable.h" @@ -246,7 +247,10 @@ chromeos::DBusThreadManager::Get() ->GetSessionManagerClient() ->SetFlagsForUser( - user_manager::UserManager::Get()->GetActiveUser()->email(), flags); + cryptohome::Identification(user_manager::UserManager::Get() + ->GetActiveUser() + ->GetAccountId()), + flags); #endif chrome::AttemptRestart(); }
diff --git a/chrome/browser/ui/webui/md_history_ui.cc b/chrome/browser/ui/webui/md_history_ui.cc index c0936575..e0f82545 100644 --- a/chrome/browser/ui/webui/md_history_ui.cc +++ b/chrome/browser/ui/webui/md_history_ui.cc
@@ -32,15 +32,21 @@ content::WebUIDataSource::Create(chrome::kChromeUIHistoryHost); // Localized strings (alphabetical order). + source->AddLocalizedString("cancel", IDS_CANCEL); source->AddLocalizedString("clearBrowsingData", IDS_CLEAR_BROWSING_DATA_TITLE); source->AddLocalizedString("clearSearch", IDS_MD_HISTORY_CLEAR_SEARCH); - source->AddLocalizedString("cancel", IDS_CANCEL); source->AddLocalizedString("delete", IDS_MD_HISTORY_DELETE); + source->AddLocalizedString("foundSearchResults", + IDS_HISTORY_FOUND_SEARCH_RESULTS); source->AddLocalizedString("itemsSelected", IDS_MD_HISTORY_ITEMS_SELECTED); source->AddLocalizedString("moreFromSite", IDS_HISTORY_MORE_FROM_SITE); + source->AddLocalizedString("noResults", IDS_HISTORY_NO_RESULTS); + source->AddLocalizedString("noSearchResults", IDS_HISTORY_NO_SEARCH_RESULTS); source->AddLocalizedString("removeFromHistory", IDS_HISTORY_REMOVE_PAGE); source->AddLocalizedString("search", IDS_MD_HISTORY_SEARCH); + source->AddLocalizedString("searchResult", IDS_HISTORY_SEARCH_RESULT); + source->AddLocalizedString("searchResults", IDS_HISTORY_SEARCH_RESULTS); source->AddLocalizedString("title", IDS_HISTORY_TITLE); bool allow_deleting_history =
diff --git a/chrome/browser/ui/webui/options/browser_options_handler.cc b/chrome/browser/ui/webui/options/browser_options_handler.cc index faeec30..1e56c52 100644 --- a/chrome/browser/ui/webui/options/browser_options_handler.cc +++ b/chrome/browser/ui/webui/options/browser_options_handler.cc
@@ -173,9 +173,11 @@ } #endif // defined(OS_WIN) +#if !defined(OS_CHROMEOS) bool IsDisabledByPolicy(const BooleanPrefMember& pref) { return pref.IsManaged() && !pref.GetValue(); } +#endif // !defined(OS_CHROMEOS) } // namespace @@ -190,11 +192,13 @@ #endif // defined(OS_CHROMEOS) signin_observer_(this), weak_ptr_factory_(this) { +#if !defined(OS_CHROMEOS) // The worker pointer is reference counted. While it is running, the // message loops of the FILE and UI thread will hold references to it // and it will be automatically freed once all its tasks have finished. default_browser_worker_ = new shell_integration::DefaultBrowserWorker( this, /*delete_observer=*/false); +#endif #if defined(ENABLE_SERVICE_DISCOVERY) cloud_print_mdns_ui_enabled_ = true; @@ -207,8 +211,10 @@ if (sync_service) sync_service->RemoveObserver(this); +#if !defined(OS_CHROMEOS) if (default_browser_worker_.get()) default_browser_worker_->ObserverDestroyed(); +#endif if (template_url_service_) template_url_service_->RemoveObserver(this); // There may be pending file dialogs, we need to tell them that we've gone @@ -723,10 +729,6 @@ void BrowserOptionsHandler::RegisterMessages() { web_ui()->RegisterMessageCallback( - "becomeDefaultBrowser", - base::Bind(&BrowserOptionsHandler::BecomeDefaultBrowser, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( "setDefaultSearchEngine", base::Bind(&BrowserOptionsHandler::SetDefaultSearchEngine, base::Unretained(this))); @@ -789,6 +791,10 @@ base::Unretained(this))); #else web_ui()->RegisterMessageCallback( + "becomeDefaultBrowser", + base::Bind(&BrowserOptionsHandler::BecomeDefaultBrowser, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "restartBrowser", base::Bind(&BrowserOptionsHandler::HandleRestartBrowser, base::Unretained(this))); @@ -911,11 +917,13 @@ content::URLDataSource::Add( profile, new FaviconSource(profile, FaviconSource::FAVICON)); +#if !defined(OS_CHROMEOS) default_browser_policy_.Init( prefs::kDefaultBrowserSettingEnabled, g_browser_process->local_state(), base::Bind(&BrowserOptionsHandler::UpdateDefaultBrowserState, base::Unretained(this))); +#endif #if defined(OS_CHROMEOS) registrar_.Add(this, chrome::NOTIFICATION_LOGIN_USER_IMAGE_CHANGED, @@ -1011,7 +1019,9 @@ ObserveThemeChanged(); OnStateChanged(); +#if !defined(OS_CHROMEOS) UpdateDefaultBrowserState(); +#endif SetupMetricsReportingSettingVisibility(); SetupMetricsReportingCheckbox(); @@ -1095,6 +1105,7 @@ #endif } +#if !defined(OS_CHROMEOS) void BrowserOptionsHandler::UpdateDefaultBrowserState() { default_browser_worker_->StartCheckIsDefault(); } @@ -1117,15 +1128,6 @@ prefs->SetBoolean(prefs::kCheckDefaultBrowser, true); } -int BrowserOptionsHandler::StatusStringIdForState( - shell_integration::DefaultWebClientState state) { - if (state == shell_integration::IS_DEFAULT) - return IDS_OPTIONS_DEFAULTBROWSER_DEFAULT; - if (state == shell_integration::NOT_DEFAULT) - return IDS_OPTIONS_DEFAULTBROWSER_NOTDEFAULT; - return IDS_OPTIONS_DEFAULTBROWSER_UNKNOWN; -} - void BrowserOptionsHandler::SetDefaultWebClientUIState( shell_integration::DefaultWebClientUIState state) { int status_string_id; @@ -1169,6 +1171,7 @@ "BrowserOptions.updateDefaultBrowserState", status_string, is_default, can_be_default); } +#endif // !defined(OS_CHROMEOS) void BrowserOptionsHandler::OnTemplateURLServiceChanged() { if (!template_url_service_ || !template_url_service_->loaded())
diff --git a/chrome/browser/ui/webui/options/browser_options_handler.h b/chrome/browser/ui/webui/options/browser_options_handler.h index 2cbedb3..edeced0 100644 --- a/chrome/browser/ui/webui/options/browser_options_handler.h +++ b/chrome/browser/ui/webui/options/browser_options_handler.h
@@ -16,7 +16,6 @@ #include "build/build_config.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_attributes_storage.h" -#include "chrome/browser/shell_integration.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/webui/options/options_ui.h" #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h" @@ -36,7 +35,9 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/policy/consumer_management_service.h" #include "chrome/browser/chromeos/system/pointer_device_observer.h" -#endif // defined(OS_CHROMEOS) +#else // defined(OS_CHROMEOS) +#include "chrome/browser/shell_integration.h" +#endif // !defined(OS_CHROMEOS) class AutocompleteController; class CloudPrintSetupHandler; @@ -60,7 +61,9 @@ public sync_driver::SyncServiceObserver, public SigninManagerBase::Observer, public ui::SelectFileDialog::Listener, +#if !defined(OS_CHROMEOS) public shell_integration::DefaultWebClientObserver, +#endif #if defined(OS_CHROMEOS) public chromeos::system::PointerDeviceObserver::Observer, public policy::ConsumerManagementService::Observer, @@ -91,10 +94,6 @@ void GoogleSignedOut(const std::string& account_id, const std::string& username) override; - // shell_integration::DefaultWebClientObserver implementation. - void SetDefaultWebClientUIState( - shell_integration::DefaultWebClientUIState state) override; - // TemplateURLServiceObserver implementation. void OnTemplateURLServiceChanged() override; @@ -158,15 +157,9 @@ // Will be called when the kSigninAllowed pref has changed. void OnSigninAllowedPrefChange(); - // Makes this the default browser. Called from WebUI. - void BecomeDefaultBrowser(const base::ListValue* args); - // Sets the search engine at the given index to be default. Called from WebUI. void SetDefaultSearchEngine(const base::ListValue* args); - // Returns the string ID for the given default browser state. - int StatusStringIdForState(shell_integration::DefaultWebClientState state); - // Returns if the "make Chrome default browser" button should be shown. bool ShouldShowSetDefaultBrowser(); @@ -176,12 +169,21 @@ // Returns if access to advanced settings should be allowed. bool ShouldAllowAdvancedSettings(); +#if !defined(OS_CHROMEOS) // Gets the current default browser state, and asynchronously reports it to // the WebUI page. void UpdateDefaultBrowserState(); + // Makes this the default browser. Called from WebUI. + void BecomeDefaultBrowser(const base::ListValue* args); + + // shell_integration::DefaultWebClientObserver implementation. + void SetDefaultWebClientUIState( + shell_integration::DefaultWebClientUIState state) override; + // Updates the UI with the given state for the default browser. void SetDefaultBrowserUIString(int status_string_id); +#endif // !defined(OS_CHROMEOS) // Loads the possible default search engine list and reports it to the WebUI. void AddTemplateUrlServiceObserver(); @@ -376,13 +378,15 @@ // true on other platforms. bool IsDeviceOwnerProfile(); +#if !defined(OS_CHROMEOS) scoped_refptr<shell_integration::DefaultBrowserWorker> default_browser_worker_; + BooleanPrefMember default_browser_policy_; +#endif bool page_initialized_; StringPrefMember homepage_; - BooleanPrefMember default_browser_policy_; TemplateURLService* template_url_service_; // Weak.
diff --git a/chrome/browser/usb/usb_tab_helper.cc b/chrome/browser/usb/usb_tab_helper.cc index 8e235e4..91977fd 100644 --- a/chrome/browser/usb/usb_tab_helper.cc +++ b/chrome/browser/usb/usb_tab_helper.cc
@@ -38,11 +38,8 @@ RenderFrameHost* render_frame_host, mojo::InterfaceRequest<device::usb::DeviceManager> request) { DCHECK(WebContents::FromRenderFrameHost(render_frame_host) == web_contents()); - device::usb::PermissionProviderPtr permission_provider; - GetPermissionProvider(render_frame_host, - mojo::GetProxy(&permission_provider)); - device::usb::DeviceManagerImpl::Create(std::move(permission_provider), - std::move(request)); + device::usb::DeviceManagerImpl::Create( + GetPermissionProvider(render_frame_host), std::move(request)); } #if !defined(OS_ANDROID) @@ -73,15 +70,14 @@ return it->second.get(); } -void UsbTabHelper::GetPermissionProvider( - RenderFrameHost* render_frame_host, - mojo::InterfaceRequest<device::usb::PermissionProvider> request) { +base::WeakPtr<device::usb::PermissionProvider> +UsbTabHelper::GetPermissionProvider(RenderFrameHost* render_frame_host) { FrameUsbServices* frame_usb_services = GetFrameUsbService(render_frame_host); if (!frame_usb_services->permission_provider) { frame_usb_services->permission_provider.reset( new WebUSBPermissionProvider(render_frame_host)); } - frame_usb_services->permission_provider->Bind(std::move(request)); + return frame_usb_services->permission_provider->GetWeakPtr(); } #if !defined(OS_ANDROID)
diff --git a/chrome/browser/usb/usb_tab_helper.h b/chrome/browser/usb/usb_tab_helper.h index 277cf678..688f5013 100644 --- a/chrome/browser/usb/usb_tab_helper.h +++ b/chrome/browser/usb/usb_tab_helper.h
@@ -57,9 +57,8 @@ FrameUsbServices* GetFrameUsbService( content::RenderFrameHost* render_frame_host); - void GetPermissionProvider( - content::RenderFrameHost* render_frame_host, - mojo::InterfaceRequest<device::usb::PermissionProvider> request); + base::WeakPtr<device::usb::PermissionProvider> GetPermissionProvider( + content::RenderFrameHost* render_frame_host); #if !defined(OS_ANDROID) void GetPermissionBubble(
diff --git a/chrome/browser/usb/web_usb_permission_provider.cc b/chrome/browser/usb/web_usb_permission_provider.cc index a037432..3e278819 100644 --- a/chrome/browser/usb/web_usb_permission_provider.cc +++ b/chrome/browser/usb/web_usb_permission_provider.cc
@@ -13,7 +13,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" -#include "device/core/device_client.h" +#include "device/usb/public/interfaces/device.mojom.h" using content::WebContents; using device::usb::WebUsbDescriptorSet; @@ -28,31 +28,26 @@ const uint8_t* interface_number) { if (!set) return false; - for (size_t i = 0; i < set->origins.size(); ++i) { + for (size_t i = 0; i < set->origins.size(); ++i) if (origin.spec() == set->origins[i]) return true; - } for (size_t i = 0; i < set->configurations.size(); ++i) { - const device::usb::WebUsbConfigurationSubsetPtr& config = - set->configurations[i]; + const WebUsbConfigurationSubsetPtr& config = set->configurations[i]; if (configuration_value && *configuration_value != config->configuration_value) continue; - for (size_t j = 0; i < config->origins.size(); ++j) { + for (size_t j = 0; i < config->origins.size(); ++j) if (origin.spec() == config->origins[j]) return true; - } for (size_t j = 0; j < config->functions.size(); ++j) { - const device::usb::WebUsbFunctionSubsetPtr& function = - config->functions[j]; + const WebUsbFunctionSubsetPtr& function = config->functions[j]; // TODO(reillyg): Implement support for Interface Association Descriptors // so that this check will match associated interfaces. if (interface_number && *interface_number != function->first_interface) continue; - for (size_t k = 0; k < function->origins.size(); ++k) { + for (size_t k = 0; k < function->origins.size(); ++k) if (origin.spec() == function->origins[k]) return true; - } } } return false; @@ -62,16 +57,20 @@ WebUSBPermissionProvider::WebUSBPermissionProvider( content::RenderFrameHost* render_frame_host) - : render_frame_host_(render_frame_host) { + : render_frame_host_(render_frame_host), weak_factory_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(render_frame_host_); } WebUSBPermissionProvider::~WebUSBPermissionProvider() {} -void WebUSBPermissionProvider::HasDevicePermission( - mojo::Array<device::usb::DeviceInfoPtr> requested_devices, - const HasDevicePermissionCallback& callback) { +base::WeakPtr<device::usb::PermissionProvider> +WebUSBPermissionProvider::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +bool WebUSBPermissionProvider::HasDevicePermission( + const device::usb::DeviceInfo& device_info) const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); WebContents* web_contents = WebContents::FromRenderFrameHost(render_frame_host_); @@ -84,44 +83,29 @@ UsbChooserContext* chooser_context = UsbChooserContextFactory::GetForProfile(profile); - mojo::Array<mojo::String> allowed_guids; - for (size_t i = 0; i < requested_devices.size(); ++i) { - const device::usb::DeviceInfo& device = *requested_devices[i]; - if (FindOriginInDescriptorSet(device.webusb_allowed_origins.get(), - requesting_origin, nullptr, nullptr) && - chooser_context->HasDevicePermission(requesting_origin, - embedding_origin, device)) { - allowed_guids.push_back(device.guid); - } - } - callback.Run(std::move(allowed_guids)); + return FindOriginInDescriptorSet(device_info.webusb_allowed_origins.get(), + requesting_origin, nullptr, nullptr) && + chooser_context->HasDevicePermission(requesting_origin, + embedding_origin, device_info); } -void WebUSBPermissionProvider::HasConfigurationPermission( +bool WebUSBPermissionProvider::HasConfigurationPermission( uint8_t requested_configuration_value, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) { + const device::usb::DeviceInfo& device_info) const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - callback.Run(FindOriginInDescriptorSet( - device->webusb_allowed_origins.get(), + return FindOriginInDescriptorSet( + device_info.webusb_allowed_origins.get(), render_frame_host_->GetLastCommittedURL().GetOrigin(), - &requested_configuration_value, nullptr)); + &requested_configuration_value, nullptr); } -void WebUSBPermissionProvider::HasInterfacePermission( +bool WebUSBPermissionProvider::HasInterfacePermission( uint8_t requested_interface, uint8_t configuration_value, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) { + const device::usb::DeviceInfo& device_info) const { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - callback.Run(FindOriginInDescriptorSet( - device->webusb_allowed_origins.get(), + return FindOriginInDescriptorSet( + device_info.webusb_allowed_origins.get(), render_frame_host_->GetLastCommittedURL().GetOrigin(), - &configuration_value, &requested_interface)); -} - -void WebUSBPermissionProvider::Bind( - mojo::InterfaceRequest<device::usb::PermissionProvider> request) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - bindings_.AddBinding(this, std::move(request)); + &configuration_value, &requested_interface); }
diff --git a/chrome/browser/usb/web_usb_permission_provider.h b/chrome/browser/usb/web_usb_permission_provider.h index 19b6f30..e52275b 100644 --- a/chrome/browser/usb/web_usb_permission_provider.h +++ b/chrome/browser/usb/web_usb_permission_provider.h
@@ -7,10 +7,8 @@ #include <stdint.h> -#include "device/usb/public/interfaces/permission_provider.mojom.h" -#include "mojo/public/cpp/bindings/array.h" -#include "mojo/public/cpp/bindings/binding_set.h" -#include "mojo/public/cpp/bindings/interface_request.h" +#include "base/memory/weak_ptr.h" +#include "device/usb/mojo/permission_provider.h" namespace content { class RenderFrameHost; @@ -24,28 +22,24 @@ public: explicit WebUSBPermissionProvider( content::RenderFrameHost* render_frame_host); - ~WebUSBPermissionProvider() override; + base::WeakPtr<PermissionProvider> GetWeakPtr(); + // device::usb::PermissionProvider implementation. - void HasDevicePermission( - mojo::Array<device::usb::DeviceInfoPtr> requested_devices, - const HasDevicePermissionCallback& callback) override; - void HasConfigurationPermission( + bool HasDevicePermission( + const device::usb::DeviceInfo& device_info) const override; + bool HasConfigurationPermission( uint8_t requested_configuration, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) override; - void HasInterfacePermission( + const device::usb::DeviceInfo& device_info) const override; + bool HasInterfacePermission( uint8_t requested_interface, uint8_t configuration_value, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) override; - void Bind( - mojo::InterfaceRequest<device::usb::PermissionProvider> request) override; + const device::usb::DeviceInfo& device_info) const override; private: - mojo::BindingSet<PermissionProvider> bindings_; content::RenderFrameHost* const render_frame_host_; + base::WeakPtrFactory<PermissionProvider> weak_factory_; }; #endif // CHROME_BROWSER_USB_WEB_USB_PERMISSION_PROVIDER_H_
diff --git a/chrome/common/extensions/api/media_galleries.idl b/chrome/common/extensions/api/media_galleries.idl index 8c257c4..7ef67279 100644 --- a/chrome/common/extensions/api/media_galleries.idl +++ b/chrome/common/extensions/api/media_galleries.idl
@@ -75,7 +75,7 @@ void ([instanceOf=DOMFileSystem] object[] mediaFileSystems, DOMString selectedFileSystemName); - callback DropPermissionForMediaFileSystemCallback = void (); + [nodefine] callback DropPermissionForMediaFileSystemCallback = void (); [inline_doc] dictionary MediaFileSystemMetadata { // The name of the file system. @@ -180,7 +180,8 @@ }; callback AddGalleryWatchCallback = void (AddGalleryWatchResult result); - callback GetAllGalleryWatchCallback = void (DOMString[] galleryIds); + [nodefine] callback GetAllGalleryWatchCallback = + void (DOMString[] galleryIds); interface Functions { // Get the media galleries configured in this user agent. If none are @@ -196,6 +197,8 @@ static void addUserSelectedFolder(AddUserFolderCallback callback); // Give up access to a given media gallery. + [nodefine, deprecated="The user can manually drop access to galleries + via the permissions dialog."] static void dropPermissionForMediaFileSystem( DOMString galleryId, optional DropPermissionForMediaFileSystemCallback callback); @@ -224,6 +227,7 @@ [instanceOf=DOMFileSystem] object mediaFileSystem); // Get metadata for all available media galleries. + [nodefine, deprecated="Use getMediaFileSystemMetadata instead."] static void getAllMediaFileSystemMetadata( MediaFileSystemsMetadataCallback callback); @@ -242,9 +246,12 @@ static void removeGalleryWatch(DOMString galleryId); // Notifies which galleries are being watched via the given callback. + [nodefine, deprecated="Applications should store their own gallery watches + as they are added."] static void getAllGalleryWatch(GetAllGalleryWatchCallback callback); // Removes all gallery watches. + [nodefine, deprecated="Use removeGalleryWatch instead."] static void removeAllGalleryWatch(); };
diff --git a/chrome/common/extensions/api/preferences_private.json b/chrome/common/extensions/api/preferences_private.json index bb23460..8044178a 100644 --- a/chrome/common/extensions/api/preferences_private.json +++ b/chrome/common/extensions/api/preferences_private.json
@@ -18,12 +18,6 @@ "$ref": "types.private.ChromeDirectSetting", "value": ["googlegeolocationaccess.enabled", {"type":"boolean"}], "description": "If enabled, Google services can access the user's location. This preference's value is a boolean, defaulting to <code>false</code>." - }, - "dataReductionUpdateDailyLengths": { - "nocompile": true, - "$ref": "types.private.ChromeDirectSetting", - "value": ["data_reduction.update_daily_lengths", {"type":"boolean"}], - "description": "Flag to indicate that dataReductionDailyContentLength and dataReductionDailyReceivedLength must be updated with their latest values. This preference's value is a boolean, defaulting to <code>false</code>." } }, "functions": [
diff --git a/chrome/installer/linux/common/apt.include b/chrome/installer/linux/common/apt.include index 77d418c1..aabca09 100644 --- a/chrome/installer/linux/common/apt.include +++ b/chrome/installer/linux/common/apt.include
@@ -87,7 +87,7 @@ ACTIVECONFIGS=$(grep -v "^[[:space:]]*\(#.*\)\?$" "$SOURCELIST" 2>/dev/null) # Check if the correct repository configuration is in there. - REPOMATCH=$(grep -E "^[[:space:]#]*\b($REPOCONFIG|$SSLREPOCONFIG)\b" "$SOURCELIST" \ + REPOMATCH=$(grep -E "^[[:space:]#]*\b$REPOCONFIGREGEX\b" "$SOURCELIST" \ 2>/dev/null) # Check if the correct repository is disabled. @@ -174,9 +174,9 @@ find_apt_sources SOURCELIST="$APT_SOURCESDIR/@@PACKAGE@@.list" if [ -r "$SOURCELIST" ]; then - REPOLINE=$(grep -E "^[[:space:]]*#[[:space:]]*($REPOCONFIG|$SSLREPOCONFIG)[[:space:]]*# disabled on upgrade to .*" "$SOURCELIST") + REPOLINE=$(grep -E "^[[:space:]]*#[[:space:]]*$REPOCONFIGREGEX[[:space:]]*# disabled on upgrade to .*" "$SOURCELIST") if [ $? -eq 0 ]; then - sed -i -e "s,^[[:space:]]*#[[:space:]]*\($REPOCONFIG\|$SSLREPOCONFIG\)[[:space:]]*# disabled on upgrade to .*,\1," \ + sed -i -e "s,^[[:space:]]*#[[:space:]]*\(.*\)[[:space:]]*# disabled on upgrade to .*,\1," \ "$SOURCELIST" LOGGER=$(which logger 2> /dev/null) if [ "$LOGGER" ]; then
diff --git a/chrome/installer/linux/common/installer.include b/chrome/installer/linux/common/installer.include index 68c6555e..386d4877 100644 --- a/chrome/installer/linux/common/installer.include +++ b/chrome/installer/linux/common/installer.include
@@ -73,7 +73,7 @@ -e "s#@@MAINTNAME@@#${MAINTNAME}#g" \ -e "s#@@MAINTMAIL@@#${MAINTMAIL}#g" \ -e "s#@@REPOCONFIG@@#${REPOCONFIG}#g" \ - -e "s#@@SSLREPOCONFIG@@#${SSLREPOCONFIG}#g" \ + -e "s#@@REPOCONFIGREGEX@@#${REPOCONFIGREGEX}#g" \ -e "s#@@SHORTDESC@@#${SHORTDESC}#g" \ -e "s#@@FULLDESC@@#${FULLDESC}#g" \ -e "s#@@DEFAULT_FLAGS@@#${DEFAULT_FLAGS:-}#g" \
diff --git a/chrome/installer/linux/common/variables.include b/chrome/installer/linux/common/variables.include index 79340cd..be94314 100644 --- a/chrome/installer/linux/common/variables.include +++ b/chrome/installer/linux/common/variables.include
@@ -3,4 +3,4 @@ # sources.list setting for @@PACKAGE@@ updates. REPOCONFIG="@@REPOCONFIG@@" -SSLREPOCONFIG="@@SSLREPOCONFIG@@" +REPOCONFIGREGEX="@@REPOCONFIGREGEX@@"
diff --git a/chrome/installer/linux/debian/build.sh b/chrome/installer/linux/debian/build.sh index de11150..2de349c 100755 --- a/chrome/installer/linux/debian/build.sh +++ b/chrome/installer/linux/debian/build.sh
@@ -236,8 +236,6 @@ eval $(sed -e "s/^\([^=]\+\)=\(.*\)$/export \1='\2'/" \ "${BUILDDIR}/installer/theme/BRANDING") -REPOCONFIG="deb http://dl.google.com/linux/chrome/deb/ stable main" -SSLREPOCONFIG="deb https://dl.google.com/linux/chrome/deb/ stable main" verify_channel # Some Debian packaging tools want these set. @@ -323,11 +321,9 @@ case "$TARGETARCH" in ia32 ) export ARCHITECTURE="i386" - stage_install_debian ;; x64 ) export ARCHITECTURE="amd64" - stage_install_debian ;; * ) echo @@ -336,5 +332,14 @@ exit 1 ;; esac +BASEREPOCONFIG="dl.google.com/linux/chrome/deb/ stable main" +# Only use the default REPOCONFIG if it's unset (e.g. verify_channel might have +# set it to an empty string) +REPOCONFIG="${REPOCONFIG-deb [arch=${ARCHITECTURE}] http://${BASEREPOCONFIG}}" +# Allowed configs include optional HTTPS support and explicit multiarch +# platforms. +REPOCONFIGREGEX="deb (\\\\[arch=[^]]*\\\\b${ARCHITECTURE}\\\\b[^]]*\\\\]" +REPOCONFIGREGEX+="[[:space:]]*)?https?://${BASEREPOCONFIG}" +stage_install_debian do_package
diff --git a/chrome/installer/linux/rpm/build.sh b/chrome/installer/linux/rpm/build.sh index dd4233c..89709f7 100755 --- a/chrome/installer/linux/rpm/build.sh +++ b/chrome/installer/linux/rpm/build.sh
@@ -314,7 +314,6 @@ "${BUILDDIR}/installer/theme/BRANDING") REPOCONFIG="http://dl.google.com/linux/${PACKAGE#google-}/rpm/stable" -SSLREPOCONFIG="https://dl.google.com/linux/${PACKAGE#google-}/rpm/stable" verify_channel export USR_BIN_SYMLINK_NAME="${PACKAGE}-${CHANNEL}"
diff --git a/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js b/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js index 277a222e..4be13a5 100644 --- a/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js +++ b/chrome/renderer/resources/extensions/media_galleries_custom_bindings.js
@@ -56,22 +56,6 @@ callback(fileSystems, selectedFileSystemName); }); - apiFunctions.setCustomCallback('dropPermissionForMediaFileSystem', - function(name, request, callback, response) { - var galleryId = response; - - if (galleryId) { - for (var key in mediaGalleriesMetadata) { - if (mediaGalleriesMetadata[key].galleryId == galleryId) { - delete mediaGalleriesMetadata[key]; - break; - } - } - } - if (callback) - callback(); - }); - apiFunctions.setHandleRequest('getMediaFileSystemMetadata', function(filesystem) { if (filesystem && filesystem.name &&
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index 8897002..74c7d01 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc
@@ -132,6 +132,9 @@ namespace { +// Default profile name +const char kTestingProfile[] = "testing_profile"; + // Task used to make sure history has finished processing a request. Intended // for use with BlockUntilHistoryProcessesPendingRequests. @@ -258,7 +261,8 @@ browser_context_dependency_manager_( BrowserContextDependencyManager::GetInstance()), resource_context_(NULL), - delegate_(NULL) { + delegate_(NULL), + profile_name_(kTestingProfile) { CreateTempProfileDir(); profile_path_ = temp_dir_.path(); @@ -277,13 +281,13 @@ browser_context_dependency_manager_( BrowserContextDependencyManager::GetInstance()), resource_context_(NULL), - delegate_(NULL) { + delegate_(NULL), + profile_name_(kTestingProfile) { Init(); FinishInit(); } -TestingProfile::TestingProfile(const base::FilePath& path, - Delegate* delegate) +TestingProfile::TestingProfile(const base::FilePath& path, Delegate* delegate) : start_time_(Time::Now()), testing_prefs_(NULL), force_incognito_(false), @@ -294,7 +298,8 @@ browser_context_dependency_manager_( BrowserContextDependencyManager::GetInstance()), resource_context_(NULL), - delegate_(delegate) { + delegate_(delegate), + profile_name_(kTestingProfile) { Init(); if (delegate_) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -316,7 +321,8 @@ bool guest_session, const std::string& supervised_user_id, scoped_ptr<policy::PolicyService> policy_service, - const TestingFactories& factories) + const TestingFactories& factories, + const std::string& profile_name) : start_time_(Time::Now()), prefs_(prefs.release()), testing_prefs_(NULL), @@ -332,6 +338,7 @@ BrowserContextDependencyManager::GetInstance()), resource_context_(NULL), delegate_(delegate), + profile_name_(profile_name), policy_service_(policy_service.release()) { if (parent) parent->SetOffTheRecordProfile(scoped_ptr<Profile>(this)); @@ -475,8 +482,6 @@ store->SetInitializationCompleted(); } #endif - - profile_name_ = "testing_profile"; } void TestingProfile::FinishInit() { @@ -975,8 +980,8 @@ TestingProfile::Builder::Builder() : build_called_(false), delegate_(NULL), - guest_session_(false) { -} + guest_session_(false), + profile_name_(kTestingProfile) {} TestingProfile::Builder::~Builder() { } @@ -1015,6 +1020,10 @@ policy_service_ = std::move(policy_service); } +void TestingProfile::Builder::SetProfileName(const std::string& profile_name) { + profile_name_ = profile_name; +} + void TestingProfile::Builder::AddTestingFactory( BrowserContextKeyedServiceFactory* service_factory, BrowserContextKeyedServiceFactory::TestingFactoryFunction callback) { @@ -1031,7 +1040,7 @@ extension_policy_, #endif std::move(pref_service_), NULL, guest_session_, supervised_user_id_, - std::move(policy_service_), testing_factories_)); + std::move(policy_service_), testing_factories_, profile_name_)); } TestingProfile* TestingProfile::Builder::BuildIncognito( @@ -1047,5 +1056,6 @@ #endif std::move(pref_service_), original_profile, guest_session_, supervised_user_id_, - std::move(policy_service_), testing_factories_); + std::move(policy_service_), testing_factories_, + profile_name_); }
diff --git a/chrome/test/base/testing_profile.h b/chrome/test/base/testing_profile.h index c177c72..7004078 100644 --- a/chrome/test/base/testing_profile.h +++ b/chrome/test/base/testing_profile.h
@@ -111,6 +111,9 @@ // Sets the PolicyService to be used by this profile. void SetPolicyService(scoped_ptr<policy::PolicyService> policy_service); + // Sets the UserProfileName to be used by this profile. + void SetProfileName(const std::string& profile_name); + // Creates the TestingProfile using previously-set settings. scoped_ptr<TestingProfile> Build(); @@ -134,6 +137,7 @@ std::string supervised_user_id_; scoped_ptr<policy::PolicyService> policy_service_; TestingFactories testing_factories_; + std::string profile_name_; DISALLOW_COPY_AND_ASSIGN(Builder); }; @@ -163,7 +167,8 @@ bool guest_session, const std::string& supervised_user_id, scoped_ptr<policy::PolicyService> policy_service, - const TestingFactories& factories); + const TestingFactories& factories, + const std::string& profile_name); ~TestingProfile() override;
diff --git a/chrome/test/base/testing_profile_manager.cc b/chrome/test/base/testing_profile_manager.cc index 1f363318..0271c18 100644 --- a/chrome/test/base/testing_profile_manager.cc +++ b/chrome/test/base/testing_profile_manager.cc
@@ -87,6 +87,7 @@ builder.SetPath(profile_path); builder.SetPrefService(std::move(prefs)); builder.SetSupervisedUserId(supervised_user_id); + builder.SetProfileName(profile_name); for (TestingProfile::TestingFactories::const_iterator it = factories.begin(); it != factories.end(); ++it) { @@ -94,7 +95,6 @@ } TestingProfile* profile = builder.Build().release(); - profile->set_profile_name(profile_name); profile_manager_->AddProfile(profile); // Takes ownership. // Update the user metadata.
diff --git a/chrome/test/data/autofill/heuristics/input/138_cc_checkout_united.com.html b/chrome/test/data/autofill/heuristics/input/138_cc_checkout_united.com.html new file mode 100644 index 0000000..883ae9c0 --- /dev/null +++ b/chrome/test/data/autofill/heuristics/input/138_cc_checkout_united.com.html
@@ -0,0 +1,876 @@ +<form action="https://www.united.com/ual/en/us/flight-search/book-a-flight/billinginfo/default/rev" data-randomhash="https://www.united.com/ual/en/us/flight-search/book-a-flight/billinginfo/generatehash/rev" id="billingInfoForm" method="post" novalidate="novalidate"><input data-val="true" data-val-required="The HasUnitedFundOption field is required." id="HasUnitedFundOption" name="HasUnitedFundOption" type="hidden" value="False"><input data-val="true" data-val-number="The field PosAddressLines must be a number." data-val-required="The PosAddressLines field is required." id="PosAddressLines" name="PosAddressLines" type="hidden" value="3"><input data-val="true" data-val-required="The IsPosAddressZipBeforeCity field is required." id="IsPosAddressZipBeforeCity" name="IsPosAddressZipBeforeCity" type="hidden" value="False"><input data-val="true" data-val-required="The IsPosStateVisible field is required." id="IsPosStateVisible" name="IsPosStateVisible" type="hidden" value="True"><input data-val="true" data-val-required="The IsPosZipVisible field is required." id="IsPosZipVisible" name="IsPosZipVisible" type="hidden" value="True"><input data-val="true" data-val-required="The IsRefundable field is required." id="IsRefundable" name="IsRefundable" type="hidden" value="False"> <div class="panel panel-travel-info" style="display: none"> + + <div id="divCard0" style="display:"> + <div class="form-row"> + <div class="form-group card-type"><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].CardTypeCode" data-valmsg-replace="true"></span><div class="selector fixedWidth" id="uniform-CreditCardViewModels_0__CardTypeCode"><span aria-hidden="true" style="-webkit-user-select: none;"></span><label class="ifl" for="CreditCardViewModels_0__CardTypeCode" style="opacity: 1;">Select card type<em aria-hidden="true" class="rqrd">*</em></label><select aria-label="Select card type" aria-required="true" autocomplete="off" data-val="true" data-val-required="Please select a Card type.<!--EC:V2-->" id="CreditCardViewModels_0__CardTypeCode" name="CreditCardViewModels[0].CardTypeCode" class="preproc"><option selected="selected" value=""></option> +<option value="VI">MileagePlus Visa</option> +<option value="VI">Visa</option> +<option value="JC">JCB</option> +<option value="MC">MasterCard</option> +<option value="AX">American Express</option> +<option value="DS">Discover Network</option> +<option value="DC">Diners Club</option> +<option value="TP">UATP</option> +</select></div></div> + </div> + <div class="form-row"> + <div class="form-group card-number"><label class="ifl" for="CreditCardViewModels_0__CardNumber">Card number<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].CardNumber" data-valmsg-replace="true"></span><input aria-required="true" autocomplete="off" data-privacy="no-capture" data-val="true" data-val-length="The field Card number must be a string with a maximum length of 20." data-val-length-max="20" data-val-regex="Please provide a valid debit or credit card number.<!--EC:CC98-->" data-val-regex-pattern="[13456]{1}[0-9 ]{1,}" data-val-required="Please provide a valid debit or credit card number.<!--EC:CC98-->" id="CreditCardViewModels_0__CardNumber" maxlength="20" name="CreditCardViewModels[0].CardNumber" type="text" value=""></div> + + <input type="text" class="hidden"><input type="password" class="hidden"> + <input id="CreditCardViewModels_0__EncryptedCardNumber" name="CreditCardViewModels[0].EncryptedCardNumber" type="hidden" value=""> + <input id="CreditCardViewModels_0__CardNumberLast4Digits" name="CreditCardViewModels[0].CardNumberLast4Digits" type="hidden" value=""> + <input id="CreditCardViewModels_0__CardNumberToken" name="CreditCardViewModels[0].CardNumberToken" type="hidden" value=""> + <input id="CreditCardViewModels_0__ErrorType" name="CreditCardViewModels[0].ErrorType" type="hidden" value=""> + <input id="CreditCardViewModels_0__ErrorNumber" name="CreditCardViewModels[0].ErrorNumber" type="hidden" value=""> + </div> + <div class="form-row"> + <div class="form-group date-month"><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].ExpMonth" data-valmsg-replace="true"></span><div class="selector fixedWidth" id="uniform-CreditCardViewModels_0__ExpMonth"><span aria-hidden="true" style="-webkit-user-select: none;"></span><label class="ifl" for="CreditCardViewModels_0__ExpMonth">Expiration month<em aria-hidden="true" class="rqrd">*</em></label><select aria-label="Expiration month" aria-required="true" autocomplete="off" data-val="true" data-val-number="The field Expiration month must be a number." data-val-required="Please select an Expiration month.<!--EC:V13-->" id="CreditCardViewModels_0__ExpMonth" name="CreditCardViewModels[0].ExpMonth" class="preproc"><option selected="selected" value=""></option> +<option value="1">01 - January</option> +<option value="2">02 - February</option> +<option value="3">03 - March</option> +<option value="4">04 - April</option> +<option value="5">05 - May</option> +<option value="6">06 - June</option> +<option value="7">07 - July</option> +<option value="8">08 - August</option> +<option value="9">09 - September</option> +<option value="10">10 - October</option> +<option value="11">11 - November</option> +<option value="12">12 - December</option> +</select></div></div> + <div class="form-group card-exp-year"><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].ExpYear" data-valmsg-replace="true"></span><div class="selector fixedWidth" id="uniform-CreditCardViewModels_0__ExpYear"><span aria-hidden="true" style="-webkit-user-select: none;"></span><label class="ifl" for="CreditCardViewModels_0__ExpYear">Year<em aria-hidden="true" class="rqrd">*</em></label><select aria-label="Year" aria-required="true" autocomplete="off" data-val="true" data-val-number="The field Expiration year must be a number." data-val-required="Please select an Expiration year.<!--EC:V13-->" id="CreditCardViewModels_0__ExpYear" name="CreditCardViewModels[0].ExpYear" class="preproc"><option selected="selected" value=""></option> +<option value="2016">2016</option> +<option value="2017">2017</option> +<option value="2018">2018</option> +<option value="2019">2019</option> +<option value="2020">2020</option> +<option value="2021">2021</option> +<option value="2022">2022</option> +<option value="2023">2023</option> +<option value="2024">2024</option> +<option value="2025">2025</option> +<option value="2026">2026</option> +</select></div></div> + <div id="divCreditCardSecurityCode0" class="form-groupset"> + <div class="form-group card-security-code"><label class="ifl" for="CreditCardViewModels_0__SecurityCode">Security code<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].SecurityCode" data-valmsg-replace="true"></span><input aria-required="true" autocomplete="off" data-privacy="no-capture" data-val="true" data-val-length="The field Security code must be a string with a maximum length of 4." data-val-length-max="4" data-val-regex="Please enter a valid Security code.<!--EC:V15-->" data-val-regex-pattern="[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,///-]{3,}" data-val-required="Please enter a Security code.<!--EC:V1-->" id="CreditCardViewModels_0__SecurityCode" maxlength="4" name="CreditCardViewModels[0].SecurityCode" type="password" value=""></div> + <button type="button" class="icon-tooltip-large-clear-bg tool-tip-security-code" data-toggle="tooltip" data-tooltip-style="default" tabindex="0" data-hasqtip="3" oldtitle="What's a security code?" title=""><span class="visuallyhidden">About credit card security code</span></button> + <div class="tip-security-code"> + <div class="tip-security-code-default"> + <h6>Security code</h6> + <p>The card security code consists of the last three digits of the number on the back of your Visa, MasterCard or Discover Card, or the four digits above the main number on your American Express card.</p> + </div> + <div class="tip-security-code-visa" style="display: none;"> + <h6>Visa - CVV2</h6> + <p>The card security code consists of the last three digits of the number on the back of your Visa.</p> + <img src="https://www.united.com/web/format/img/card/CVV2_Visa.GIF" alt="Visa security code"> + </div> + <div class="tip-security-code-mc" style="display: none;"> + <h6>MasterCard - CVC2</h6> + <p>The card security code consists of the last three digits of the number on the back of your MasterCard.</p> + <img src="https://www.united.com/web/format/img/card/CVC2_MC.GIF" alt="MasterCard security code"> + </div> + <div class="tip-security-code-amex" style="display: none;"> + <h6>American Express – CID</h6> + <p>The card security code consists of the four digits above the main number on your American Express card.</p> + <img src="https://www.united.com/web/format/img/card/CID_Amex.GIF" alt="American Express security code"> + </div> + <div class="tip-security-code-discover" style="display: none;"> + <h6>Discover – CID</h6> + <p>The card security code consists of the last three digits of the number on the back of your Discover Card.</p> + <img src="https://www.united.com/web/format/img/card/CID_Discover.GIF" alt="Discover security code"> + </div> + </div> + </div> + </div> + <div class="form-row"> + <div class="form-group card-holder-name"><label class="ifl" for="CreditCardViewModels_0__CardHolderName">Full name as it appears on your card<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].CardHolderName" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Full name as it appears on your card must be a string with a maximum length of 35." data-val-length-max="35" data-val-regex="Please enter a valid Full name as it appears on your card.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z]{1,}[A-Za-z '-.]{1,}" data-val-required="Please enter a Full name as it appears on your card.<!--EC:V1-->" id="CreditCardViewModels_0__CardHolderName" maxlength="35" name="CreditCardViewModels[0].CardHolderName" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-line"><label class="ifl" for="CreditCardViewModels_0__AddressLine1">Billing address line 1<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].AddressLine1" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Billing address line 1 must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address line 1.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" data-val-required="Please enter a Billing address line 1.<!--EC:V1-->" id="CreditCardViewModels_0__AddressLine1" maxlength="30" name="CreditCardViewModels[0].AddressLine1" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-line"><label class="ifl" for="CreditCardViewModels_0__AddressLine2">Billing address line 2 (Optional)</label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].AddressLine2" data-valmsg-replace="true"></span><input data-val="true" data-val-length="The field Billing address line 2 (Optional) must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address line 2 (Optional).<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" id="CreditCardViewModels_0__AddressLine2" maxlength="30" name="CreditCardViewModels[0].AddressLine2" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-line"><label class="ifl" for="CreditCardViewModels_0__AddressLine3">Billing address line 3 (Optional)</label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].AddressLine3" data-valmsg-replace="true"></span><input data-val="true" data-val-length="The field Billing address line 3 (Optional) must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address line 3 (Optional).<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" id="CreditCardViewModels_0__AddressLine3" maxlength="30" name="CreditCardViewModels[0].AddressLine3" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-city"><label class="ifl" for="CreditCardViewModels_0__City">City/town/department<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].City" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field City/town/department must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid City/town/department.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z., \-]{2,}" data-val-required="Please enter a City/town/department.<!--EC:V1-->" id="CreditCardViewModels_0__City" maxlength="30" name="CreditCardViewModels[0].City" type="text" value=""></div> +<div class="form-group address-state"><label class="ifl" for="CreditCardViewModels_0__StateCode">State/province/region/county<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].StateCode" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-regex="Please enter a valid State/province/region/county.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z., ]{2,}" data-val-required="Please enter a State/province/region/county.<!--EC:V1-->" id="CreditCardViewModels_0__StateCode" name="CreditCardViewModels[0].StateCode" type="text" value=""></div> <div class="form-group address-post-code"><label class="ifl" for="CreditCardViewModels_0__PostalCode">ZIP/Postal code<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].PostalCode" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field ZIP/Postal code must be a string with a maximum length of 10." data-val-length-max="10" data-val-regex="Please enter a valid ZIP/Postal code.<!--EC:V15-->" data-val-regex-pattern="[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,///-]{1,}" data-val-required="Please enter a ZIP/Postal code.<!--EC:V1-->" id="CreditCardViewModels_0__PostalCode" maxlength="10" name="CreditCardViewModels[0].PostalCode" type="text" value=""></div> </div> + <div class="form-row"> + <div class="form-group address-country"> + <div class="form-group"><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CreditCardViewModels[0].CountryCode" data-valmsg-replace="true"></span><div class="selector fixedWidth" id="uniform-CreditCardViewModels_0__CountryCode"><span aria-hidden="true" style="-webkit-user-select: none;">United States</span><label class="ifl visuallyhidden" for="CreditCardViewModels_0__CountryCode">Country<em aria-hidden="true" class="rqrd">*</em></label><select aria-label="Country" aria-required="true" data-val="true" data-val-required="The Country field is required." id="CreditCardViewModels_0__CountryCode" name="CreditCardViewModels[0].CountryCode" class="preproc"><option selected="selected" value="US">United States</option> +<option value="CA">Canada</option> +<option value="GB">United Kingdom</option> +<option value="AG">Antigua and Barbuda</option> +<option value="AR">Argentina</option> +<option value="AW">Aruba</option> +<option value="AU">Australia</option> +<option value="BS">Bahamas</option> +<option value="BH">Bahrain</option> +<option value="BB">Barbados</option> +<option value="BE">Belgium</option> +<option value="BZ">Belize</option> +<option value="BM">Bermuda</option> +<option value="BR">Brazil</option> +<option value="CA">Canada</option> +<option value="KY">Cayman Islands</option> +<option value="CL">Chile</option> +<option value="CN">China</option> +<option value="CO">Colombia</option> +<option value="CR">Costa Rica</option> +<option value="DK">Denmark</option> +<option value="DO">Dominican Republic</option> +<option value="EC">Ecuador</option> +<option value="SV">El Salvador</option> +<option value="FR">France</option> +<option value="DE">Germany</option> +<option value="GR">Greece</option> +<option value="GU">Guam</option> +<option value="GT">Guatemala</option> +<option value="HN">Honduras</option> +<option value="HK">Hong Kong</option> +<option value="IN">India</option> +<option value="ID">Indonesia</option> +<option value="IE">Ireland</option> +<option value="IL">Israel</option> +<option value="IT">Italy</option> +<option value="JM">Jamaica</option> +<option value="JP">Japan</option> +<option value="KR">Korea, South</option> +<option value="KW">Kuwait</option> +<option value="MH">Marshall Islands</option> +<option value="MX">Mexico</option> +<option value="FM">Micronesia</option> +<option value="NL">Netherlands</option> +<option value="AN">Netherlands Antilles</option> +<option value="NZ">New Zealand</option> +<option value="NI">Nicaragua</option> +<option value="MP">Northern Mariana Islands</option> +<option value="NO">Norway</option> +<option value="PW">Palau</option> +<option value="PA">Panama</option> +<option value="PE">Peru</option> +<option value="PH">Philippines</option> +<option value="PT">Portugal</option> +<option value="PR">Puerto Rico</option> +<option value="QA">Qatar</option> +<option value="RU">Russia</option> +<option value="SG">Singapore</option> +<option value="ES">Spain & Canary Islands</option> +<option value="SE">Sweden</option> +<option value="CH">Switzerland</option> +<option value="TW">Taiwan</option> +<option value="TH">Thailand</option> +<option value="TT">Trinidad and Tobago</option> +<option value="TR">Turkey</option> +<option value="AE">United Arab Emirates</option> +<option value="GB">United Kingdom</option> +<option selected="selected" value="US">United States</option> +<option value="VN">Vietnam</option> +</select></div></div> + </div> + </div> + + <p>Your bank may apply a credit card conversion fee.</p> + + </div> + </fieldset> + </div> + <div class="panel-body-section" id="divOtherFop" style="display"> + <div id="fop-other-alert"> + <div class="payment-notice"><i class="icon-information-small-gray"></i> Alipay is not eligible forms of payment based on your current selections.</div> + </div> + <div id="fop-other" class="label-payment-type" style=""> + <div class="form-group"> + <span aria-hidden="true" class="field-validation-valid" data-valmsg-for="FOPOption" data-valmsg-replace="true"></span><div class="radio" id="uniform-FOPOption_OtherFop"><span><input aria-required="true" class="type-radio rotherform preproc" id="FOPOption_OtherFop" name="FOPOption" tabindex="0" type="radio" value="OtherFop"></span></div><label class="radio" for="FOPOption_OtherFop">Other forms of payment</label> + </div> + <div id="fop-other-images" class="form-group container-payment-type-images fop-other"> + <ul><li><i class="icon-payment-type-visa-checkout-small" title="Visa Checkout"><span class="visuallyhidden">Visa Checkout</span></i></li><li><i class="icon-payment-type-check-small" title="TeleCheck Online Checks"><span class="visuallyhidden">TeleCheck Online Checks</span></i></li><li><i class="icon-payment-type-cash-small" title="Western Union Cash"><span class="visuallyhidden">Western Union Cash</span></i></li><li><i class="icon-payment-type-paypal-small" title="PayPal"><span class="visuallyhidden">PayPal</span></i></li><li><i class="icon-payment-type-bill-me-later-small" title="PayPal Credit"><span class="visuallyhidden">PayPal Credit</span></i></li></ul> + </div> + </div> + + + <div id="other-fop-section" style=""> + <div class="form-row section-other-fop" id="other_fop_list" style="display: none;"> + <label for="OtherFOPType" class="visuallyhidden">Form of payment</label> + <div class="selector fixedWidth" id="uniform-OtherFOPType"><span aria-hidden="true" style="-webkit-user-select: none;">Not Selected</span><select class="ddlotherfop preproc" data-cartid="83029498-98C8-4043-AA9B-106E1F89C4BF" data-fopurl="https://www.united.com/ual/en/us/flight-search/book-a-flight/billinginfo/getotherfops/rev" id="OtherFOPType" name="OtherFOPType"><option hideoptions="" value="">Not Selected</option><option hideoptions="" value="VCO">Visa Checkout</option><option hideoptions="PAS, AAC" value="CASH">Cash</option><option hideoptions="PAS, AAC" value="CHECK">Online check</option><option hideoptions="" value="PP">PayPal</option><option hideoptions="" value="BML">PayPal Credit</option></select></div> + + + <a href="https://www.united.com/web/en-US/content/booking/flight/whatIsBML.aspx" target="_blank" class="info-link" id="BML-info-link">What is PayPal Credit?</a> + <a href="https://www.united.com/web/en-US/content/booking/flight/whatispaypal.aspx" target="_blank" class="info-link" id="PayPal-info-link">What is PayPal?</a> + </div> + <div class="section-PayPal-type" style="display: none;"> + <p>You will be directed to PayPal's website to enroll or to sign in to your account. You will then be redirected to united.com to complete this purchase.</p> + <input type="hidden" id="paypalUrl"> + <button class="btn" id="btnPayPalCheckOut" value="PayPal">Check out with PayPal</button> + </div> + <div class="section-Alipay-type" style="display: none;"> + <input type="hidden" id="alipayUrl"> + <fieldset> + <legend class="visuallyhidden">Billing information <small class="required" aria-required="true">(*Required)</small></legend> + <h4 class="legend">Billing information <small class="required" aria-required="true">(*Required)</small></h4> + <p>Please enter the purchaser's name and billing address below. Selecting "Purchase" will direct you to Alipay's website to enroll or to sign in to your account. You'll then be redirected to united.com for your purchase confirmation.</p> + <div class="form-row"> + <div class="form-group card-holder-name"><label class="ifl" for="AlipayCardHolderName">Full name as it appears on your card<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="AlipayCardHolderName" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Full name as it appears on your card must be a string with a maximum length of 35." data-val-length-max="35" data-val-regex="Please enter a valid Full name as it appears on your card.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z]{1,}[A-Za-z '-.]{1,}" data-val-required="Please enter a Full name as it appears on your card.<!--EC:V1-->" id="AlipayCardHolderName" maxlength="35" name="AlipayCardHolderName" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-line"><label class="ifl" for="AlipayBillingAddressLine1">Billing address line 1<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="AlipayBillingAddressLine1" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Billing address line 1 must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address line 1.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" data-val-required="Please enter a Billing address line 1.<!--EC:V1-->" id="AlipayBillingAddressLine1" maxlength="30" name="AlipayBillingAddressLine1" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-line"><label class="ifl" for="AlipayBillingAddressLine2">Billing address line 2 (Optional)</label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="AlipayBillingAddressLine2" data-valmsg-replace="true"></span><input data-val="true" data-val-length="The field Billing address line 2 (Optional) must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address line 2 (Optional).<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" id="AlipayBillingAddressLine2" maxlength="30" name="AlipayBillingAddressLine2" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-line"><label class="ifl" for="AlipayBillingAddressLine3">Billing address line 3 (Optional)</label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="AlipayBillingAddressLine3" data-valmsg-replace="true"></span><input data-val="true" data-val-length="The field Billing address line 3 (Optional) must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address line 3 (Optional).<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" id="AlipayBillingAddressLine3" maxlength="30" name="AlipayBillingAddressLine3" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-city"><label class="ifl" for="AlipayCity">City/town/department<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="AlipayCity" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field City/town/department must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid City/town/department.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z., \-]{2,}" data-val-required="Please enter a City/town/department.<!--EC:V1-->" id="AlipayCity" maxlength="30" name="AlipayCity" type="text" value=""></div> + <div class="form-group paypal-address-post-code"><label class="ifl" for="AlipayZipCode">ZIP/Postal code<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="AlipayZipCode" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field ZIP/Postal code must be a string with a maximum length of 10." data-val-length-max="10" data-val-regex="Please enter a valid ZIP/Postal code.<!--EC:V15-->" data-val-regex-pattern="[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,///-]{1,}" data-val-required="Please enter a ZIP/Postal code.<!--EC:V1-->" id="AlipayZipCode" maxlength="10" name="AlipayZipCode" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="selector fixedWidth" id="uniform-AlipayCountryCode"><span aria-hidden="true" style="-webkit-user-select: none;">United States</span><select class="phone-country-list preproc" id="AlipayCountryCode" name="AlipayCountryCode"><option selected="selected" value="US">United States</option> +<option value="CA">Canada</option> +<option value="GB">United Kingdom</option> +<option value="AG">Antigua and Barbuda</option> +<option value="AR">Argentina</option> +<option value="AW">Aruba</option> +<option value="AU">Australia</option> +<option value="BS">Bahamas</option> +<option value="BH">Bahrain</option> +<option value="BB">Barbados</option> +<option value="BE">Belgium</option> +<option value="BZ">Belize</option> +<option value="BM">Bermuda</option> +<option value="BR">Brazil</option> +<option value="CA">Canada</option> +<option value="KY">Cayman Islands</option> +<option value="CL">Chile</option> +<option value="CN">China</option> +<option value="CO">Colombia</option> +<option value="CR">Costa Rica</option> +<option value="DK">Denmark</option> +<option value="DO">Dominican Republic</option> +<option value="EC">Ecuador</option> +<option value="SV">El Salvador</option> +<option value="FR">France</option> +<option value="DE">Germany</option> +<option value="GR">Greece</option> +<option value="GU">Guam</option> +<option value="GT">Guatemala</option> +<option value="HN">Honduras</option> +<option value="HK">Hong Kong</option> +<option value="IN">India</option> +<option value="ID">Indonesia</option> +<option value="IE">Ireland</option> +<option value="IL">Israel</option> +<option value="IT">Italy</option> +<option value="JM">Jamaica</option> +<option value="JP">Japan</option> +<option value="KR">Korea, South</option> +<option value="KW">Kuwait</option> +<option value="MH">Marshall Islands</option> +<option value="MX">Mexico</option> +<option value="FM">Micronesia</option> +<option value="NL">Netherlands</option> +<option value="AN">Netherlands Antilles</option> +<option value="NZ">New Zealand</option> +<option value="NI">Nicaragua</option> +<option value="MP">Northern Mariana Islands</option> +<option value="NO">Norway</option> +<option value="PW">Palau</option> +<option value="PA">Panama</option> +<option value="PE">Peru</option> +<option value="PH">Philippines</option> +<option value="PT">Portugal</option> +<option value="PR">Puerto Rico</option> +<option value="QA">Qatar</option> +<option value="RU">Russia</option> +<option value="SG">Singapore</option> +<option value="ES">Spain & Canary Islands</option> +<option value="SE">Sweden</option> +<option value="CH">Switzerland</option> +<option value="TW">Taiwan</option> +<option value="TH">Thailand</option> +<option value="TT">Trinidad and Tobago</option> +<option value="TR">Turkey</option> +<option value="AE">United Arab Emirates</option> +<option value="GB">United Kingdom</option> +<option selected="selected" value="US">United States</option> +<option value="VN">Vietnam</option> +</select></div> + </div> + </fieldset> + </div> + <div class="section-VisaCheckout-type" style="display: none;"> + <input id="WalletVCOEnvironment" name="WalletVCOEnvironment" type="hidden" value="prod"> + <input data-val="true" data-val-required="Please enter a WalletId.<!--EC:V1-->" id="WalletId" name="WalletId" type="hidden" value=""> + <input id="WalletCardType" name="WalletCardType" type="hidden" value=""> + <input id="WalletCreditCardTypeList" name="WalletCreditCardTypeList" type="hidden" value="["VISA","JCB","MASTERCARD","AMEX","DISCOVER","DINERS","UATP"]"> + <input id="WalletBillingAddress" name="WalletBillingAddress" type="hidden" value=""> + <input id="WalletBillingCity" name="WalletBillingCity" type="hidden" value=""> + <input id="WalletBillingZipCode" name="WalletBillingZipCode" type="hidden" value=""> + <input id="WalletBillingCountryCode" name="WalletBillingCountryCode" type="hidden" value=""> + <input type="hidden" name="vcoTotalCartAmount" id="vcoTotalCartAmount"> + <input type="hidden" name="vcoCurrencyCode" id="vcoCurrencyCode"> + <p>To use Visa Checkout, click the button below. You will be prompted to log in or create an account.</p> + <button class="btn-visa" id="btnVisaCheckOut" value="Visa Checkout"> + <img class="btn-img-visa" alt="Use Visa Checkout" src="https://sandbox.secure.checkout.visa.com/wallet-services-web/xo/button.png"> + </button> + </div> + <div id="spinner-visaCheckout" class="spinner-container-visa-checkout-form" style="display: none"> </div> + <div id="form-payPal" class="form-PayPal" style="display: none"> + <div class="PayPal-selected-info"> + <i class="icon-payment-type-paypal"></i> + <p><span id="paypalName"></span>, you have selected PayPal as your payment method. PayPal account: <span id="paypalEmail"></span></p> + </div> + + <fieldset> + <legend class="visuallyhidden">Billing information <small class="rqrd" aria-hidden="true">(*Required)</small></legend> + <h4 class="legend">Billing information <small class="rqrd" aria-hidden="true">(*Required)</small></h4> + <p>Please enter the billing information associated with the specified PayPal account.</p> + <div class="form-row"> + <div class="form-group paypal-address-line"><label class="ifl" for="PayPalBillingAddress">Billing address<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="PayPalBillingAddress" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Billing address must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid Billing address.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9]{1}[A-Za-z0-9 '\-,\./#]{1,}" data-val-required="Please enter a Billing address.<!--EC:V1-->" id="PayPalBillingAddress" maxlength="30" name="PayPalBillingAddress" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-city"><label class="ifl" for="PayPalCity">City/town/department<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="PayPalCity" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field City/town/department must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid City/town/department.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z., \-]{2,}" data-val-required="Please enter a City/town/department.<!--EC:V1-->" id="PayPalCity" maxlength="30" name="PayPalCity" type="text" value=""></div> + <div class="form-group address-state"><label class="ifl" for="PayPalState">State/province/region/county<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="PayPalState" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-required="Please enter a State/province/region/county.<!--EC:V1-->" id="PayPalState" name="PayPalState" type="text" value=""></div> + <div class="form-group paypal-address-post-code"><label class="ifl" for="PayPalZipCode">ZIP/Postal code<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="PayPalZipCode" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field ZIP/Postal code must be a string with a maximum length of 10." data-val-length-max="10" data-val-regex="Please enter a valid ZIP/Postal code.<!--EC:V15-->" data-val-regex-pattern="[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,///-]{1,}" data-val-required="Please enter a ZIP/Postal code.<!--EC:V1-->" id="PayPalZipCode" maxlength="10" name="PayPalZipCode" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="selector fixedWidth" id="uniform-PayPalCountryCode"><span aria-hidden="true" style="-webkit-user-select: none;">United States</span><select class="address-country preproc" id="PayPalCountryCode" name="PayPalCountryCode"><option value="US">United States</option> +<option value="CA">Canada</option> +<option value="GB">United Kingdom</option> +<option value="AG">Antigua and Barbuda</option> +<option value="AR">Argentina</option> +<option value="AW">Aruba</option> +<option value="AU">Australia</option> +<option value="BS">Bahamas</option> +<option value="BH">Bahrain</option> +<option value="BB">Barbados</option> +<option value="BE">Belgium</option> +<option value="BZ">Belize</option> +<option value="BM">Bermuda</option> +<option value="BR">Brazil</option> +<option value="CA">Canada</option> +<option value="KY">Cayman Islands</option> +<option value="CL">Chile</option> +<option value="CN">China</option> +<option value="CO">Colombia</option> +<option value="CR">Costa Rica</option> +<option value="DK">Denmark</option> +<option value="DO">Dominican Republic</option> +<option value="EC">Ecuador</option> +<option value="SV">El Salvador</option> +<option value="FR">France</option> +<option value="DE">Germany</option> +<option value="GR">Greece</option> +<option value="GU">Guam</option> +<option value="GT">Guatemala</option> +<option value="HN">Honduras</option> +<option value="HK">Hong Kong</option> +<option value="IN">India</option> +<option value="ID">Indonesia</option> +<option value="IE">Ireland</option> +<option value="IL">Israel</option> +<option value="IT">Italy</option> +<option value="JM">Jamaica</option> +<option value="JP">Japan</option> +<option value="KR">Korea, South</option> +<option value="KW">Kuwait</option> +<option value="MH">Marshall Islands</option> +<option value="MX">Mexico</option> +<option value="FM">Micronesia</option> +<option value="NL">Netherlands</option> +<option value="AN">Netherlands Antilles</option> +<option value="NZ">New Zealand</option> +<option value="NI">Nicaragua</option> +<option value="MP">Northern Mariana Islands</option> +<option value="NO">Norway</option> +<option value="PW">Palau</option> +<option value="PA">Panama</option> +<option value="PE">Peru</option> +<option value="PH">Philippines</option> +<option value="PT">Portugal</option> +<option value="PR">Puerto Rico</option> +<option value="QA">Qatar</option> +<option value="RU">Russia</option> +<option value="SG">Singapore</option> +<option value="ES">Spain & Canary Islands</option> +<option value="SE">Sweden</option> +<option value="CH">Switzerland</option> +<option value="TW">Taiwan</option> +<option value="TH">Thailand</option> +<option value="TT">Trinidad and Tobago</option> +<option value="TR">Turkey</option> +<option value="AE">United Arab Emirates</option> +<option value="GB">United Kingdom</option> +<option value="US">United States</option> +<option value="VN">Vietnam</option> +</select></div> + </div> + </fieldset> + + </div> + <div id="form-visaCheckout" class="form-visaCheckout" style="display: none"> + <div class="visa-checkout-selected-info"> + <p>You have selected the following payment method:</p> + </div> + <div> + <div id="vcoCardToExpireMsg" class="info-msg"></div> + <div id="vcoCardBrandImage"></div> + <div id="spinner-visaCheckout-data" class="spinner-container-visa-checkout-data" style="display: none"> </div> + <div class="visa-checkout-data"> + <div id="cardNumber"></div> + <div><a id="editVisaCheckoutPayment" href="javascript:void(0);">Edit Visa Checkout payment</a> | <a id="selectDiffPaymentMethod" href="javascript:void(0);">Select a different payment method</a></div> + <div id="customerEmail"></div> + <div class="form-row" style="margin-top: 12px; display: none"> + <div id="divWalletCCSecurityCode" class="form-groupset" style="display: none; visibility: hidden"> + <div class="form-group card-security-code"><label class="ifl" for="WalletCCSecurityCode">Security code</label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="WalletCCSecurityCode" data-valmsg-replace="true"></span><input autocomplete="off" data-privacy="no-capture" id="WalletCCSecurityCode" maxlength="4" name="WalletCCSecurityCode" type="password" value=""></div> + <button type="button" class="icon-tooltip-large-clear-bg tool-tip-security-code" data-toggle="tooltip" data-tooltip-style="default" tabindex="0" data-hasqtip="4" oldtitle="What's a security code?" title=""><span class="visuallyhidden">About credit card security code</span></button> + <div class="tip-security-code"> + <div class="tip-security-code-default"> + <h6>Security code</h6> + <p>The card security code consists of the last three digits of the number on the back of your Visa, MasterCard or Discover Card, or the four digits above the main number on your American Express card.</p> + </div> + <div class="tip-security-code-visa" style="display: none;"> + <h6>Visa - CVV2</h6> + <p>The card security code consists of the last three digits of the number on the back of your Visa.</p> + <img src="https://www.united.com/web/format/img/card/CVV2_Visa.GIF" alt="Visa security code"> + </div> + <div class="tip-security-code-mc" style="display: none;"> + <h6>MasterCard - CVC2</h6> + <p>The card security code consists of the last three digits of the number on the back of your MasterCard.</p> + <img src="https://www.united.com/web/format/img/card/CVC2_MC.GIF" alt="MasterCard security code"> + </div> + <div class="tip-security-code-amex" style="display: none;"> + <h6>American Express – CID</h6> + <p>The card security code consists of the four digits above the main number on your American Express card.</p> + <img src="https://www.united.com/web/format/img/card/CID_Amex.GIF" alt="American Express security code"> + </div> + <div class="tip-security-code-discover" style="display: none;"> + <h6>Discover – CID</h6> + <p>The card security code consists of the last three digits of the number on the back of your Discover Card.</p> + <img src="https://www.united.com/web/format/img/card/CID_Discover.GIF" alt="Discover security code"> + </div> + </div> + </div> + </div> + </div> + </div> + </div> + <div id="divcashoptions"> + <fieldset class="section-cash-type form-group" style="display: none;"> + <p>If you plan to pay with cash, your reservation will be held until midnight CT on Wed, Mar 02, 2016 and must be purchased by that time or the reservation will be released for another customer to purchase.</p> + + <legend>Select where you will complete your cash purchase <small class="rqrd" aria-hidden="true">(*Required)</small></legend> + <h4 class="legend">Select where you will complete your cash purchase <small class="rqrd" aria-hidden="true">(*Required)</small></h4> + <div class="form-group group-type-radio group-type-radio-cash"> + + <div class="form-row"><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="CashType" data-valmsg-replace="true"></span><div class="radio" id="uniform-CashType_WU"><span><input aria-required="true" class="type-radio rcashtype preproc" data-number="1" data-val="true" data-val-required="Please make a selection.<!--EC:V152-->" id="CashType_WU" name="CashType" tabindex="0" type="radio" value="WU"></span></div><label class="radio" for="CashType_WU">Western Union ($11.95 service charge per transaction)</label></div> + <div class="form-row"><div class="radio" id="uniform-CashType_ATO"><span><input aria-required="true" class="type-radio rcashtype preproc" data-number="2" id="CashType_ATO" name="CashType" tabindex="0" type="radio" value="ATO"></span></div><label class="radio" for="CashType_ATO">Airport Ticket Office (service charge per transaction may apply)</label></div> + <div class="form-row"><div class="radio" id="uniform-CashType_CTO"><span><input aria-required="true" class="type-radio rcashtype preproc" data-number="3" id="CashType_CTO" name="CashType" tabindex="0" type="radio" value="CTO"></span></div><label class="radio" for="CashType_CTO">United Ticket Office (service charge per transaction may apply)</label></div> + </div> +</fieldset> + </div> + + + + + +<div id="BMLInfo" class="booking-content" style="display: none;"> + <p>PayPal Credit is a fast and secure way to pay online without using a credit card. After your ticket is confirmed, you will receive a billing statement. <a href="https://www.united.com/web/en-US/content/booking/flight/whatIsBML.aspx" target="_blank">Learn more about PayPal Credit</a></p> + <div class="form-row"> + <span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.IfForSixMonthsNoPayment" data-valmsg-replace="true"></span><div class="checker" id="uniform-BmlModel_IfForSixMonthsNoPayment"><span><input class="type-checkbox type-checkbox preproc" data-val="true" data-val-required="The IfForSixMonthsNoPayment field is required." id="BmlModel_IfForSixMonthsNoPayment" name="BmlModel.IfForSixMonthsNoPayment" type="checkbox" value="true"></span></div><input name="BmlModel.IfForSixMonthsNoPayment" type="hidden" value="false"><label class="checkbox" for="BmlModel_IfForSixMonthsNoPayment">Yes, I would like to make no payments for six months on orders greater than $250.</label> + </div> + <fieldset id="PayPal CreditInfo"> + <legend class="visuallyhidden">Apply for PayPal Credit <small class="rqrd" aria-hidden="true">(*Required)</small></legend> + <h4 class="legend" aria-hidden="true">Apply for PayPal Credit <small class="rqrd" aria-hidden="true">(*Required)</small></h4> + <p>The information entered below will be sent to PayPal Credit.</p> + <div> + <div class="form-row"> + <div class="form-group"><label class="ifl" for="BmlModel_FirstName">First name<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.FirstName" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-regex="Please enter a valid First name.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z]{1,}[A-Za-z -]{0,}" data-val-required="Please enter a First name.<!--EC:V1-->" id="BmlModel_FirstName" name="BmlModel.FirstName" type="text" value=""></div> + <div class="form-group"><label class="ifl" for="BmlModel_LastName">Last name<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.LastName" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-regex="Please enter a valid Last name.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z]{2,}[A-Za-z -]{0,}" data-val-required="Please enter a Last name.<!--EC:V1-->" id="BmlModel_LastName" name="BmlModel.LastName" type="text" value=""></div> + </div> + <div id="guestBML"> + <div class="form-row"> + <div class="form-group bml-address-line"><label class="ifl" for="BmlModel_BMLAddressLine1">Billing address<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLAddressLine1" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-required="Please enter a Billing address.<!--EC:V1-->" id="BmlModel_BMLAddressLine1" name="BmlModel.BMLAddressLine1" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group address-city"><label class="ifl" for="BmlModel_BMLCity">City<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLCity" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field City must be a string with a maximum length of 30." data-val-length-max="30" data-val-regex="Please enter a valid City.<!--EC:V15-->" data-val-regex-pattern="[A-Za-z., \-]{2,}" data-val-required="Please enter a City.<!--EC:V1-->" id="BmlModel_BMLCity" maxlength="30" name="BmlModel.BMLCity" type="text" value=""></div> + <div class="form-group address-state"><label class="ifl" for="BmlModel_BMLStateCode">State/territory/province<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLStateCode" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-required="Please enter a State/territory/province.<!--EC:V1-->" id="BmlModel_BMLStateCode" name="BmlModel.BMLStateCode" type="text" value=""></div> + <div class="form-group bml-address-post-code"><label class="ifl" for="BmlModel_BMLPostalCode">Zip/Postal code<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLPostalCode" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Zip/Postal code must be a string with a maximum length of 10." data-val-length-max="10" data-val-regex="Please enter a valid Zip/Postal code.<!--EC:V15-->" data-val-regex-pattern="[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,///-]{1,}" data-val-required="Please enter a Zip/Postal code.<!--EC:V1-->" id="BmlModel_BMLPostalCode" maxlength="10" name="BmlModel.BMLPostalCode" type="text" value=""></div> + </div> + <h4 id="countryDescription" class="legend"></h4> + <div id="divBMLGuestPhoneInputFields" style="display:"> + <div class="form-row"> + <div class="form-group"> + <div class="group-label">Phone prefix<em class="rqrd" aria-hidden="true">*</em></div> + <label for="BmlModel_BMLPhoneCountryAccessCode" class="visuallyhidden">Phone Country</label> + <div class="selector fixedWidth" id="uniform-BmlModel_BMLPhoneCountryAccessCode"><span aria-hidden="true" style="-webkit-user-select: none;">United States</span><select id="BmlModel_BMLPhoneCountryAccessCode" name="BmlModel.BMLPhoneCountryAccessCode" class="preproc"><option value="US">United States</option> +<option value="CA">Canada</option> +<option value="GB">United Kingdom</option> +<option value="AF">Afghanistan</option> +<option value="AL">Albania</option> +<option value="DZ">Algeria</option> +<option value="AS">American Samoa</option> +<option value="AD">Andorra</option> +<option value="AO">Angola</option> +<option value="AI">Anguilia</option> +<option value="AQ">Antarctica</option> +<option value="AG">Antigua and Barbuda</option> +<option value="AR">Argentina</option> +<option value="AM">Armenia</option> +<option value="AW">Aruba</option> +<option value="AU">Australia</option> +<option value="AT">Austria</option> +<option value="AZ">Azerbaijan</option> +<option value="BS">Bahamas</option> +<option value="BH">Bahrain</option> +<option value="BD">Bangladesh</option> +<option value="BB">Barbados</option> +<option value="BY">Belarus</option> +<option value="BE">Belgium</option> +<option value="BZ">Belize</option> +<option value="BJ">Benin</option> +<option value="BM">Bermuda</option> +<option value="BT">Bhutan</option> +<option value="BO">Bolivia</option> +<option value="BQ">Bonaire, Sint Eustatius and Saba</option> +<option value="BA">Bosnia and Herzegovina</option> +<option value="BW">Botswana</option> +<option value="BR">Brazil</option> +<option value="IO">British Indian Ocean Territory</option> +<option value="VG">British Virgin Islands</option> +<option value="BN">Brunei</option> +<option value="BG">Bulgaria</option> +<option value="BF">Burkina Faso</option> +<option value="BI">Burundi</option> +<option value="KH">Cambodia</option> +<option value="CM">Cameroon</option> +<option value="CV">Cape Verde</option> +<option value="KY">Cayman Islands</option> +<option value="CF">Central African Republic</option> +<option value="TD">Chad</option> +<option value="CL">Chile</option> +<option value="CN">China, People's Republic of</option> +<option value="CX">Christmas Island</option> +<option value="CC">Cocos (Keeling) Islands</option> +<option value="CO">Colombia</option> +<option value="KM">Comoros</option> +<option value="CG">Congo</option> +<option value="CD">Congo, Democratic Republic of the (Zaire)</option> +<option value="CK">Cook Islands</option> +<option value="CR">Costa Rica</option> +<option value="CI">Cote d'ivoire</option> +<option value="HR">Croatia</option> +<option value="CU">Cuba</option> +<option value="CW">Curaçao</option> +<option value="CY">Cyprus</option> +<option value="CZ">Czech Republic</option> +<option value="DK">Denmark</option> +<option value="DG">Diego Garcia</option> +<option value="DJ">Djibouti</option> +<option value="DM">Dominica</option> +<option value="DO">Dominican Republic</option> +<option value="TP">East Timor</option> +<option value="EC">Ecuador</option> +<option value="EG">Egypt</option> +<option value="SV">El Salvador</option> +<option value="GQ">Equatorial Guinea</option> +<option value="ER">Eritrea</option> +<option value="EE">Estonia</option> +<option value="ET">Ethiopia</option> +<option value="FK">Falkland Islands</option> +<option value="FO">Faroe Islands</option> +<option value="FJ">Fiji</option> +<option value="FI">Finland</option> +<option value="FR">France</option> +<option value="GF">French Guiana</option> +<option value="PF">French Polynesia</option> +<option value="GA">Gabon</option> +<option value="GM">Gambia</option> +<option value="GE">Georgia</option> +<option value="DE">Germany</option> +<option value="GH">Ghana</option> +<option value="GI">Gibraltar</option> +<option value="GR">Greece</option> +<option value="GL">Greenland</option> +<option value="GD">Grenada</option> +<option value="GP">Guadeloupe</option> +<option value="GU">Guam</option> +<option value="GT">Guatemala</option> +<option value="GN">Guinea</option> +<option value="GW">Guinea-Bissau</option> +<option value="GY">Guyana</option> +<option value="HT">Haiti</option> +<option value="HN">Honduras</option> +<option value="HK">Hong Kong</option> +<option value="HU">Hungary</option> +<option value="IS">Iceland</option> +<option value="IN">India</option> +<option value="ID">Indonesia</option> +<option value="IR">Iran</option> +<option value="IQ">Iraq</option> +<option value="IE">Ireland</option> +<option value="IL">Israel</option> +<option value="IT">Italy</option> +<option value="JM">Jamaica</option> +<option value="JP">Japan</option> +<option value="JO">Jordan</option> +<option value="KZ">Kazakhstan</option> +<option value="KE">Kenya</option> +<option value="KI">Kiribati</option> +<option value="KP">Korea, North</option> +<option value="KR">Korea, South</option> +<option value="KW">Kuwait</option> +<option value="KG">Kyrgyzstan</option> +<option value="LA">Laos</option> +<option value="LV">Latvia</option> +<option value="LB">Lebanon</option> +<option value="LS">Lesotho</option> +<option value="LR">Liberia</option> +<option value="LY">Libya</option> +<option value="LI">Liechtenstein</option> +<option value="LT">Lithuania</option> +<option value="LU">Luxembourg</option> +<option value="MO">Macau</option> +<option value="MK">Macedonia (FYROM)</option> +<option value="MG">Madagascar</option> +<option value="MW">Malawi</option> +<option value="MY">Malaysia</option> +<option value="MV">Maldives</option> +<option value="ML">Mali</option> +<option value="MT">Malta</option> +<option value="MH">Marshall Islands</option> +<option value="MQ">Martinique</option> +<option value="MR">Mauritania</option> +<option value="MU">Mauritius</option> +<option value="YT">Mayotte</option> +<option value="MX">Mexico</option> +<option value="FM">Micronesia</option> +<option value="MD">Moldova</option> +<option value="MC">Monaco</option> +<option value="MN">Mongolia</option> +<option value="ME">Montenegro</option> +<option value="MS">Montserrat</option> +<option value="MA">Morocco</option> +<option value="MZ">Mozambique</option> +<option value="MM">Myanmar (Burma)</option> +<option value="NA">Namibia</option> +<option value="NR">Nauru</option> +<option value="NP">Nepal</option> +<option value="NL">Netherlands</option> +<option value="NC">New Caledonia</option> +<option value="NZ">New Zealand</option> +<option value="NI">Nicaragua</option> +<option value="NE">Niger</option> +<option value="NG">Nigeria</option> +<option value="NU">Niue</option> +<option value="NF">Norfolk Island</option> +<option value="MP">Northern Mariana Islands</option> +<option value="NO">Norway</option> +<option value="OM">Oman</option> +<option value="PK">Pakistan</option> +<option value="PW">Palau</option> +<option value="PS">Palestinian Territories</option> +<option value="PA">Panama</option> +<option value="PG">Papua New Guinea</option> +<option value="PY">Paraguay</option> +<option value="PE">Peru</option> +<option value="PH">Philippines</option> +<option value="PN">Pitcairn</option> +<option value="PL">Poland</option> +<option value="PT">Portugal</option> +<option value="PR">Puerto Rico</option> +<option value="QA">Qatar</option> +<option value="RE">Reunion</option> +<option value="RO">Romania</option> +<option value="RU">Russia</option> +<option value="RW">Rwanda</option> +<option value="GS">South Georgia and the South Sandwich Islands</option> +<option value="BL">Saint Barthélemy</option> +<option value="KN">Saint Kitts and Nevis</option> +<option value="LC">Saint Lucia</option> +<option value="MF">Saint Martin (France)</option> +<option value="VC">Saint Vincent and the Grenadines</option> +<option value="WS">Samoa</option> +<option value="SM">San Marino</option> +<option value="ST">Sao Tome and Principe</option> +<option value="SA">Saudi Arabia</option> +<option value="SN">Senegal</option> +<option value="RS">Serbia</option> +<option value="SC">Seychelles</option> +<option value="SL">Sierra Leone</option> +<option value="SG">Singapore</option> +<option value="SX">Sint Maarten (Netherlands)</option> +<option value="SK">Slovakia</option> +<option value="SI">Slovenia</option> +<option value="SB">Solomon Islands</option> +<option value="SO">Somalia</option> +<option value="ZA">South Africa</option> +<option value="SS">South Sudan</option> +<option value="ES">Spain & Canary Islands</option> +<option value="LK">Sri Lanka</option> +<option value="SH">Saint Helena</option> +<option value="PM">Saint Pierre and Miquelon</option> +<option value="SD">Sudan</option> +<option value="SR">Suriname</option> +<option value="SJ">Svalbard and Jan Mayen Islands</option> +<option value="SZ">Swaziland</option> +<option value="SE">Sweden</option> +<option value="CH">Switzerland</option> +<option value="SY">Syria</option> +<option value="TW">Taiwan</option> +<option value="TJ">Tajikistan</option> +<option value="TZ">Tanzania</option> +<option value="TH">Thailand</option> +<option value="TG">Togo</option> +<option value="TK">Tokelau</option> +<option value="TO">Tonga</option> +<option value="TT">Trinidad and Tobago</option> +<option value="TN">Tunisia</option> +<option value="TR">Turkey</option> +<option value="TM">Turkmenistan</option> +<option value="TC">Turks and Caicos Islands</option> +<option value="TV">Tuvalu</option> +<option value="UG">Uganda</option> +<option value="UA">Ukraine</option> +<option value="AE">United Arab Emirates</option> +<option value="UM">United States Minor Outlying Islands</option> +<option value="UY">Uruguay</option> +<option value="UZ">Uzbekistan</option> +<option value="VU">Vanuatu</option> +<option value="VA">Vatican City State (Holy See)</option> +<option value="VE">Venezuela</option> +<option value="VN">Vietnam</option> +<option value="VI">U.S. Virgin Islands</option> +<option value="WF">Wallis and Futuna</option> +<option value="YE">Yemen</option> +<option value="ZM">Zambia</option> +<option value="ZW">Zimbabwe</option> +</select></div> + </div> + </div> + <div class="form-row"> + <div class="form-group"><label class="ifl" for="BmlModel_BMLPhoneNumber">Phone number<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLPhoneNumber" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-regex="Please enter a valid Phone number.<!--EC:V15-->" data-val-regex-pattern="[0-9 .+\\()/-]{6,}" data-val-required="Please enter a Phone number.<!--EC:V1-->" id="BmlModel_BMLPhoneNumber" name="BmlModel.BMLPhoneNumber" type="text" value=""></div> + <div class="form-group"><label class="ifl" for="BmlModel_BMLPhoneExtension">Extension (Optional)</label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLPhoneExtension" data-valmsg-replace="true"></span><input data-val="true" data-val-regex="Please enter a valid Extension (Optional).<!--EC:V15-->" data-val-regex-pattern="[A-Za-z0-9 ]+" id="BmlModel_BMLPhoneExtension" name="BmlModel.BMLPhoneExtension" type="text" value=""></div> + </div> + <div class="form-row"> + <div class="form-group" id="guest-bml-email"><label class="ifl" for="BmlModel_BMLEmail">Email address<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.BMLEmail" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="The field Email address must be a string with a maximum length of 75." data-val-length-max="75" data-val-regex="Please enter a valid Email address.<!--EC:V15-->" data-val-regex-pattern="^( ?)([\w\.\-_]+)@([\w\-]+)((\.([\w\-]{2,}))?)+$" data-val-required="Please enter a Email address.<!--EC:V1-->" id="BmlModel_BMLEmail" maxlength="75" name="BmlModel.BMLEmail" type="text" value=""></div> + </div> + </div> + <div id="divBMLGuestSelectedPhoneData" class="form-row"></div> + </div> + + </div> + <div class="form-row"> + For verification purposes , please enter your date of birth and the last four digits of your Social Security Number. + </div> + <div class="form-row"> + <div class="form-group bml-birth-month"> + <div class="group-label">Date of birth<em class="rqrd" aria-hidden="true">*</em></div> + <span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.DobMonth" data-valmsg-replace="true"></span> + <label for="BmlModel_DobMonth" class="visuallyhidden">Date Of Birth Month</label> + <div class="selector fixedWidth" id="uniform-BmlModel_DobMonth"><span aria-hidden="true" style="-webkit-user-select: none;">Month</span><select data-val="true" data-val-required="Please enter a Month.<!--EC:V1-->" id="BmlModel_DobMonth" name="BmlModel.DobMonth" class="preproc"><option value="">Month</option> +<option value="1">01 - January</option> +<option value="2">02 - February</option> +<option value="3">03 - March</option> +<option value="4">04 - April</option> +<option value="5">05 - May</option> +<option value="6">06 - June</option> +<option value="7">07 - July</option> +<option value="8">08 - August</option> +<option value="9">09 - September</option> +<option value="10">10 - October</option> +<option value="11">11 - November</option> +<option value="12">12 - December</option> +</select></div> + </div> + <div class="form-group date-day"> + <div class="group-label"> </div> + <div class="form-group"><label class="ifl" for="BmlModel_DobDay">DD<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.DobDay" data-valmsg-replace="true"></span><input length="2" aria-required="true" data-val="true" data-val-regex="Please enter a valid DD.<!--EC:V15-->" data-val-regex-pattern="(0[1-9]|[12]\d|3[01])" data-val-required="Please enter a DD.<!--EC:V1-->" id="BmlModel_DobDay" name="BmlModel.DobDay" type="text" value=""></div> + </div> + <div class="form-group bml-birth-year"> + <div class="group-label"> </div> + <div class="form-group"><label class="ifl" for="BmlModel_DobYear">YYYY<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.DobYear" data-valmsg-replace="true"></span><input length="4" aria-required="true" data-val="true" data-val-range="Date of Birth year cannot be greater than cuurent year." data-val-range-max="2014" data-val-range-min="1880" data-val-required="Please enter a YYYY.<!--EC:V1-->" id="BmlModel_DobYear" name="BmlModel.DobYear" type="text" value=""></div> + </div> + + <div class="form-group ssn-last-four"> + <div class="group-label">Social Security Number<em class="rqrd" aria-hidden="true">*</em></div> + <span class="ssn-hash">#### - ### -</span> <div class="form-group"><label class="ifl" for="BmlModel_SocialSN">Last 4 digits<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.SocialSN" data-valmsg-replace="true"></span><input aria-required="true" autocomplete="off" data-privacy="no-capture" data-val="true" data-val-regex="Invalid Social Security Number - last 4 digits" data-val-regex-pattern="^\d{4}$" data-val-required="Last 4 digits" id="BmlModel_SocialSN" name="BmlModel.SocialSN" type="text" value=""></div> + </div> + </div> + <p>You must read the E-Sign consent of the Terms and Conditions listed below prior to checking the following box: <a href="https://www.united.com/web/en-US/content/booking/flight/FNGENP36.pdf" target="_blank">See E-Sign printer-friendly version</a></p> + <div class="form-row"> + <div class="form-group group-type-checkbox"> + <span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.IfBMLTermsElectronicAccepted" data-valmsg-replace="true"></span><div class="checker" id="uniform-BmlModel_IfBMLTermsElectronicAccepted"><span><input class="type-checkbox type-checkbox preproc" data-val="true" data-val-mandatory="Please make a selection.<!--EC:V152-->" data-val-required="The IfBMLTermsElectronicAccepted field is required." id="BmlModel_IfBMLTermsElectronicAccepted" name="BmlModel.IfBMLTermsElectronicAccepted" type="checkbox" value="true"></span></div><input name="BmlModel.IfBMLTermsElectronicAccepted" type="hidden" value="false"><label class="checkbox" for="BmlModel_IfBMLTermsElectronicAccepted"></label> + <label for="BmlModel_IfBMLTermsElectronicAccepted">I agree to have the <a href="https://www.united.com/web/en-US/content/booking/flight/bmlTerms.aspx" target="_blank">PayPal Credit terms and conditions</a> presented electronically</label> + <div class="inline-validation-msg"></div> + </div> + </div> + <div class="form-row "> + <div> + <iframe src="https://www.securecheckout.billmelater.com/paycapture-content/fetch?hash=AU631DB5&content=/bmlweb/bmlwebtnc_iframe.html" width="100%" height="100%" class="terms"></iframe> + </div> + </div> + <div class="form-row"> + <div class="form-group group-type-checkbox"> + <span aria-hidden="true" class="field-validation-valid" data-valmsg-for="BmlModel.IfBMLTermsAccepted" data-valmsg-replace="true"></span><div class="checker" id="uniform-BmlModel_IfBMLTermsAccepted"><span><input class="type-checkbox type-checkbox preproc" data-val="true" data-val-mandatory="Please make a selection.<!--EC:V152-->" data-val-required="The IfBMLTermsAccepted field is required." id="BmlModel_IfBMLTermsAccepted" name="BmlModel.IfBMLTermsAccepted" type="checkbox" value="true"></span></div><input name="BmlModel.IfBMLTermsAccepted" type="hidden" value="false"><label class="checkbox" for="BmlModel_IfBMLTermsAccepted"></label> + <label for="BmlModel_IfBMLTermsAccepted">I agree to the <a href="https://www.united.com/web/en-US/content/booking/flight/bmlTerms.aspx" target="_blank">PayPal Credit terms and conditions</a></label> + <div class="inline-validation-msg"></div> + </div> + </div> + </fieldset> +</div> + + <div class="panel-body-section"> + <fieldset> + <legend class="visuallyhidden">Purchaser contact information</legend> + <h3 class="legend">Purchaser contact information</h3> + <div id="divEmailAddressList" class="form-row" style="display:none"> + <div class="form-group"> + <div class="selector fixedWidth" id="uniform-EmailAddressList"><span aria-hidden="true" style="-webkit-user-select: none;"></span><select id="EmailAddressList" name="EmailAddressList" class="saved-emails-list-sync preproc" onchange="UA.Account.EmailList.getSelectedEmailData('#EmailAddressList','','#hdnEmailAddressList','#divEmailAddressList','#divEmailAddressInputFields','#divSelectedEmailAddressData','/ual/en/us/flight-search/book-a-flight/billinginfo/rev/')"></select></div> + <input type="hidden" id="hdnEmailAddressList" value="1st"> + </div> + <div class="form-group"> + <aside>Your email address will be used to contact you about this reservation only.</aside> + </div> + </div> + <div class="form-row" id="divEmailAddressInputFields" style="display:"> + <div class="form-group"><label class="ifl visuallyhidden" for="PurchaserEmailAddress">Email address<em aria-hidden="true" class="rqrd">*</em></label><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="PurchaserEmailAddress" data-valmsg-replace="true"></span><input aria-required="true" data-val="true" data-val-length="Email address must be no more than 75 characters.<!--EC:V142-->" data-val-length-max="75" data-val-regex="Please enter a valid Email address.<!--EC:V15-->" data-val-regex-pattern="^( ?)([\w\.\-_]+)@([\w\-]+)((\.([\w\-]{2,}))?)+$" data-val-required="Please enter a Email address.<!--EC:V1-->" id="PurchaserEmailAddress" maxlength="75" name="PurchaserEmailAddress" type="text" value="homer.simpson.duffman@gmail.com"></div> + <div class="form-group"> + <aside>Your email address will be used to contact you about this reservation only.</aside> + </div> + </div> + <ul id="divSelectedEmailAddressData" class="field-edit-links"> + <li><a href="#" class="btn-edit-email">Edit email address</a></li> + <li><a href="#" class="btn-add-email">Add new email address</a></li> + </ul> + <div id="divPhoneList" class="form-row" style="display:none"> + <div class="selector fixedWidth" id="uniform-PhoneList"><span aria-hidden="true" style="-webkit-user-select: none;"></span><select id="PhoneList" name="PhoneList" class="saved-phones-list-sync preproc" onchange="UA.Account.PhoneList.getSelectedPhoneData('#PhoneList','','#hdnPhoneList','#divPhoneList','#divPhoneInputFields','#divSelectedPhoneData','/ual/en/us/flight-search/book-a-flight/billinginfo/rev/')"></select></div> + <input type="hidden" id="hdnPhoneList" value="1st"> + </div> + <div id="divPhoneInputFields" style="display:"> + <div class="form-row"> + <div class="form-group"><span aria-hidden="true" class="field-validation-valid" data-valmsg-for="PhoneCountryCode" data-valmsg-replace="true"></span><div class="selector fixedWidth" id="uniform-PhoneCountryCode"><span aria-hidden="true" style="-webkit-user-select: none;">United States</span><label class="ifl visuallyhidden" for="PhoneCountryCode">Country</label><select aria-label="Country" class="phone-country-list preproc" id="PhoneCountryCode" name="PhoneCountryCode"><option value=""></option> +<option selected="selected" value="US">United States</option> +<option value="CA">Canada</option> +<option value="GB">United Kingdom</option> +<option value="AF">Afghanistan</option> +<option value="AL">Albania</option> +<option value="DZ">Algeria</option> +<option value="AS">American Samoa</option> +<option value="AD">Andorra</option> +<option value="AO">Angola</option> +<option value="AI">Anguilia</option> +<option value="AQ">Antarctica</option> +<option value="AG">Antigua and Barbuda</option> +<option value="AR">Argentina</option> +<option value="AM">Armenia</option> +</select></div></div> + </div> + </div> + </fieldset> + </div> + </div> +<input id="CartId" name="CartId" type="hidden" value="83029498-98C8-4043-AA9B-106E1F89C4BF"><input id="PageError" name="PageError" type="hidden" value="False"><input id="TripInsurancePurchased" name="TripInsurancePurchased" type="hidden" value="False"><input id="AdditionalData" name="AdditionalData" type="hidden" value=""></form> \ No newline at end of file
diff --git a/chrome/test/data/autofill/heuristics/output/138_cc_checkout_united.com.out b/chrome/test/data/autofill/heuristics/output/138_cc_checkout_united.com.out new file mode 100644 index 0000000..dd699fe --- /dev/null +++ b/chrome/test/data/autofill/heuristics/output/138_cc_checkout_united.com.out
@@ -0,0 +1,54 @@ +CREDIT_CARD_TYPE | CreditCardViewModels[0].CardTypeCode | Select card type* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_NUMBER | CreditCardViewModels[0].CardNumber | Card number* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_NUMBER | | Card number* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_NUMBER | | Card number* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_EXP_MONTH | CreditCardViewModels[0].ExpMonth | Expiration month* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_EXP_4_DIGIT_YEAR | CreditCardViewModels[0].ExpYear | Year* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_VERIFICATION_CODE | CreditCardViewModels[0].SecurityCode | Security code* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_NAME_FULL | CreditCardViewModels[0].CardHolderName | Full name as it appears on your card* | | CreditCardViewModels[0].CardTypeCode_1-cc +ADDRESS_HOME_LINE1 | CreditCardViewModels[0].AddressLine1 | Billing address line 1* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_LINE2 | CreditCardViewModels[0].AddressLine2 | Billing address line 2 (Optional) | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_LINE3 | CreditCardViewModels[0].AddressLine3 | Billing address line 3 (Optional) | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_CITY | CreditCardViewModels[0].City | City/town/department* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_STATE | CreditCardViewModels[0].StateCode | State/province/region/county* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_ZIP | CreditCardViewModels[0].PostalCode | ZIP/Postal code* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_COUNTRY | CreditCardViewModels[0].CountryCode | Country* | US | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | FOPOption | Other forms of payment | OtherFop | CreditCardViewModels[0].CardTypeCode_1-default +CREDIT_CARD_TYPE | OtherFOPType | Form of payment | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_NAME_FULL | AlipayCardHolderName | Full name as it appears on your card* | | CreditCardViewModels[0].CardTypeCode_1-cc +ADDRESS_HOME_LINE1 | AlipayBillingAddressLine1 | Billing address line 1* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_LINE2 | AlipayBillingAddressLine2 | Billing address line 2 (Optional) | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_LINE3 | AlipayBillingAddressLine3 | Billing address line 3 (Optional) | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_CITY | AlipayCity | City/town/department* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_ZIP | AlipayZipCode | ZIP/Postal code* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_COUNTRY | AlipayCountryCode | United States | US | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_LINE1 | PayPalBillingAddress | Billing address* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_CITY | PayPalCity | City/town/department* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_STATE | PayPalState | State/province/region/county* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_ZIP | PayPalZipCode | ZIP/Postal code* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_COUNTRY | PayPalCountryCode | United States | US | CreditCardViewModels[0].CardTypeCode_1-default +CREDIT_CARD_VERIFICATION_CODE | WalletCCSecurityCode | Security code | | CreditCardViewModels[0].CardTypeCode_1-cc +UNKNOWN_TYPE | CashType | Western Union ($11.95 service charge per transaction) | WU | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | CashType | Airport Ticket Office (service charge per transaction may apply) | ATO | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | CashType | United Ticket Office (service charge per transaction may apply) | CTO | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.IfForSixMonthsNoPayment | Yes, I would like to make no payments for six months on orders greater than $250. | true | CreditCardViewModels[0].CardTypeCode_1-default +CREDIT_CARD_NAME_FIRST | BmlModel.FirstName | First name* | | CreditCardViewModels[0].CardTypeCode_1-cc +CREDIT_CARD_NAME_LAST | BmlModel.LastName | Last name* | | CreditCardViewModels[0].CardTypeCode_1-cc +ADDRESS_HOME_LINE1 | BmlModel.BMLAddressLine1 | Billing address* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_CITY | BmlModel.BMLCity | City* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_STATE | BmlModel.BMLStateCode | State/territory/province* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_ZIP | BmlModel.BMLPostalCode | Zip/Postal code* | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_COUNTRY | BmlModel.BMLPhoneCountryAccessCode | Phone Country | US | CreditCardViewModels[0].CardTypeCode_1-default +PHONE_HOME_WHOLE_NUMBER | BmlModel.BMLPhoneNumber | Phone number* | | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.BMLPhoneExtension | Extension (Optional) | | CreditCardViewModels[0].CardTypeCode_1-default +EMAIL_ADDRESS | BmlModel.BMLEmail | Email address* | | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.DobMonth | Date Of Birth Month | | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.DobDay | DD* | | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.DobYear | YYYY* | | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.SocialSN | Last 4 digits* | | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.IfBMLTermsElectronicAccepted | I agree to have the PayPal Credit terms and conditions presented electronically | true | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | BmlModel.IfBMLTermsAccepted | I agree to the PayPal Credit terms and conditions | true | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | EmailAddressList | Your email address will be used to contact you about this reservation only. | | CreditCardViewModels[0].CardTypeCode_1-default +EMAIL_ADDRESS | PurchaserEmailAddress | Email address* | homer.simpson.duffman@gmail.com | CreditCardViewModels[0].CardTypeCode_1-default +UNKNOWN_TYPE | PhoneList | | | CreditCardViewModels[0].CardTypeCode_1-default +ADDRESS_HOME_COUNTRY | PhoneCountryCode | Country | US | CreditCardViewModels[0].CardTypeCode_1-default
diff --git a/chrome/test/data/autofill/heuristics/output/27_checkout_cc_keurig.com.out b/chrome/test/data/autofill/heuristics/output/27_checkout_cc_keurig.com.out deleted file mode 100644 index ee43f6bf..0000000 --- a/chrome/test/data/autofill/heuristics/output/27_checkout_cc_keurig.com.out +++ /dev/null
@@ -1,10 +0,0 @@ -CREDIT_CARD_NAME_FIRST | card_firstNameOnCard | First Name* | | card_firstNameOnCard_1-cc -CREDIT_CARD_NAME_LAST | card_lastNameOnCard | Last Name* | | card_firstNameOnCard_1-cc -CREDIT_CARD_NUMBER | card_accountNumber | Card Number* | | card_firstNameOnCard_1-cc -CREDIT_CARD_TYPE | card_cardType | Card Type | | card_firstNameOnCard_1-cc -UNKNOWN_TYPE | | Please select a card type | | card_firstNameOnCard_1-default -UNKNOWN_TYPE | card_expirationMonth | Expiration Date* | | card_firstNameOnCard_1-default -UNKNOWN_TYPE | | Month | | card_firstNameOnCard_1-default -CREDIT_CARD_EXP_MONTH | card_expirationYear | Expiration Date* | | card_firstNameOnCard_1-cc -CREDIT_CARD_EXP_4_DIGIT_YEAR | | Year | | card_firstNameOnCard_1-cc -CREDIT_CARD_VERIFICATION_CODE | card_cvNumber | Security Code* | | card_firstNameOnCard_1-cc
diff --git a/chrome/test/data/extensions/api_test/input_ime_nonchromeos/background.js b/chrome/test/data/extensions/api_test/input_ime_nonchromeos/background.js index 3cb752d..e3ba1d6 100644 --- a/chrome/test/data/extensions/api_test/input_ime_nonchromeos/background.js +++ b/chrome/test/data/extensions/api_test/input_ime_nonchromeos/background.js
@@ -32,6 +32,10 @@ chrome.test.assertTrue(!!win); chrome.test.assertTrue(win instanceof Window); chrome.test.assertFalse(win.document.webkitHidden); + // Test for security origin. + // If security origin is not correctly set, there will be securtiy + // exceptions when accessing DOM or add event listeners. + win.addEventListener('unload', function() {}); chrome.test.succeed(); }); }, @@ -40,7 +44,12 @@ chrome.input.ime.createWindow(options, function(win) { chrome.test.assertNoLastError() chrome.test.assertTrue(!!win); + chrome.test.assertTrue(win instanceof Window); chrome.test.assertFalse(win.document.webkitHidden); + // test for security origin. + // If security origin is not correctly set, there will be securtiy + // exceptions when accessing DOM or add event listeners. + win.addEventListener('unload', function() {}); chrome.test.succeed(); }); }
diff --git a/chrome/test/data/extensions/api_test/media_galleries/gallerywatch/test.js b/chrome/test/data/extensions/api_test/media_galleries/gallerywatch/test.js index a4e14f7..ac5d63dd 100644 --- a/chrome/test/data/extensions/api_test/media_galleries/gallerywatch/test.js +++ b/chrome/test/data/extensions/api_test/media_galleries/gallerywatch/test.js
@@ -25,26 +25,6 @@ } }; -// chrome.mediaGalleries.getAllGalleryWatch callback. -var getAllGalleryWatchCallback = function (results) { - if (!results) { - chrome.test.sendMessage('get_all_gallery_watch_failed'); - return; - } - if (results.length == 0) { - chrome.test.sendMessage('gallery_watchers_does_not_exists'); - } else { - for (var i = 0; i < results.length; ++i) { - var info = chrome.mediaGalleries.getMediaFileSystemMetadata(galleries[i]); - if (results[i] !== info.galleryId) { - chrome.test.sendMessage('gallery_watcher_mismatch'); - return; - } - } - chrome.test.sendMessage('gallery_watcher_checks'); - } -}; - var onGalleryChangedCheckingCallback = function(result) { if (result.galleryId != '' && result.type == 'contents_changed') { chrome.test.sendMessage('on_gallery_changed_checking_ok'); @@ -128,13 +108,3 @@ onGalleryChangedCallback); chrome.test.sendMessage('remove_gallery_changed_listener_ok'); }; - -function getAllWatchedGalleryIds() { - chrome.mediaGalleries.getAllGalleryWatch(getAllGalleryWatchCallback); - chrome.test.sendMessage('get_all_gallery_watch_ok'); -}; - -function removeAllGalleryWatch() { - chrome.mediaGalleries.removeAllGalleryWatch(); - chrome.test.sendMessage('remove_all_gallery_watch_ok'); -};
diff --git a/chrome/test/data/extensions/api_test/media_galleries/read_access/test.js b/chrome/test/data/extensions/api_test/media_galleries/read_access/test.js index 5987e917..561677a 100644 --- a/chrome/test/data/extensions/api_test/media_galleries/read_access/test.js +++ b/chrome/test/data/extensions/api_test/media_galleries/read_access/test.js
@@ -74,67 +74,6 @@ TestFirstFilesystem(verifyFilesystem); } -function GetAllMediaFileSystemMetadataTest() { - function verifyMetadataList(metadataList) { - chrome.test.assertEq(1, metadataList.length) - checkMetadata(metadataList[0]); - chrome.test.succeed(); - } - - mediaGalleries.getAllMediaFileSystemMetadata(verifyMetadataList); -} - -function DropPermissionForMediaFileSystemTest() { - var droppedFilesystem; - var droppedGalleryId; - - function callDropPermission(filesystem) { - var metadata = mediaGalleries.getMediaFileSystemMetadata(filesystem); - droppedFilesystem = filesystem; - droppedGalleryId = metadata.galleryId; - mediaGalleries.dropPermissionForMediaFileSystem( - droppedGalleryId, - chrome.test.callbackPass(onDropPermissionSucceeded)); - } - - function onDropPermissionSucceeded() { - var metadata = mediaGalleries.getMediaFileSystemMetadata(droppedFilesystem); - var notFoundMetadata = { - "name": "", - "galleryId": "", - "isRemovable": false, - "isMediaDevice": false, - "isAvailable": false, - } - chrome.test.assertEq(notFoundMetadata, metadata); - mediaGalleries.getMediaFileSystems(verifyNoFileSystemAccess); - } - - function verifyNoFileSystemAccess(results) { - chrome.test.assertEq(0, results.length); - mediaGalleries.dropPermissionForMediaFileSystem( - droppedGalleryId, - chrome.test.callbackFail("Failed to set gallery permission.", - onDropPermissionFailed)); - } - - function onDropPermissionFailed() { - mediaGalleries.dropPermissionForMediaFileSystem( - "badid", - chrome.test.callbackFail("Invalid gallery id.", - onDropPermissionFailedForInvalidGallery)); - } - - function onDropPermissionFailedForInvalidGallery() { - mediaGalleries.dropPermissionForMediaFileSystem( - "99999", - chrome.test.callbackFail("Non-existent gallery id.", - chrome.test.succeed)); - } - - TestFirstFilesystem(callDropPermission); -} - CreateDummyWindowToPreventSleep(); chrome.test.getConfig(function(config) { @@ -146,7 +85,5 @@ ReadFileToBytesTest, GetMetadataTest, GetMediaFileSystemMetadataTest, - GetAllMediaFileSystemMetadataTest, - DropPermissionForMediaFileSystemTest, ]); })
diff --git a/chrome/test/data/extensions/api_test/preference/data_reduction_proxy/test.js b/chrome/test/data/extensions/api_test/preference/data_reduction_proxy/test.js index 54c6e49..712fa60b 100644 --- a/chrome/test/data/extensions/api_test/preference/data_reduction_proxy/test.js +++ b/chrome/test/data/extensions/api_test/preference/data_reduction_proxy/test.js
@@ -7,7 +7,6 @@ // --gtest_filter=ExtensionPreferenceApiTest.DataReductionProxy var dataReductionProxy = chrome.dataReductionProxy; -var privatePreferences = chrome.preferencesPrivate; chrome.test.runTests([ function getDrpPrefs() { dataReductionProxy.spdyProxyEnabled.get({}, chrome.test.callbackPass( @@ -19,141 +18,48 @@ }, result); })); - dataReductionProxy.dataReductionDailyContentLength.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': [], - 'levelOfControl': 'controllable_by_this_extension' - }, - result); - })); - dataReductionProxy.dataReductionDailyReceivedLength.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': [], - 'levelOfControl': 'controllable_by_this_extension' - }, - result); - })); - privatePreferences.dataReductionUpdateDailyLengths.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': false - }, - result); - })); - }, - function updateDailyLengths() { - dataReductionProxy.dataReductionDailyContentLength.onChange.addListener( - confirmDailyContentLength); - dataReductionProxy.dataReductionDailyReceivedLength.onChange.addListener( - confirmRecievedLength); - - // Trigger calls to confirmDailyContentLength.onChange and - // dataReductionDailyReceivedLength.onChange listeners. - dataReductionProxy.spdyProxyEnabled.set({ 'value': true }); - privatePreferences.dataReductionUpdateDailyLengths.set({'value': true}); - - // Helper methods. - var expectedDailyLengths = []; - for (var i = 0; i < 60; i++) { - expectedDailyLengths[i] = '0'; - } - function confirmRecievedLength() { - dataReductionProxy.dataReductionDailyReceivedLength.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': expectedDailyLengths , - 'levelOfControl': 'controllable_by_this_extension' - }, - result); - })); - privatePreferences.dataReductionUpdateDailyLengths.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': false - }, - result); - })); - } - function confirmDailyContentLength() { - dataReductionProxy.dataReductionDailyContentLength.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': expectedDailyLengths , - 'levelOfControl': 'controllable_by_this_extension' - }, - result); - dataReductionProxy.dataReductionDailyContentLength.onChange. - removeListener(confirmDailyContentLength); - })); - privatePreferences.dataReductionUpdateDailyLengths.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': false - }, - result); - dataReductionProxy.dataReductionDailyReceivedLength.onChange. - removeListener(confirmRecievedLength); - })); - } }, function clearDataSavings() { + dataReductionProxy.dataUsageReportingEnabled.set({ 'value': true }); dataReductionProxy.spdyProxyEnabled.set({ 'value': true }); - dataReductionProxy.clearDataSavings(function() { - // Confirm that data is cleared - dataReductionProxy.dataReductionDailyContentLength.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': [], - 'levelOfControl': 'controllable_by_this_extension' - }, - result); - })); - dataReductionProxy.dataReductionDailyReceivedLength.get({}, - chrome.test.callbackPass(function(result) { - chrome.test.assertEq( - { - 'value': [], - 'levelOfControl': 'controllable_by_this_extension' - }, - result); - })); - }); + verifyDataUsage(20, chrome.test.callbackPass(function() { + dataReductionProxy.clearDataSavings(function() { + verifyDataUsage(1, null); + }); + })); }, function dataUsageReporting() { dataReductionProxy.dataUsageReportingEnabled.set({ 'value': true }); - // Data usage reporting takes some time to initialize before a call to - // |getDataUsage| is successful. If |getDataUsage| gives us an empty array, - // we retry after some delay. Test will report failure if the expected - // data usage is not returned after 20 retries. - var verifyDataUsage = function(numRetries) { - chrome.test.assertTrue(numRetries != 0); - - setTimeout(chrome.test.callbackPass(function() { - dataReductionProxy.getDataUsage(chrome.test.callbackPass( - function(data_usage) { - chrome.test.assertTrue('data_usage_buckets' in data_usage); - if (data_usage['data_usage_buckets'].length == 0) { - verifyDataUsage(numRetries - 1); - } else { - chrome.test.assertEq(5760, - data_usage['data_usage_buckets'].length); - } - })); - }), 1000); - }; - - verifyDataUsage(20); + verifyDataUsage(20, null); } ]); + +// Data usage reporting takes some time to initialize before a call to +// |getDataUsage| is successful. If |getDataUsage| gives us an empty array, +// we retry after some delay. Test will report failure if the expected data +// usage is not returned after |numRetries| retries. +// We don't have a way to populate actual data usage in a browser test, so we +// only check the length of the returned data usage array. +// The |onVerifyDone| callback, if present, is executed after verifying data +// usage. +function verifyDataUsage(numRetries, onVerifyDone) { + chrome.test.assertTrue(numRetries != 0); + + setTimeout(chrome.test.callbackPass(function() { + dataReductionProxy.getDataUsage(chrome.test.callbackPass( + function(data_usage) { + chrome.test.assertTrue('data_usage_buckets' in data_usage); + if (data_usage['data_usage_buckets'].length == 0) { + verifyDataUsage(numRetries - 1, onVerifyDone); + } else { + chrome.test.assertEq(5760, + data_usage['data_usage_buckets'].length); + if (onVerifyDone) { + onVerifyDone(); + } + } + })); + }), 1000); +}; \ No newline at end of file
diff --git a/chrome/test/data/webui/cr_reload_test.html b/chrome/test/data/webui/cr_reload_test.html new file mode 100644 index 0000000..d3bb982 --- /dev/null +++ b/chrome/test/data/webui/cr_reload_test.html
@@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html> +<body> + +<script> + +function testCrUIStillExists() { + assertFalse(cr.ui == undefined); +} + +</script> + +</body> +</html>
diff --git a/chrome/test/data/webui/md_history/history_item_test.js b/chrome/test/data/webui/md_history/history_item_test.js index aede65c..a0b1510 100644 --- a/chrome/test/data/webui/md_history/history_item_test.js +++ b/chrome/test/data/webui/md_history/history_item_test.js
@@ -11,6 +11,12 @@ {"time": "1"} ]; + var SEARCH_HISTORY_RESULTS = [ + {"dateShort": "Feb 22, 2016"}, + {"dateShort": "Feb 21, 2016"}, + {"dateShort": "Feb 21, 2016"}, + ]; + function registerTests() { suite('history-item', function() { var element; @@ -20,12 +26,12 @@ }); setup(function() { - element.addNewResults(TEST_HISTORY_RESULTS); + element.addNewResults(TEST_HISTORY_RESULTS, ''); }); test('basic separator insertion', function(done) { flush(function() { - // Check that the correct numbegitr of time gaps are inserted. + // Check that the correct number of time gaps are inserted. var items = Polymer.dom(element.root).querySelectorAll('history-item'); @@ -39,6 +45,20 @@ }); }); + test('separator insertion for search', function(done) { + element.addNewResults(SEARCH_HISTORY_RESULTS, 'search'); + flush(function() { + var items = + Polymer.dom(element.root).querySelectorAll('history-item'); + + assertTrue(items[0].hasTimeGap); + assertFalse(items[1].hasTimeGap); + assertFalse(items[2].hasTimeGap); + + done(); + }); + }); + test('separator insertion after deletion', function(done) { flush(function() { items = Polymer.dom(element.root).querySelectorAll('history-item');
diff --git a/chrome/test/data/webui/md_history/history_list_test.js b/chrome/test/data/webui/md_history/history_list_test.js index c29e086d..ef043ba 100644 --- a/chrome/test/data/webui/md_history/history_list_test.js +++ b/chrome/test/data/webui/md_history/history_list_test.js
@@ -7,18 +7,22 @@ var TEST_HISTORY_RESULTS = [ { "dateRelativeDay": "Today - Wednesday, December 9, 2015", + "title": "Google", "url": "https://www.google.com" }, { "dateRelativeDay": "Yesterday - Tuesday, December 8, 2015", + "title": "Wikipedia", "url": "https://en.wikipedia.com" }, { "dateRelativeDay": "Monday, December 7, 2015", + "title": "Example", "url": "https://www.example.com" }, { "dateRelativeDay": "Monday, December 7, 2015", + "title": "Google", "url": "https://www.google.com" } ]; @@ -52,11 +56,8 @@ toolbar = $('toolbar'); }); - setup(function() { - element.addNewResults(TEST_HISTORY_RESULTS); - }); - test('setting first and last items', function() { + element.addNewResults(TEST_HISTORY_RESULTS, ''); assertTrue(element.historyData[0].isLastItem); assertTrue(element.historyData[0].isFirstItem); assertTrue(element.historyData[2].isFirstItem); @@ -64,6 +65,7 @@ }); test('cancelling selection of multiple items', function(done) { + element.addNewResults(TEST_HISTORY_RESULTS, ''); flush(function() { var items = Polymer.dom(element.root) .querySelectorAll('history-item'); @@ -95,7 +97,8 @@ }); test('updating history results', function(done) { - element.addNewResults(ADDITIONAL_RESULTS); + element.addNewResults(TEST_HISTORY_RESULTS, ''); + element.addNewResults(ADDITIONAL_RESULTS, ''); flush(function() { assertTrue(element.historyData[2].isFirstItem); @@ -112,6 +115,7 @@ }); test('removeVisits for multiple items', function(done) { + element.addNewResults(TEST_HISTORY_RESULTS, ''); // Ensure that the correct identifying data is being used for removal. registerMessageCallback('removeVisits', this, function (toBeRemoved) { @@ -136,7 +140,8 @@ }); test('deleting multiple items from view', function(done) { - element.addNewResults(ADDITIONAL_RESULTS); + element.addNewResults(TEST_HISTORY_RESULTS, ''); + element.addNewResults(ADDITIONAL_RESULTS, ''); flush(function() { items = Polymer.dom(element.root).querySelectorAll('history-item'); @@ -172,6 +177,41 @@ }); }); + test('search results display with correct item title', function(done) { + element.addNewResults(TEST_HISTORY_RESULTS, 'Google'); + + flush(function() { + var heading = + element.$$('history-item').$$('#date-accessed').textContent; + var title = element.$$('history-item').$.title; + + // Check that the card title displays the search term somewhere. + var index = heading.indexOf('Google'); + assertTrue(index != -1); + + // Check that the search term is bolded correctly in the history-item. + assertEquals(title.innerHTML, '<b>Google</b>'); + done(); + }); + }); + + test('correct display message when no history available', function(done) { + element.addNewResults([], ''); + + flush(function() { + assertFalse(element.$['no-results'].hidden); + assertTrue(element.$['infinite-list'].hidden); + + element.addNewResults(TEST_HISTORY_RESULTS, ''); + + flush(function() { + assertTrue(element.$['no-results'].hidden); + assertFalse(element.$['infinite-list'].hidden); + done(); + }); + }); + }); + teardown(function() { element.historyData = []; });
diff --git a/chrome/test/data/webui/md_history/history_overflow_menu_test.js b/chrome/test/data/webui/md_history/history_overflow_menu_test.js index e264d4e8..aa2307e7 100644 --- a/chrome/test/data/webui/md_history/history_overflow_menu_test.js +++ b/chrome/test/data/webui/md_history/history_overflow_menu_test.js
@@ -6,13 +6,13 @@ // Menu button event. var MENU_EVENT = { detail: { - accessTime: 1 + target: null } }; var ADDITIONAL_MENU_EVENT = { detail: { - accessTime: 2 + target: null } }; @@ -22,31 +22,43 @@ suiteSetup(function() { element = $('history-list'); + + var element1 = document.createElement('div'); + var element2 = document.createElement('div'); + document.body.appendChild(element1); + document.body.appendChild(element2); + + MENU_EVENT.detail.target = element1; + ADDITIONAL_MENU_EVENT.detail.target = element2; }); test('opening and closing menu', function() { element.toggleMenu_(MENU_EVENT); - assertEquals(true, element.menuOpen); - assertEquals(1, element.menuIdentifier); + assertEquals(true, element.$.sharedMenu.menuOpen); + assertEquals(MENU_EVENT.detail.target, + element.$.sharedMenu.lastAnchor_); // Test having the same menu event (pressing the same button) closes the // overflow menu. element.toggleMenu_(MENU_EVENT); - assertEquals(false, element.menuOpen); + assertEquals(false, element.$.sharedMenu.menuOpen); // Test having consecutive distinct menu events moves the menu to the // new button. element.toggleMenu_(MENU_EVENT); element.toggleMenu_(ADDITIONAL_MENU_EVENT); - assertEquals(2, element.menuIdentifier); - assertEquals(true, element.menuOpen); + assertEquals(ADDITIONAL_MENU_EVENT.detail.target, + element.$.sharedMenu.lastAnchor_); + assertEquals(true, element.$.sharedMenu.menuOpen); element.toggleMenu_(MENU_EVENT); - assertEquals(true, element.menuOpen); - assertEquals(1, element.menuIdentifier); + assertEquals(true, element.$.sharedMenu.menuOpen); + assertEquals(MENU_EVENT.detail.target, + element.$.sharedMenu.lastAnchor_); - element.closeMenu(); - assertEquals(false, element.menuOpen); - assertEquals(1, element.menuIdentifier); + element.$.sharedMenu.closeMenu(); + assertEquals(false, element.$.sharedMenu.menuOpen); + assertEquals(MENU_EVENT.detail.target, + element.$.sharedMenu.lastAnchor_); }); test('keyboard input for closing menu', function() { @@ -55,11 +67,11 @@ // TODO(yingran): Fix this behavior to only require one key press. element.toggleMenu_(MENU_EVENT); MockInteractions.pressAndReleaseKeyOn(document, 27); - assertEquals(false, element.menuOpen); + assertEquals(false, element.$.sharedMenu.menuOpen); }); teardown(function() { - element.menuIdentifier = 0; + element.$.sharedMenu.lastAnchor_ = null; }); }); }
diff --git a/chrome/test/data/webui/md_history/history_toolbar_test.js b/chrome/test/data/webui/md_history/history_toolbar_test.js index 3a80866..77a9a70 100644 --- a/chrome/test/data/webui/md_history/history_toolbar_test.js +++ b/chrome/test/data/webui/md_history/history_toolbar_test.js
@@ -7,6 +7,7 @@ var TEST_HISTORY_RESULTS = [ { "dateRelativeDay": "Today - Wednesday, December 9, 2015", + "title": "Google", "url": "https://www.google.com" } ]; @@ -22,7 +23,7 @@ }); test('selecting checkbox causes toolbar to change', function(done) { - element.addNewResults(TEST_HISTORY_RESULTS); + element.addNewResults(TEST_HISTORY_RESULTS, ''); flush(function() { var item = element.$$('history-item'); @@ -47,7 +48,17 @@ }); }); + test('search term gathered correctly from toolbar', function(done) { + registerMessageCallback('queryHistory', this, function (info) { + assertEquals(info[0], 'Test'); + done(); + }); + + toolbar.onSearch('Test'); + }); + teardown(function() { + element.historyData = []; toolbar.count = 0; }); });
diff --git a/chrome/test/data/webui/settings/reset_page_test.js b/chrome/test/data/webui/settings/reset_page_test.js index 2445718..8eac592 100644 --- a/chrome/test/data/webui/settings/reset_page_test.js +++ b/chrome/test/data/webui/settings/reset_page_test.js
@@ -93,11 +93,12 @@ /** - * @param {string} closeButtonId The ID of the button that closes the - * dialog. + * @param {function(SettingsResetProfileDialogElemeent):!Element} + * closeButtonFn A function that returns the button to be used for + * closing the dialog. * @return {!Promise} */ - function testOpenCloseResetProfileDialog(closeButtonId) { + function testOpenCloseResetProfileDialog(closeButtonFn) { var onShowResetProfileDialogCalled = whenChromeSendCalled( 'onShowResetProfileDialog'); var onHideResetProfileDialogCalled = whenChromeSendCalled( @@ -111,7 +112,7 @@ dialog.addEventListener('iron-overlay-closed', resolve); }); - MockInteractions.tap(dialog.$[closeButtonId]); + MockInteractions.tap(closeButtonFn(dialog)); return Promise.all([ onShowResetProfileDialogCalled, @@ -125,9 +126,11 @@ test(TestNames.ResetProfileDialogOpenClose, function() { return Promise.all([ // Test case where the 'cancel' button is clicked. - testOpenCloseResetProfileDialog('cancel'), + testOpenCloseResetProfileDialog( + function(dialog) { return dialog.$.cancel;}), // Test case where the 'close' button is clicked. - testOpenCloseResetProfileDialog('close') + testOpenCloseResetProfileDialog( + function(dialog) { return dialog.$.dialog.getCloseButton(); }), ]); }); @@ -144,11 +147,12 @@ if (cr.isChromeOS) { /** - * @param {string} closeButtonId The ID of the button that closes the - * dialog. + * @param {function(SettingsPowerwashDialogElemeent):!Element} + * closeButtonFn A function that returns the button to be used for + * closing the dialog. * @return {!Promise} */ - function testOpenClosePowerwashDialog(closeButtonId) { + function testOpenClosePowerwashDialog(closeButtonFn) { var onPowerwashDialogShowCalled = whenChromeSendCalled( 'onPowerwashDialogShow'); @@ -160,7 +164,7 @@ dialog.addEventListener('iron-overlay-closed', resolve); }); - MockInteractions.tap(dialog.$[closeButtonId]); + MockInteractions.tap(closeButtonFn(dialog)); return Promise.all([onPowerwashDialogShowCalled, onDialogClosed]); } @@ -169,9 +173,11 @@ test(TestNames.PowerwashDialogOpenClose, function() { return Promise.all([ // Test case where the 'cancel' button is clicked. - testOpenClosePowerwashDialog('cancel'), + testOpenClosePowerwashDialog( + function(dialog) { return dialog.$.cancel; }), // Test case where the 'close' button is clicked. - testOpenClosePowerwashDialog('close') + testOpenClosePowerwashDialog( + function(dialog) { return dialog.$.dialog.getCloseButton(); }), ]); });
diff --git a/chrome/test/data/webui/settings/search_engines_page_test.js b/chrome/test/data/webui/settings/search_engines_page_test.js index e4b4b94..002bbd4 100644 --- a/chrome/test/data/webui/settings/search_engines_page_test.js +++ b/chrome/test/data/webui/settings/search_engines_page_test.js
@@ -172,7 +172,7 @@ test('DialogOpenAndClose', function() { return browserProxy.whenCalled('searchEngineEditStarted').then( function() { - MockInteractions.tap(dialog.$.close); + MockInteractions.tap(dialog.$.dialog.getCloseButton()); return browserProxy.whenCalled('searchEngineEditCancelled'); }); });
diff --git a/chrome/test/data/webui/util_test.html b/chrome/test/data/webui/util_test.html new file mode 100644 index 0000000..0c8c4ea --- /dev/null +++ b/chrome/test/data/webui/util_test.html
@@ -0,0 +1,25 @@ +<!DOCTYPE html> +<html> +<body> +<script> + +function testQuoteString() { + // Basic cases. + assertEquals('\"test\"', quoteString('"test"')); + assertEquals('\\!\\?', quoteString('!?')); + assertEquals('\\(\\._\\.\\) \\( \\:l \\) \\(\\.-\\.\\)', + quoteString('(._.) ( :l ) (.-.)')); + + // Using the output as a regex. + var re = new RegExp(quoteString('"hello"'), 'gim'); + var match = re.exec('She said "Hello" loudly'); + assertEquals(9, match.index); + + re = new RegExp(quoteString('Hello, .*'), 'gim'); + match = re.exec('Hello, world'); + assertEquals(null, match); +} + +</script> +</body> +</html>
diff --git a/chrome/test/data/webui/webui_resource_browsertest.cc b/chrome/test/data/webui/webui_resource_browsertest.cc index 28b0a55e..b1d55188 100644 --- a/chrome/test/data/webui/webui_resource_browsertest.cc +++ b/chrome/test/data/webui/webui_resource_browsertest.cc
@@ -74,6 +74,15 @@ LoadFile(base::FilePath(FILE_PATH_LITERAL("cr_test.html"))); } +IN_PROC_BROWSER_TEST_F(WebUIResourceBrowserTest, CrReloadTest) { + AddLibrary(IDR_WEBUI_JS_CR); + AddLibrary(IDR_WEBUI_JS_CR_UI); + // Loading cr.js again on purpose to check whether it overwrites the cr + // namespace. + AddLibrary(IDR_WEBUI_JS_CR); + LoadFile(base::FilePath(FILE_PATH_LITERAL("cr_reload_test.html"))); +} + IN_PROC_BROWSER_TEST_F(WebUIResourceBrowserTest, EventTargetTest) { AddLibrary(IDR_WEBUI_JS_CR); AddLibrary(IDR_WEBUI_JS_CR_EVENT_TARGET); @@ -225,3 +234,8 @@ AddLibrary(IDR_WEBUI_JS_CR_UI_SPLITTER); LoadFile(base::FilePath(FILE_PATH_LITERAL("splitter_test.html"))); } + +IN_PROC_BROWSER_TEST_F(WebUIResourceBrowserTest, UtilTest) { + AddLibrary(IDR_WEBUI_JS_UTIL); + LoadFile(base::FilePath(FILE_PATH_LITERAL("util_test.html"))); +}
diff --git a/chrome/test/media_router/media_router_integration_ui_browsertest.cc b/chrome/test/media_router/media_router_integration_ui_browsertest.cc index b11c41f..b33e93e5 100644 --- a/chrome/test/media_router/media_router_integration_ui_browsertest.cc +++ b/chrome/test/media_router/media_router_integration_ui_browsertest.cc
@@ -33,15 +33,15 @@ ChooseSink(web_contents, kTestSinkName); -// Linux bots run browser tests without a physical display, which is causing -// flaky event dispatching of mouseenter and mouseleave events. This causes -// the dialog to sometimes close prematurely even though a mouseenter event -// is explicitly dispatched in the test. -// Here, we still dispatch the mouseenter event for OSX and Windows, but close -// the dialog and reopen it on Linux. +// Linux and Windows bots run browser tests without a physical display, which +// is causing flaky event dispatching of mouseenter and mouseleave events. This +// causes the dialog to sometimes close prematurely even though a mouseenter +// event is explicitly dispatched in the test. +// Here, we still dispatch the mouseenter event for OSX, but close +// the dialog and reopen it on Linux and Windows. // The test succeeds fine when run with a physical display. -// http://crbug.com/577943 -#if defined(OS_MACOSX) || defined(OS_WIN) +// http://crbug.com/577943 http://crbug.com/591779 +#if defined(OS_MACOSX) // Simulate keeping the mouse on the dialog to prevent it from automatically // closing after the route has been created. Then, check that the dialog // remains open. @@ -53,9 +53,9 @@ #endif WaitUntilRouteCreated(); -#if defined(OS_MACOSX) || defined(OS_WIN) +#if defined(OS_MACOSX) CheckDialogRemainsOpen(web_contents); -#elif defined(OS_LINUX) +#elif defined(OS_LINUX) || defined(OS_WIN) Wait(base::TimeDelta::FromSeconds(5)); WaitUntilDialogClosed(web_contents); dialog_contents = OpenMRDialog(web_contents); @@ -81,7 +81,7 @@ dialog_contents, sink_name_script); ASSERT_EQ(kTestSinkName, sink_name); -#if defined(OS_MACOSX) || defined(OS_WIN) +#if defined(OS_MACOSX) // Simulate moving the mouse off the dialog. Confirm that the dialog closes // automatically after the route is closed. // In tests, it sometimes takes too long to CloseRouteOnUI() to finish so @@ -94,7 +94,7 @@ ASSERT_TRUE(content::ExecuteScript(dialog_contents, mouse_leave_script)); #endif CloseRouteOnUI(); -#if defined(OS_MACOSX) || defined(OS_WIN) +#if defined(OS_MACOSX) WaitUntilDialogClosed(web_contents); #endif }
diff --git a/chromecast/browser/media/cma_media_pipeline_client.cc b/chromecast/browser/media/cma_media_pipeline_client.cc index a62e1ec..e91f513 100644 --- a/chromecast/browser/media/cma_media_pipeline_client.cc +++ b/chromecast/browser/media/cma_media_pipeline_client.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "chromecast/browser/media/cma_media_pipeline_client.h" +#include "chromecast/media/cma/backend/media_pipeline_backend_manager.h" #include "chromecast/public/cast_media_shlib.h" namespace chromecast { @@ -17,7 +18,8 @@ scoped_ptr<MediaPipelineBackend> CmaMediaPipelineClient::CreateMediaPipelineBackend( const MediaPipelineDeviceParams& params) { - return make_scoped_ptr(CastMediaShlib::CreateMediaPipelineBackend(params)); + return make_scoped_ptr( + MediaPipelineBackendManager::CreateMediaPipelineBackend(params)); } void CmaMediaPipelineClient::OnMediaPipelineBackendCreated() {
diff --git a/chromecast/media/audio/BUILD.gn b/chromecast/media/audio/BUILD.gn index 4aeeb38..149a664 100644 --- a/chromecast/media/audio/BUILD.gn +++ b/chromecast/media/audio/BUILD.gn
@@ -16,6 +16,7 @@ "//base", "//chromecast/base", "//chromecast/media/base", + "//chromecast/media/cma/backend", "//chromecast/media/cma/base", "//chromecast/public/media", "//media",
diff --git a/chromecast/media/audio/cast_audio_manager.cc b/chromecast/media/audio/cast_audio_manager.cc index eaed754..54cd794 100644 --- a/chromecast/media/audio/cast_audio_manager.cc +++ b/chromecast/media/audio/cast_audio_manager.cc
@@ -4,8 +4,12 @@ #include "chromecast/media/audio/cast_audio_manager.h" +#include <algorithm> +#include <string> + #include "chromecast/media/audio/cast_audio_output_stream.h" #include "chromecast/media/base/media_message_loop.h" +#include "chromecast/media/cma/backend/media_pipeline_backend_manager.h" #include "chromecast/public/cast_media_shlib.h" #include "chromecast/public/media/media_pipeline_backend.h" @@ -63,7 +67,7 @@ DCHECK(media::MediaMessageLoop::GetTaskRunner()->BelongsToCurrentThread()); return scoped_ptr<MediaPipelineBackend>( - CastMediaShlib::CreateMediaPipelineBackend(params)); + MediaPipelineBackendManager::CreateMediaPipelineBackend(params)); } ::media::AudioOutputStream* CastAudioManager::MakeLinearOutputStream(
diff --git a/chromecast/media/cma/backend/BUILD.gn b/chromecast/media/cma/backend/BUILD.gn index fc72d02..618481a 100644 --- a/chromecast/media/cma/backend/BUILD.gn +++ b/chromecast/media/cma/backend/BUILD.gn
@@ -6,8 +6,14 @@ sources = [ "audio_decoder_default.cc", "audio_decoder_default.h", + "audio_decoder_wrapper.cc", + "audio_decoder_wrapper.h", "media_pipeline_backend_default.cc", "media_pipeline_backend_default.h", + "media_pipeline_backend_manager.cc", + "media_pipeline_backend_manager.h", + "media_pipeline_backend_wrapper.cc", + "media_pipeline_backend_wrapper.h", "video_decoder_default.cc", "video_decoder_default.h", ] @@ -19,5 +25,6 @@ deps = [ "//base", + "//chromecast/media/base:message_loop", ] }
diff --git a/chromecast/media/cma/backend/audio_decoder_wrapper.cc b/chromecast/media/cma/backend/audio_decoder_wrapper.cc new file mode 100644 index 0000000..eff40d3e --- /dev/null +++ b/chromecast/media/cma/backend/audio_decoder_wrapper.cc
@@ -0,0 +1,55 @@ +// 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 "chromecast/media/cma/backend/audio_decoder_wrapper.h" + +#include "base/logging.h" + +namespace chromecast { +namespace media { + +AudioDecoderWrapper::AudioDecoderWrapper( + MediaPipelineBackend::AudioDecoder* audio_decoder) + : audio_decoder_(audio_decoder), + stream_type_volume_(1.0), + stream_volume_(1.0) { + DCHECK(audio_decoder_); +} + +AudioDecoderWrapper::~AudioDecoderWrapper() { +} + +void AudioDecoderWrapper::SetDelegate(Delegate* delegate) { + audio_decoder_->SetDelegate(delegate); +} + +MediaPipelineBackend::BufferStatus AudioDecoderWrapper::PushBuffer( + CastDecoderBuffer* buffer) { + return audio_decoder_->PushBuffer(buffer); +} + +void AudioDecoderWrapper::GetStatistics(Statistics* statistics) { + audio_decoder_->GetStatistics(statistics); +} + +bool AudioDecoderWrapper::SetConfig(const AudioConfig& config) { + return audio_decoder_->SetConfig(config); +} + +bool AudioDecoderWrapper::SetVolume(float multiplier) { + stream_volume_ = multiplier; + return audio_decoder_->SetVolume(stream_volume_ * stream_type_volume_); +} + +AudioDecoderWrapper::RenderingDelay AudioDecoderWrapper::GetRenderingDelay() { + return audio_decoder_->GetRenderingDelay(); +} + +bool AudioDecoderWrapper::SetStreamTypeVolume(float stream_type_volume) { + stream_type_volume_ = stream_type_volume; + return audio_decoder_->SetVolume(stream_volume_ * stream_type_volume_); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/cma/backend/audio_decoder_wrapper.h b/chromecast/media/cma/backend/audio_decoder_wrapper.h new file mode 100644 index 0000000..3a4ccf4 --- /dev/null +++ b/chromecast/media/cma/backend/audio_decoder_wrapper.h
@@ -0,0 +1,42 @@ +// 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 CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_DECODER_WRAPPER_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_DECODER_WRAPPER_H_ + +#include "base/macros.h" +#include "chromecast/public/media/media_pipeline_backend.h" + +namespace chromecast { +namespace media { + +class AudioDecoderWrapper : public MediaPipelineBackend::AudioDecoder { + public: + explicit AudioDecoderWrapper( + MediaPipelineBackend::AudioDecoder* audio_decoder); + ~AudioDecoderWrapper() override; + + // MediaPipelineBackend::AudioDecoder implementation: + void SetDelegate(Delegate* delegate) override; + MediaPipelineBackend::BufferStatus PushBuffer( + CastDecoderBuffer* buffer) override; + void GetStatistics(Statistics* statistics) override; + bool SetConfig(const AudioConfig& config) override; + bool SetVolume(float multiplier) override; + RenderingDelay GetRenderingDelay() override; + + bool SetStreamTypeVolume(float stream_type_volume); + + private: + MediaPipelineBackend::AudioDecoder* const audio_decoder_; + float stream_type_volume_; + float stream_volume_; + + DISALLOW_COPY_AND_ASSIGN(AudioDecoderWrapper); +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_AUDIO_DECODER_WRAPPER_H_
diff --git a/chromecast/media/cma/backend/media_pipeline_backend_manager.cc b/chromecast/media/cma/backend/media_pipeline_backend_manager.cc new file mode 100644 index 0000000..d0db5adf --- /dev/null +++ b/chromecast/media/cma/backend/media_pipeline_backend_manager.cc
@@ -0,0 +1,98 @@ +// 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 "chromecast/media/cma/backend/media_pipeline_backend_manager.h" + +#include <algorithm> + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "base/location.h" +#include "chromecast/media/base/media_message_loop.h" +#include "chromecast/media/cma/backend/media_pipeline_backend_wrapper.h" +#include "chromecast/public/cast_media_shlib.h" + +namespace chromecast { +namespace media { + +namespace { + +base::LazyInstance<MediaPipelineBackendManager> g_instance = + LAZY_INSTANCE_INITIALIZER; + +} // namespace + +// static +MediaPipelineBackend* MediaPipelineBackendManager::CreateMediaPipelineBackend( + const media::MediaPipelineDeviceParams& params) { + DCHECK(MediaMessageLoop::GetTaskRunner()->BelongsToCurrentThread()); + return CreateMediaPipelineBackend(params, 0); +} + +// static +MediaPipelineBackend* MediaPipelineBackendManager::CreateMediaPipelineBackend( + const media::MediaPipelineDeviceParams& params, + int stream_type) { + DCHECK(MediaMessageLoop::GetTaskRunner()->BelongsToCurrentThread()); + MediaPipelineBackendManager* backend_manager = Get(); + MediaPipelineBackendWrapper* backend_ptr = new MediaPipelineBackendWrapper( + media::CastMediaShlib::CreateMediaPipelineBackend(params), stream_type, + backend_manager->GetVolumeMultiplier(stream_type)); + backend_manager->media_pipeline_backends_.push_back(backend_ptr); + return backend_ptr; +} + +// static +void MediaPipelineBackendManager::OnMediaPipelineBackendDestroyed( + const MediaPipelineBackend* backend) { + DCHECK(MediaMessageLoop::GetTaskRunner()->BelongsToCurrentThread()); + MediaPipelineBackendManager* backend_manager = Get(); + backend_manager->media_pipeline_backends_.erase( + std::remove(backend_manager->media_pipeline_backends_.begin(), + backend_manager->media_pipeline_backends_.end(), backend), + backend_manager->media_pipeline_backends_.end()); +} + +// static +void MediaPipelineBackendManager::SetVolumeMultiplier(int stream_type, + float volume) { + DCHECK(MediaMessageLoop::GetTaskRunner()->BelongsToCurrentThread()); + MediaPipelineBackendManager* backend_manager = Get(); + volume = std::max(0.0f, std::min(volume, 1.0f)); + backend_manager->volume_by_stream_type_[stream_type] = volume; + + // Set volume for each open media pipeline backends. + for (auto it = backend_manager->media_pipeline_backends_.begin(); + it != backend_manager->media_pipeline_backends_.end(); it++) { + MediaPipelineBackendWrapper* wrapper = + static_cast<MediaPipelineBackendWrapper*>(*it); + if (wrapper->GetStreamType() == stream_type) + wrapper->SetStreamTypeVolume(volume); + } +} + +// static +MediaPipelineBackendManager* MediaPipelineBackendManager::Get() { + return g_instance.Pointer(); +} + +MediaPipelineBackendManager::MediaPipelineBackendManager() { +} + +MediaPipelineBackendManager::~MediaPipelineBackendManager() { +} + +float MediaPipelineBackendManager::GetVolumeMultiplier(int stream_type) { + DCHECK(MediaMessageLoop::GetTaskRunner()->BelongsToCurrentThread()); + MediaPipelineBackendManager* backend_manager = Get(); + auto it = backend_manager->volume_by_stream_type_.find(stream_type); + if (it == backend_manager->volume_by_stream_type_.end()) { + return 1.0; + } else { + return it->second; + } +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/cma/backend/media_pipeline_backend_manager.h b/chromecast/media/cma/backend/media_pipeline_backend_manager.h new file mode 100644 index 0000000..890dfc86 --- /dev/null +++ b/chromecast/media/cma/backend/media_pipeline_backend_manager.h
@@ -0,0 +1,72 @@ +// 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 CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_MANAGER_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_MANAGER_H_ + +#include <map> +#include <vector> + +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "chromecast/public/media/media_pipeline_backend.h" +#include "chromecast/public/media/media_pipeline_device_params.h" + +namespace base { +template <typename T> +struct DefaultLazyInstanceTraits; +} // namespace base + +namespace chromecast { +namespace media { + +// This class manages created media pipelines, and provides volume control by +// stream type. +// All functions in this class should be called on the media thread. +class MediaPipelineBackendManager { + public: + // Create media pipeline backend. + static MediaPipelineBackend* CreateMediaPipelineBackend( + const MediaPipelineDeviceParams& params); + + // Create media pipeline backend with a specific stream_type. + static MediaPipelineBackend* CreateMediaPipelineBackend( + const MediaPipelineDeviceParams& params, + int stream_type); + + // Internal clean up when a new media pipeline backend is destroyed. + static void OnMediaPipelineBackendDestroyed( + const MediaPipelineBackend* backend); + + // Sets the relative volume for a specified stream type, + // with range [0.0, 1.0] inclusive. If |multiplier| is outside the + // range [0.0, 1.0], it is clamped to that range. + // TODO(tianyuwang): change stream_type to use a enum. + static void SetVolumeMultiplier(int stream_type, float volume); + + private: + friend struct base::DefaultLazyInstanceTraits<MediaPipelineBackendManager>; + + // Returns a pointer to a singleton instance of the + // MediaPipelineBackendManager. + static MediaPipelineBackendManager* Get(); + + MediaPipelineBackendManager(); + ~MediaPipelineBackendManager(); + + float GetVolumeMultiplier(int stream_type); + + // A vector that stores all of the existing media_pipeline_backends_. + std::vector<MediaPipelineBackend*> media_pipeline_backends_; + + // Volume multiplier for each type of audio streams. + std::map<int, float> volume_by_stream_type_; + + DISALLOW_COPY_AND_ASSIGN(MediaPipelineBackendManager); +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_MANAGER_H_
diff --git a/chromecast/media/cma/backend/media_pipeline_backend_wrapper.cc b/chromecast/media/cma/backend/media_pipeline_backend_wrapper.cc new file mode 100644 index 0000000..447981f5 --- /dev/null +++ b/chromecast/media/cma/backend/media_pipeline_backend_wrapper.cc
@@ -0,0 +1,88 @@ +// 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 "chromecast/media/cma/backend/media_pipeline_backend_wrapper.h" + +#include "base/logging.h" +#include "chromecast/media/cma/backend/media_pipeline_backend_manager.h" + +namespace chromecast { +namespace media { + +MediaPipelineBackendWrapper::MediaPipelineBackendWrapper( + MediaPipelineBackend* backend, + int stream_type, + float stream_type_volume) + : backend_(backend), + stream_type_(stream_type), + audio_decoder_wrapper_(nullptr), + stream_type_volume_(stream_type_volume), + is_initialized_(false) { + DCHECK(backend_); +} + +MediaPipelineBackendWrapper::~MediaPipelineBackendWrapper() { + MediaPipelineBackendManager::OnMediaPipelineBackendDestroyed(this); +} + +MediaPipelineBackend::AudioDecoder* +MediaPipelineBackendWrapper::CreateAudioDecoder() { + if (audio_decoder_wrapper_) + return nullptr; + + audio_decoder_wrapper_.reset( + new AudioDecoderWrapper(backend_->CreateAudioDecoder())); + return audio_decoder_wrapper_.get(); +} + +MediaPipelineBackend::VideoDecoder* +MediaPipelineBackendWrapper::CreateVideoDecoder() { + return backend_->CreateVideoDecoder(); +} + +bool MediaPipelineBackendWrapper::Initialize() { + is_initialized_ = backend_->Initialize(); + if (is_initialized_) + audio_decoder_wrapper_->SetStreamTypeVolume(stream_type_volume_); + + return is_initialized_; +} + +bool MediaPipelineBackendWrapper::Start(int64_t start_pts) { + return backend_->Start(start_pts); +} + +bool MediaPipelineBackendWrapper::Stop() { + return backend_->Stop(); +} + +bool MediaPipelineBackendWrapper::Pause() { + return backend_->Pause(); +} + +bool MediaPipelineBackendWrapper::Resume() { + return backend_->Resume(); +} + +int64_t MediaPipelineBackendWrapper::GetCurrentPts() { + return backend_->GetCurrentPts(); +} + +bool MediaPipelineBackendWrapper::SetPlaybackRate(float rate) { + return backend_->SetPlaybackRate(rate); +} + +int MediaPipelineBackendWrapper::GetStreamType() const { + return stream_type_; +} + +void MediaPipelineBackendWrapper::SetStreamTypeVolume( + float stream_type_volume) { + stream_type_volume_ = stream_type_volume; + if (is_initialized_ && audio_decoder_wrapper_) + audio_decoder_wrapper_->SetStreamTypeVolume(stream_type_volume_); +} + +} // namespace media +} // namespace chromecast
diff --git a/chromecast/media/cma/backend/media_pipeline_backend_wrapper.h b/chromecast/media/cma/backend/media_pipeline_backend_wrapper.h new file mode 100644 index 0000000..f2befb8a --- /dev/null +++ b/chromecast/media/cma/backend/media_pipeline_backend_wrapper.h
@@ -0,0 +1,59 @@ +// 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 CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_WRAPPER_H_ +#define CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_WRAPPER_H_ + +#include <stdint.h> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/time/time.h" +#include "chromecast/media/cma/backend/audio_decoder_wrapper.h" +#include "chromecast/public/media/media_pipeline_backend.h" +#include "chromecast/public/media/media_pipeline_device_params.h" + +namespace base { +class SingleThreadTaskRunner; +} // namespace base + +namespace chromecast { +namespace media { + +class MediaPipelineBackendWrapper : public MediaPipelineBackend { + public: + MediaPipelineBackendWrapper(MediaPipelineBackend* backend, + int stream_type, + float stream_type_volume); + ~MediaPipelineBackendWrapper() override; + + // MediaPipelineBackend implementation: + AudioDecoder* CreateAudioDecoder() override; + VideoDecoder* CreateVideoDecoder() override; + bool Initialize() override; + bool Start(int64_t start_pts) override; + bool Stop() override; + bool Pause() override; + bool Resume() override; + int64_t GetCurrentPts() override; + bool SetPlaybackRate(float rate) override; + + int GetStreamType() const; + void SetStreamTypeVolume(float stream_type_volume); + + private: + scoped_ptr<MediaPipelineBackend> backend_; + const int stream_type_; + scoped_ptr<AudioDecoderWrapper> audio_decoder_wrapper_; + float stream_type_volume_; + bool is_initialized_; + + DISALLOW_COPY_AND_ASSIGN(MediaPipelineBackendWrapper); +}; + +} // namespace media +} // namespace chromecast + +#endif // CHROMECAST_MEDIA_CMA_BACKEND_MEDIA_PIPELINE_BACKEND_WRAPPER_H_
diff --git a/chromecast/media/cma/test/frame_segmenter_for_test.cc b/chromecast/media/cma/test/frame_segmenter_for_test.cc index 7d4d06d..b8172eee 100644 --- a/chromecast/media/cma/test/frame_segmenter_for_test.cc +++ b/chromecast/media/cma/test/frame_segmenter_for_test.cc
@@ -15,6 +15,7 @@ #include "media/base/decoder_buffer.h" #include "media/base/demuxer.h" #include "media/base/media_log.h" +#include "media/base/media_tracks.h" #include "media/base/test_helpers.h" #include "media/filters/ffmpeg_demuxer.h" #include "media/filters/file_data_source.h" @@ -269,6 +270,9 @@ LOG(FATAL) << "Unexpected test failure: file is encrypted."; } +void OnMediaTracksUpdated(scoped_ptr<::media::MediaTracks> tracks) { +} + void OnNewBuffer(BufferList* buffer_list, const base::Closure& finished_cb, ::media::DemuxerStream::Status status, @@ -310,7 +314,8 @@ ::media::FFmpegDemuxer demuxer( base::ThreadTaskRunnerHandle::Get(), &data_source, - base::Bind(&OnEncryptedMediaInitData), new ::media::MediaLog()); + base::Bind(&OnEncryptedMediaInitData), base::Bind(&OnMediaTracksUpdated), + new ::media::MediaLog()); ::media::WaitableMessageLoopEvent init_event; demuxer.Initialize(&fake_demuxer_host, init_event.GetPipelineStatusCB(),
diff --git a/chromecast/media/media.gyp b/chromecast/media/media.gyp index 1430fe5..51a772c 100644 --- a/chromecast/media/media.gyp +++ b/chromecast/media/media.gyp
@@ -156,8 +156,14 @@ 'sources': [ 'cma/backend/audio_decoder_default.cc', 'cma/backend/audio_decoder_default.h', + 'cma/backend/audio_decoder_wrapper.cc', + 'cma/backend/audio_decoder_wrapper.h', 'cma/backend/media_pipeline_backend_default.cc', 'cma/backend/media_pipeline_backend_default.h', + 'cma/backend/media_pipeline_backend_manager.cc', + 'cma/backend/media_pipeline_backend_manager.h', + 'cma/backend/media_pipeline_backend_wrapper.cc', + 'cma/backend/media_pipeline_backend_wrapper.h', 'cma/backend/video_decoder_default.cc', 'cma/backend/video_decoder_default.h', ],
diff --git a/chromeos/BUILD.gn b/chromeos/BUILD.gn index 8ab2c15..b7203f0 100644 --- a/chromeos/BUILD.gn +++ b/chromeos/BUILD.gn
@@ -35,6 +35,7 @@ "//components/prefs", "//components/proxy_config", "//components/signin/core/account_id", + "//components/user_manager", "//crypto", "//crypto:platform", "//google_apis", @@ -149,6 +150,7 @@ "//components/onc", "//components/prefs:test_support", "//components/proxy_config", + "//components/signin/core/account_id", "//crypto", "//crypto:test_support", "//dbus:test_support",
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 653a368..e895bb6b 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -8008.0.0 \ No newline at end of file +8025.0.0 \ No newline at end of file
diff --git a/chromeos/DEPS b/chromeos/DEPS index f55569a..26aba316 100644 --- a/chromeos/DEPS +++ b/chromeos/DEPS
@@ -4,6 +4,8 @@ include_rules = [ "+components/device_event_log", "+components/prefs", + "+components/signin/core/account_id/account_id.h", + "+components/user_manager/known_user.h", "+crypto", "+net", "+policy/proto",
diff --git a/chromeos/attestation/attestation_flow.cc b/chromeos/attestation/attestation_flow.cc index ec2b12e..ea4c771b 100644 --- a/chromeos/attestation/attestation_flow.cc +++ b/chromeos/attestation/attestation_flow.cc
@@ -8,7 +8,9 @@ #include "base/bind.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" +#include "components/signin/core/account_id/account_id.h" namespace chromeos { namespace attestation { @@ -97,20 +99,15 @@ void AttestationFlow::GetCertificate( AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool force_new_key, const CertificateCallback& callback) { // If this device has not enrolled with the Privacy CA, we need to do that // first. Once enrolled we can proceed with the certificate request. base::Closure do_cert_request = base::Bind( - &AttestationFlow::StartCertificateRequest, - weak_factory_.GetWeakPtr(), - certificate_profile, - user_id, - request_origin, - force_new_key, - callback); + &AttestationFlow::StartCertificateRequest, weak_factory_.GetWeakPtr(), + certificate_profile, account_id, request_origin, force_new_key, callback); base::Closure on_enroll_failure = base::Bind(callback, false, ""); base::Closure do_enroll = base::Bind(&AttestationFlow::StartEnroll, weak_factory_.GetWeakPtr(), @@ -194,7 +191,7 @@ void AttestationFlow::StartCertificateRequest( AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool generate_new_key, const CertificateCallback& callback) { @@ -204,49 +201,31 @@ if (generate_new_key) { // Get the attestation service to create a Privacy CA certificate request. async_caller_->AsyncTpmAttestationCreateCertRequest( - server_proxy_->GetType(), - certificate_profile, - user_id, - request_origin, + server_proxy_->GetType(), certificate_profile, + cryptohome::Identification(account_id), request_origin, base::Bind(&AttestationFlow::SendCertificateRequestToPCA, - weak_factory_.GetWeakPtr(), - key_type, - user_id, - key_name, + weak_factory_.GetWeakPtr(), key_type, account_id, key_name, callback)); } else { // If the key already exists, query the existing certificate. base::Closure on_key_exists = base::Bind( - &AttestationFlow::GetExistingCertificate, - weak_factory_.GetWeakPtr(), - key_type, - user_id, - key_name, - callback); + &AttestationFlow::GetExistingCertificate, weak_factory_.GetWeakPtr(), + key_type, account_id, key_name, callback); // If the key does not exist, call this method back with |generate_new_key| // set to true. base::Closure on_key_not_exists = base::Bind( - &AttestationFlow::StartCertificateRequest, - weak_factory_.GetWeakPtr(), - certificate_profile, - user_id, - request_origin, - true, - callback); + &AttestationFlow::StartCertificateRequest, weak_factory_.GetWeakPtr(), + certificate_profile, account_id, request_origin, true, callback); cryptohome_client_->TpmAttestationDoesKeyExist( - key_type, - user_id, - key_name, - base::Bind(&DBusBoolRedirectCallback, - on_key_exists, - on_key_not_exists, - base::Bind(callback, false, ""))); + key_type, cryptohome::Identification(account_id), key_name, + base::Bind(&DBusBoolRedirectCallback, on_key_exists, on_key_not_exists, + base::Bind(callback, false, ""))); } } void AttestationFlow::SendCertificateRequestToPCA( AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, const CertificateCallback& callback, bool success, @@ -260,18 +239,14 @@ // Send the request to the Privacy CA. server_proxy_->SendCertificateRequest( - data, - base::Bind(&AttestationFlow::SendCertificateResponseToDaemon, - weak_factory_.GetWeakPtr(), - key_type, - user_id, - key_name, - callback)); + data, base::Bind(&AttestationFlow::SendCertificateResponseToDaemon, + weak_factory_.GetWeakPtr(), key_type, account_id, + key_name, callback)); } void AttestationFlow::SendCertificateResponseToDaemon( AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, const CertificateCallback& callback, bool success, @@ -284,22 +259,18 @@ } // Forward the response to the attestation service to complete the operation. - async_caller_->AsyncTpmAttestationFinishCertRequest(data, - key_type, - user_id, - key_name, - base::Bind(callback)); + async_caller_->AsyncTpmAttestationFinishCertRequest( + data, key_type, cryptohome::Identification(account_id), key_name, + base::Bind(callback)); } void AttestationFlow::GetExistingCertificate( AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, const CertificateCallback& callback) { cryptohome_client_->TpmAttestationGetCertificate( - key_type, - user_id, - key_name, + key_type, cryptohome::Identification(account_id), key_name, base::Bind(&DBusDataMethodCallback, callback)); }
diff --git a/chromeos/attestation/attestation_flow.h b/chromeos/attestation/attestation_flow.h index 7dd575b9..373f6dd 100644 --- a/chromeos/attestation/attestation_flow.h +++ b/chromeos/attestation/attestation_flow.h
@@ -16,6 +16,8 @@ #include "chromeos/dbus/dbus_method_call_status.h" #include "third_party/cros_system_api/dbus/service_constants.h" +class AccountId; + namespace cryptohome { class AsyncMethodCaller; @@ -69,9 +71,8 @@ // Parameters // certificate_profile - Specifies what kind of certificate should be // requested from the CA. - // user_id - Identifies the currently active user. For normal GAIA users - // this is a canonical email address. This is ignored when using - // the enterprise machine cert profile. + // account_id - Identifies the currently active user. This is ignored when + // using the enterprise machine cert profile. // request_origin - For content protection profiles, certificate requests // are origin-specific. This string must uniquely identify // the origin of the request. @@ -82,7 +83,7 @@ // On success |result| will be true and |data| will contain the // PCA-issued certificate chain in PEM format. virtual void GetCertificate(AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool force_new_key, const CertificateCallback& callback); @@ -143,13 +144,13 @@ // Parameters // certificate_profile - Specifies what kind of certificate should be // requested from the CA. - // user_id - Identifies the active user. + // account_id - Identifies the active user. // request_origin - An identifier for the origin of this request. // generate_new_key - If set to true a new key is generated. // callback - Called when the operation completes. void StartCertificateRequest( const AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const AccountId& account_id, const std::string& request_origin, bool generate_new_key, const CertificateCallback& callback); @@ -160,13 +161,13 @@ // // Parameters // key_type - The type of the key for which a certificate is requested. - // user_id - Identifies the active user. + // account_id - Identifies the active user. // key_name - The name of the key for which a certificate is requested. // callback - Called when the operation completes. // success - The status of request creation. // data - The request data for the Privacy CA. void SendCertificateRequestToPCA(AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, const CertificateCallback& callback, bool success, @@ -178,13 +179,13 @@ // // Parameters // key_type - The type of the key for which a certificate is requested. - // user_id - Identifies the active user. + // account_id - Identifies the active user. // key_name - The name of the key for which a certificate is requested. // callback - Called when the operation completes. // success - The status of the Privacy CA operation. // data - The response data from the Privacy CA. void SendCertificateResponseToDaemon(AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, const CertificateCallback& callback, bool success, @@ -194,11 +195,11 @@ // // Parameters // key_type - The type of the key for which a certificate is requested. - // user_id - Identifies the active user. + // account_id - Identifies the active user. // key_name - The name of the key for which a certificate is requested. // callback - Called when the operation completes. void GetExistingCertificate(AttestationKeyType key_type, - const std::string& user_id, + const AccountId& account_id, const std::string& key_name, const CertificateCallback& callback);
diff --git a/chromeos/attestation/attestation_flow_unittest.cc b/chromeos/attestation/attestation_flow_unittest.cc index 99b98bd..2e12184 100644 --- a/chromeos/attestation/attestation_flow_unittest.cc +++ b/chromeos/attestation/attestation_flow_unittest.cc
@@ -8,8 +8,10 @@ #include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "chromeos/attestation/mock_attestation_flow.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/dbus/mock_cryptohome_client.h" +#include "components/signin/core/account_id/account_id.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -105,13 +107,13 @@ .Times(1) .InSequence(flow_order); - EXPECT_CALL( - async_caller, - AsyncTpmAttestationCreateCertRequest(_, - PROFILE_ENTERPRISE_USER_CERTIFICATE, - "fake@test.com", "fake_origin", _)) - .Times(1) - .InSequence(flow_order); + const AccountId account_id = AccountId::FromUserEmail("fake@test.com"); + EXPECT_CALL(async_caller, + AsyncTpmAttestationCreateCertRequest( + _, PROFILE_ENTERPRISE_USER_CERTIFICATE, + cryptohome::Identification(account_id), "fake_origin", _)) + .Times(1) + .InSequence(flow_order); EXPECT_CALL(*proxy, SendCertificateRequest( cryptohome::MockAsyncMethodCaller::kFakeAttestationCertRequest, @@ -121,12 +123,10 @@ std::string fake_cert_response = cryptohome::MockAsyncMethodCaller::kFakeAttestationCertRequest; fake_cert_response += "_response"; - EXPECT_CALL(async_caller, - AsyncTpmAttestationFinishCertRequest(fake_cert_response, - KEY_USER, - "fake@test.com", - kEnterpriseUserKey, - _)) + EXPECT_CALL(async_caller, AsyncTpmAttestationFinishCertRequest( + fake_cert_response, KEY_USER, + cryptohome::Identification(account_id), + kEnterpriseUserKey, _)) .Times(1) .InSequence(flow_order); @@ -142,7 +142,7 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "fake@test.com", + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, account_id, "fake_origin", true, mock_callback); Run(); } @@ -170,8 +170,8 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); } @@ -201,8 +201,8 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); } @@ -237,27 +237,25 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); } TEST_F(AttestationFlowTest, GetMachineCertificateAlreadyEnrolled) { StrictMock<cryptohome::MockAsyncMethodCaller> async_caller; async_caller.SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(async_caller, - AsyncTpmAttestationCreateCertRequest( - _, PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, "", "", _)) + EXPECT_CALL(async_caller, AsyncTpmAttestationCreateCertRequest( + _, PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, + cryptohome::Identification(), "", _)) .Times(1); std::string fake_cert_response = cryptohome::MockAsyncMethodCaller::kFakeAttestationCertRequest; fake_cert_response += "_response"; EXPECT_CALL(async_caller, - AsyncTpmAttestationFinishCertRequest(fake_cert_response, - KEY_DEVICE, - "", - kEnterpriseMachineKey, - _)) + AsyncTpmAttestationFinishCertRequest( + fake_cert_response, KEY_DEVICE, cryptohome::Identification(), + kEnterpriseMachineKey, _)) .Times(1); chromeos::MockCryptohomeClient client; @@ -281,17 +279,17 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, EmptyAccountId(), + "", true, mock_callback); Run(); } TEST_F(AttestationFlowTest, GetCertificate_FailCreateCertRequest) { StrictMock<cryptohome::MockAsyncMethodCaller> async_caller; async_caller.SetUp(false, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(async_caller, - AsyncTpmAttestationCreateCertRequest( - _, PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", _)) + EXPECT_CALL(async_caller, AsyncTpmAttestationCreateCertRequest( + _, PROFILE_ENTERPRISE_USER_CERTIFICATE, + cryptohome::Identification(), "", _)) .Times(1); chromeos::MockCryptohomeClient client; @@ -310,17 +308,17 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); } TEST_F(AttestationFlowTest, GetCertificate_CertRequestRejected) { StrictMock<cryptohome::MockAsyncMethodCaller> async_caller; async_caller.SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(async_caller, - AsyncTpmAttestationCreateCertRequest( - _, PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", _)) + EXPECT_CALL(async_caller, AsyncTpmAttestationCreateCertRequest( + _, PROFILE_ENTERPRISE_USER_CERTIFICATE, + cryptohome::Identification(), "", _)) .Times(1); chromeos::MockCryptohomeClient client; @@ -342,8 +340,8 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); } @@ -367,34 +365,33 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); } TEST_F(AttestationFlowTest, GetCertificate_CheckExisting) { StrictMock<cryptohome::MockAsyncMethodCaller> async_caller; async_caller.SetUp(true, cryptohome::MOUNT_ERROR_NONE); - EXPECT_CALL(async_caller, - AsyncTpmAttestationCreateCertRequest( - _, PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", _)) + EXPECT_CALL(async_caller, AsyncTpmAttestationCreateCertRequest( + _, PROFILE_ENTERPRISE_USER_CERTIFICATE, + cryptohome::Identification(), "", _)) .Times(1); std::string fake_cert_response = cryptohome::MockAsyncMethodCaller::kFakeAttestationCertRequest; fake_cert_response += "_response"; EXPECT_CALL(async_caller, - AsyncTpmAttestationFinishCertRequest(fake_cert_response, - KEY_USER, - "", - kEnterpriseUserKey, - _)) + AsyncTpmAttestationFinishCertRequest(fake_cert_response, KEY_USER, + cryptohome::Identification(), + kEnterpriseUserKey, _)) .Times(1); chromeos::MockCryptohomeClient client; EXPECT_CALL(client, TpmAttestationIsEnrolled(_)) .WillRepeatedly(Invoke(DBusCallbackTrue)); EXPECT_CALL(client, - TpmAttestationDoesKeyExist(KEY_USER, "", kEnterpriseUserKey, _)) + TpmAttestationDoesKeyExist(KEY_USER, cryptohome::Identification(), + kEnterpriseUserKey, _)) .WillRepeatedly(WithArgs<3>(Invoke(DBusCallbackFalse))); scoped_ptr<MockServerProxy> proxy(new StrictMock<MockServerProxy>()); @@ -414,8 +411,8 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", false, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + false, mock_callback); Run(); } @@ -427,10 +424,12 @@ EXPECT_CALL(client, TpmAttestationIsEnrolled(_)) .WillRepeatedly(Invoke(DBusCallbackTrue)); EXPECT_CALL(client, - TpmAttestationDoesKeyExist(KEY_USER, "", kEnterpriseUserKey, _)) + TpmAttestationDoesKeyExist(KEY_USER, cryptohome::Identification(), + kEnterpriseUserKey, _)) .WillRepeatedly(WithArgs<3>(Invoke(DBusCallbackTrue))); - EXPECT_CALL(client, - TpmAttestationGetCertificate(KEY_USER, "", kEnterpriseUserKey, _)) + EXPECT_CALL(client, TpmAttestationGetCertificate(KEY_USER, + cryptohome::Identification(), + kEnterpriseUserKey, _)) .WillRepeatedly(WithArgs<3>(Invoke(FakeDBusData("fake_cert")))); // We're not expecting any server calls in this case; StrictMock will verify. @@ -445,8 +444,8 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", false, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + false, mock_callback); Run(); } @@ -480,8 +479,8 @@ scoped_ptr<ServerProxy> proxy_interface(proxy.release()); AttestationFlow flow(&async_caller, &client, std::move(proxy_interface)); - flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, "", "", true, - mock_callback); + flow.GetCertificate(PROFILE_ENTERPRISE_USER_CERTIFICATE, EmptyAccountId(), "", + true, mock_callback); Run(); }
diff --git a/chromeos/attestation/mock_attestation_flow.cc b/chromeos/attestation/mock_attestation_flow.cc index 4b109755..72be828 100644 --- a/chromeos/attestation/mock_attestation_flow.cc +++ b/chromeos/attestation/mock_attestation_flow.cc
@@ -5,6 +5,7 @@ #include "chromeos/attestation/mock_attestation_flow.h" #include "base/memory/scoped_ptr.h" +#include "components/signin/core/account_id/account_id.h" using testing::_; using testing::DefaultValue;
diff --git a/chromeos/attestation/mock_attestation_flow.h b/chromeos/attestation/mock_attestation_flow.h index fad04f0d..d64548e 100644 --- a/chromeos/attestation/mock_attestation_flow.h +++ b/chromeos/attestation/mock_attestation_flow.h
@@ -11,6 +11,8 @@ #include "base/macros.h" #include "testing/gmock/include/gmock/gmock.h" +class AccountId; + namespace chromeos { namespace attestation { @@ -66,11 +68,12 @@ MockAttestationFlow(); virtual ~MockAttestationFlow(); - MOCK_METHOD5(GetCertificate, void(AttestationCertificateProfile, - const std::string&, - const std::string&, - bool, - const CertificateCallback&)); + MOCK_METHOD5(GetCertificate, + void(AttestationCertificateProfile, + const AccountId& account_id, + const std::string&, + bool, + const CertificateCallback&)); }; } // namespace attestation
diff --git a/chromeos/chromeos.gyp b/chromeos/chromeos.gyp index c0f9ab53..9b76232 100644 --- a/chromeos/chromeos.gyp +++ b/chromeos/chromeos.gyp
@@ -518,6 +518,7 @@ '../components/components.gyp:device_event_log_component', '../components/components.gyp:onc_component', '../components/components.gyp:proxy_config', + '../components/components.gyp:user_manager', '../components/components.gyp:signin_core_account_id', '../components/prefs/prefs.gyp:prefs', '../crypto/crypto.gyp:crypto', @@ -650,6 +651,7 @@ '../build/linux/system.gyp:ssl', '../components/components.gyp:onc_component', '../components/components.gyp:proxy_config', + '../components/components.gyp:signin_core_account_id', '../components/prefs/prefs.gyp:prefs_test_support', '../crypto/crypto.gyp:crypto', '../crypto/crypto.gyp:crypto_test_support',
diff --git a/chromeos/cryptohome/async_method_caller.cc b/chromeos/cryptohome/async_method_caller.cc index b95966f..0e033f8 100644 --- a/chromeos/cryptohome/async_method_caller.cc +++ b/chromeos/cryptohome/async_method_caller.cc
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/dbus_thread_manager.h" using chromeos::DBusThreadManager; @@ -36,51 +37,47 @@ ResetAsyncCallStatusHandlers(); } - void AsyncCheckKey(const std::string& user_email, + void AsyncCheckKey(const Identification& cryptohome_id, const std::string& passhash, Callback callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncCheckKey(user_email, passhash, base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate async check of user's key.")); + DBusThreadManager::Get()->GetCryptohomeClient()->AsyncCheckKey( + cryptohome_id, passhash, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate async check of user's key.")); } - void AsyncMigrateKey(const std::string& user_email, + void AsyncMigrateKey(const Identification& cryptohome_id, const std::string& old_hash, const std::string& new_hash, Callback callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncMigrateKey(user_email, old_hash, new_hash, base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate aync migration of user's key")); + DBusThreadManager::Get()->GetCryptohomeClient()->AsyncMigrateKey( + cryptohome_id, old_hash, new_hash, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate aync migration of user's key")); } - void AsyncMount(const std::string& user_email, + void AsyncMount(const Identification& cryptohome_id, const std::string& passhash, int flags, Callback callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncMount(user_email, passhash, flags, base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate async mount of cryptohome.")); + DBusThreadManager::Get()->GetCryptohomeClient()->AsyncMount( + cryptohome_id, passhash, flags, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate async mount of cryptohome.")); } - void AsyncAddKey(const std::string& user_email, + void AsyncAddKey(const Identification& cryptohome_id, const std::string& passhash, const std::string& new_passhash, Callback callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncAddKey(user_email, passhash, new_passhash, base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate async key addition.")); + DBusThreadManager::Get()->GetCryptohomeClient()->AsyncAddKey( + cryptohome_id, passhash, new_passhash, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate async key addition.")); } void AsyncMountGuest(Callback callback) override { @@ -92,24 +89,23 @@ "Couldn't initiate async mount of cryptohome.")); } - void AsyncMountPublic(const std::string& public_mount_id, + void AsyncMountPublic(const Identification& public_mount_id, int flags, Callback callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncMountPublic(public_mount_id, flags, base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate async mount public of cryptohome.")); + DBusThreadManager::Get()->GetCryptohomeClient()->AsyncMountPublic( + public_mount_id, flags, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate async mount public of cryptohome.")); } - void AsyncRemove(const std::string& user_email, Callback callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncRemove(user_email, base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate async removal of cryptohome.")); + void AsyncRemove(const Identification& cryptohome_id, + Callback callback) override { + DBusThreadManager::Get()->GetCryptohomeClient()->AsyncRemove( + cryptohome_id, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate async removal of cryptohome.")); } void AsyncTpmAttestationCreateEnrollRequest( @@ -137,109 +133,88 @@ void AsyncTpmAttestationCreateCertRequest( chromeos::attestation::PrivacyCAType pca_type, chromeos::attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const Identification& cryptohome_id, const std::string& request_origin, const DataCallback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncTpmAttestationCreateCertRequest( - pca_type, - certificate_profile, - user_id, - request_origin, + DBusThreadManager::Get() + ->GetCryptohomeClient() + ->AsyncTpmAttestationCreateCertRequest( + pca_type, certificate_profile, cryptohome_id, request_origin, base::Bind(&AsyncMethodCallerImpl::RegisterAsyncDataCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, + weak_ptr_factory_.GetWeakPtr(), callback, "Couldn't initiate async attestation cert request.")); } void AsyncTpmAttestationFinishCertRequest( const std::string& pca_response, chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& cryptohome_id, const std::string& key_name, const DataCallback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - AsyncTpmAttestationFinishCertRequest( - pca_response, - key_type, - user_id, - key_name, + DBusThreadManager::Get() + ->GetCryptohomeClient() + ->AsyncTpmAttestationFinishCertRequest( + pca_response, key_type, cryptohome_id, key_name, base::Bind( &AsyncMethodCallerImpl::RegisterAsyncDataCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, + weak_ptr_factory_.GetWeakPtr(), callback, "Couldn't initiate async attestation finish cert request.")); } void TpmAttestationRegisterKey( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& cryptohome_id, const std::string& key_name, const Callback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - TpmAttestationRegisterKey( - key_type, - user_id, - key_name, - base::Bind( - &AsyncMethodCallerImpl::RegisterAsyncCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, - "Couldn't initiate async attestation register key.")); + DBusThreadManager::Get()->GetCryptohomeClient()->TpmAttestationRegisterKey( + key_type, cryptohome_id, key_name, + base::Bind(&AsyncMethodCallerImpl::RegisterAsyncCallback, + weak_ptr_factory_.GetWeakPtr(), callback, + "Couldn't initiate async attestation register key.")); } void TpmAttestationSignEnterpriseChallenge( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& cryptohome_id, const std::string& key_name, const std::string& domain, const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, const DataCallback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - TpmAttestationSignEnterpriseChallenge( - key_type, - user_id, - key_name, - domain, - device_id, - options, + DBusThreadManager::Get() + ->GetCryptohomeClient() + ->TpmAttestationSignEnterpriseChallenge( + key_type, cryptohome_id, key_name, domain, device_id, options, challenge, base::Bind( &AsyncMethodCallerImpl::RegisterAsyncDataCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, + weak_ptr_factory_.GetWeakPtr(), callback, "Couldn't initiate async attestation enterprise challenge.")); } void TpmAttestationSignSimpleChallenge( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& cryptohome_id, const std::string& key_name, const std::string& challenge, const DataCallback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - TpmAttestationSignSimpleChallenge( - key_type, - user_id, - key_name, - challenge, + DBusThreadManager::Get() + ->GetCryptohomeClient() + ->TpmAttestationSignSimpleChallenge( + key_type, cryptohome_id, key_name, challenge, base::Bind( &AsyncMethodCallerImpl::RegisterAsyncDataCallback, - weak_ptr_factory_.GetWeakPtr(), - callback, + weak_ptr_factory_.GetWeakPtr(), callback, "Couldn't initiate async attestation simple challenge.")); } - void AsyncGetSanitizedUsername(const std::string& user, + void AsyncGetSanitizedUsername(const Identification& cryptohome_id, const DataCallback& callback) override { - DBusThreadManager::Get()->GetCryptohomeClient()-> - GetSanitizedUsername(user, - base::Bind( - &AsyncMethodCallerImpl::GetSanitizedUsernameCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + DBusThreadManager::Get()->GetCryptohomeClient()->GetSanitizedUsername( + cryptohome_id, + base::Bind(&AsyncMethodCallerImpl::GetSanitizedUsernameCallback, + weak_ptr_factory_.GetWeakPtr(), callback)); } virtual void GetSanitizedUsernameCallback(
diff --git a/chromeos/cryptohome/async_method_caller.h b/chromeos/cryptohome/async_method_caller.h index 374da452..098c687e 100644 --- a/chromeos/cryptohome/async_method_caller.h +++ b/chromeos/cryptohome/async_method_caller.h
@@ -15,6 +15,8 @@ namespace cryptohome { +class Identification; + // Note: This file is placed in ::cryptohome instead of ::chromeos::cryptohome // since there is already a namespace ::cryptohome which holds the error code // enum (MountError) and referencing ::chromeos::cryptohome and ::cryptohome @@ -40,45 +42,45 @@ virtual ~AsyncMethodCaller() {} // Asks cryptohomed to asynchronously try to find the cryptohome for - // |user_email| and then use |passhash| to unlock the key. + // |user_id| and then use |passhash| to unlock the key. // |callback| will be called with status info on completion. - virtual void AsyncCheckKey(const std::string& user_email, + virtual void AsyncCheckKey(const Identification& user_id, const std::string& passhash, Callback callback) = 0; // Asks cryptohomed to asynchronously try to find the cryptohome for - // |user_email| and then change from using |old_hash| to lock the + // |user_id| and then change from using |old_hash| to lock the // key to using |new_hash|. // |callback| will be called with status info on completion. - virtual void AsyncMigrateKey(const std::string& user_email, + virtual void AsyncMigrateKey(const Identification& user_id, const std::string& old_hash, const std::string& new_hash, Callback callback) = 0; // Asks cryptohomed to asynchronously try to find the cryptohome for - // |user_email| and then mount it using |passhash| to unlock the key. + // |user_id| and then mount it using |passhash| to unlock the key. // The |flags| are a combination of |MountFlags|: // * CREATE_IF_MISSING Controls whether or not cryptohomed is asked to create // a new cryptohome if one does not exist yet for - // |user_email|. + // |user_id|. // * ENSURE_EPHEMERAL If |true|, the mounted cryptohome will be backed by // tmpfs. If |false|, the ephemeral users policy decides // whether tmpfs or an encrypted directory is used as the // backend. // |callback| will be called with status info on completion. // If the |CREATE_IF_MISSING| flag is not given and no cryptohome exists - // for |user_email|, the expected result is + // for |user_id|, the expected result is // callback.Run(false, kCryptohomeMountErrorUserDoesNotExist). Otherwise, // the normal range of return codes is expected. - virtual void AsyncMount(const std::string& user_email, + virtual void AsyncMount(const Identification& user_id, const std::string& passhash, int flags, Callback callback) = 0; // Asks cryptohomed to asynchronously try to add another |new_passhash| for - // |user_email| using |passhash| to unlock the key. + // |user_id| using |passhash| to unlock the key. // |callback| will be called with status info on completion. - virtual void AsyncAddKey(const std::string& user_email, + virtual void AsyncAddKey(const Identification& user_id, const std::string& passhash, const std::string& new_passhash, Callback callback) = 0; @@ -91,13 +93,13 @@ // |public_mount_id| and then mount it using a passhash derived from // |public_mount_id| and a secret. See AsyncMount for possible values for // |flags|. - virtual void AsyncMountPublic(const std::string& public_mount_id, + virtual void AsyncMountPublic(const Identification& public_mount_id, int flags, Callback callback) = 0; // Asks cryptohomed to asynchronously try to find the cryptohome for - // |user_email| and then nuke it. - virtual void AsyncRemove(const std::string& user_email, + // |user_id| and then nuke it. + virtual void AsyncRemove(const Identification& user_id, Callback callback) = 0; // Asks cryptohomed to asynchronously create an attestation enrollment @@ -125,7 +127,7 @@ virtual void AsyncTpmAttestationCreateCertRequest( chromeos::attestation::PrivacyCAType pca_type, chromeos::attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const Identification& user_id, const std::string& request_origin, const DataCallback& callback) = 0; @@ -135,22 +137,22 @@ // emitted by the Privacy CA. |key_type| determines whether the certified key // is to be associated with the current user. |key_name| is a name for the // key. If |key_type| is KEY_USER, a |user_id| must be provided. Otherwise - // |user_id| is ignored. For normal GAIA users the |user_id| is a canonical - // email address. + // |user_id| is ignored. For normal GAIA users the |user_id| is + // a GaiaId-derived string (see AccountId::GetGaiaIdKey). virtual void AsyncTpmAttestationFinishCertRequest( const std::string& pca_response, chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const DataCallback& callback) = 0; // Asks cryptohomed to asynchronously register the attestation key specified // by |key_type| and |key_name|. If |key_type| is KEY_USER, a |user_id| must // be provided. Otherwise |user_id| is ignored. For normal GAIA users the - // |user_id| is a canonical email address. + // |user_id| is a GaiaId-derived string (see AccountId::GetGaiaIdKey). virtual void TpmAttestationRegisterKey( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const Callback& callback) = 0; @@ -160,10 +162,10 @@ // a valid enterprise challenge. On success, the data sent to |callback| is // the challenge response. If |key_type| is KEY_USER, a |user_id| must be // provided. Otherwise |user_id| is ignored. For normal GAIA users the - // |user_id| is a canonical email address. + // |user_id| is a GaiaId-derived string (see AccountId::GetGaiaIdKey). virtual void TpmAttestationSignEnterpriseChallenge( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -176,20 +178,19 @@ // set of bytes. On success, the data sent to |callback| is the challenge // response. If |key_type| is KEY_USER, a |user_id| must be provided. // Otherwise |user_id| is ignored. For normal GAIA users the |user_id| is a - // canonical email address. + // GaiaId-derived string (see AccountId::GetGaiaIdKey). virtual void TpmAttestationSignSimpleChallenge( chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const std::string& challenge, const DataCallback& callback) = 0; // Asks cryptohome to asynchronously retrieve a string associated with given - // |user| that would be used in mount path instead of |user|. + // |user_id| that would be used in mount path instead of |user_id|. // On success the data is sent to |callback|. - virtual void AsyncGetSanitizedUsername( - const std::string& user, - const DataCallback& callback) = 0; + virtual void AsyncGetSanitizedUsername(const Identification& user_id, + const DataCallback& callback) = 0; // Creates the global AsyncMethodCaller instance. static void Initialize();
diff --git a/chromeos/cryptohome/cryptohome_parameters.cc b/chromeos/cryptohome/cryptohome_parameters.cc index c484947..5aa88578c 100644 --- a/chromeos/cryptohome/cryptohome_parameters.cc +++ b/chromeos/cryptohome/cryptohome_parameters.cc
@@ -8,14 +8,67 @@ #include <stdint.h> #include "chromeos/dbus/cryptohome/key.pb.h" +#include "components/signin/core/account_id/account_id.h" +#include "components/user_manager/known_user.h" namespace cryptohome { +namespace { -Identification::Identification(const std::string& user_id) : user_id(user_id) { +// Subsystem name for GaiaId migration status. +const char kCryptohome[] = "cryptohome"; + +const std::string GetCryptohomeId(const AccountId& account_id) { + // Guest/kiosk/managed/public accounts have empty GaiaId. Default to email. + if (account_id.GetGaiaId().empty()) + return account_id.GetUserEmail(); // Migrated + + if (GetGaiaIdMigrationStatus(account_id)) + return account_id.GetGaiaIdKey(); + + return account_id.GetUserEmail(); // Migrated +} + +} // anonymous namespace + +Identification::Identification() {} + +Identification::Identification(const AccountId& account_id) + : id_(GetCryptohomeId(account_id)) {} + +Identification::Identification(const std::string& id) : id_(id) {} + +Identification Identification::FromString(const std::string& id) { + return Identification(id); } bool Identification::operator==(const Identification& other) const { - return user_id == other.user_id; + return id_ == other.id_; +} + +bool Identification::operator<(const Identification& right) const { + return id_ < right.id_; +} + +AccountId Identification::GetAccountId() const { + const std::vector<AccountId> known_account_ids = + user_manager::known_user::GetKnownAccountIds(); + + // A LOT of tests start with --login_user <user>, and not registing this user + // before. So we might have "known_user" entry without gaia_id. + for (const AccountId& known_id : known_account_ids) { + if (!known_id.GetGaiaId().empty() && known_id.GetGaiaIdKey() == id_) { + return known_id; + } + } + + for (const AccountId& known_id : known_account_ids) { + if (known_id.GetUserEmail() == id_) { + return known_id; + } + } + + return user_manager::known_user::GetAccountId(id_, + std::string() /* gaia_id */); } KeyDefinition::AuthorizationData::Secret::Secret() : encrypt(false), @@ -183,4 +236,23 @@ MountParameters::~MountParameters() { } +bool GetGaiaIdMigrationStatus(const AccountId& account_id) { + return user_manager::known_user::GetGaiaIdMigrationStatus(account_id, + kCryptohome); +} + +void SetGaiaIdMigrationStatusDone(const AccountId& account_id) { + user_manager::known_user::SetGaiaIdMigrationStatusDone(account_id, + kCryptohome); +} + } // namespace cryptohome + +namespace BASE_HASH_NAMESPACE { + +std::size_t hash<cryptohome::Identification>::operator()( + const cryptohome::Identification& cryptohome_id) const { + return hash<std::string>()(cryptohome_id.id()); +} + +} // namespace BASE_HASH_NAMESPACE
diff --git a/chromeos/cryptohome/cryptohome_parameters.h b/chromeos/cryptohome/cryptohome_parameters.h index 3738b56..2037b21 100644 --- a/chromeos/cryptohome/cryptohome_parameters.h +++ b/chromeos/cryptohome/cryptohome_parameters.h
@@ -10,9 +10,12 @@ #include <string> #include <vector> +#include "base/containers/hash_tables.h" #include "base/memory/scoped_ptr.h" #include "chromeos/chromeos_export.h" +class AccountId; + namespace cryptohome { enum AuthKeyPrivileges { @@ -25,12 +28,28 @@ }; // Identification of the user calling cryptohome method. -struct CHROMEOS_EXPORT Identification { - explicit Identification(const std::string& user_id); +class CHROMEOS_EXPORT Identification { + public: + Identification(); + + explicit Identification(const AccountId& account_id); bool operator==(const Identification& other) const; - std::string user_id; + // This method should be used for migration purpose only. + static Identification FromString(const std::string& id); + + // Look up known user and return its AccountId. + AccountId GetAccountId() const; + + const std::string& id() const { return id_; } + + bool operator<(const Identification& right) const; + + private: + explicit Identification(const std::string&); + + std::string id_; }; // Definition of the key (e.g. password) for the cryptohome. @@ -145,6 +164,25 @@ std::vector<KeyDefinition> create_keys; }; +// This function returns true if cryptohome of |account_id| is migrated to +// gaiaId-based identifier (AccountId::GetGaiaIdKey()). +bool GetGaiaIdMigrationStatus(const AccountId& account_id); + +// This function marks |account_id| cryptohome migrated to gaiaId-based +// identifier (AccountId::GetGaiaIdKey()). +void SetGaiaIdMigrationStatusDone(const AccountId& account_id); + } // namespace cryptohome +namespace BASE_HASH_NAMESPACE { + +// Implement hashing of cryptohome::Identification, so it can be used as a key +// in STL containers. +template <> +struct hash<cryptohome::Identification> { + std::size_t operator()(const cryptohome::Identification& cryptohome_id) const; +}; + +} // namespace BASE_HASH_NAMESPACE + #endif // CHROMEOS_CRYPTOHOME_CRYPTOHOME_PARAMETERS_H_
diff --git a/chromeos/cryptohome/homedir_methods.cc b/chromeos/cryptohome/homedir_methods.cc index 8413c72..81bf153 100644 --- a/chromeos/cryptohome/homedir_methods.cc +++ b/chromeos/cryptohome/homedir_methods.cc
@@ -95,12 +95,6 @@ } } -// Fill identification protobuffer. -void FillIdentificationProtobuf(const Identification& id, - cryptohome::AccountIdentifier* id_proto) { - id_proto->set_email(id.user_id); -} - // Fill authorization protobuffer. void FillAuthorizationProtobuf(const Authorization& auth, cryptohome::AuthorizationRequest* auth_proto) { @@ -183,50 +177,38 @@ void GetKeyDataEx(const Identification& id, const std::string& label, const GetKeyDataCallback& callback) override { - cryptohome::AccountIdentifier id_proto; cryptohome::AuthorizationRequest kEmptyAuthProto; cryptohome::GetKeyDataRequest request; - FillIdentificationProtobuf(id, &id_proto); request.mutable_key()->mutable_data()->set_label(label); DBusThreadManager::Get()->GetCryptohomeClient()->GetKeyDataEx( - id_proto, - kEmptyAuthProto, - request, + id, kEmptyAuthProto, request, base::Bind(&HomedirMethodsImpl::OnGetKeyDataExCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + weak_ptr_factory_.GetWeakPtr(), callback)); } void CheckKeyEx(const Identification& id, const Authorization& auth, const Callback& callback) override { - cryptohome::AccountIdentifier id_proto; cryptohome::AuthorizationRequest auth_proto; cryptohome::CheckKeyRequest request; - FillIdentificationProtobuf(id, &id_proto); FillAuthorizationProtobuf(auth, &auth_proto); DBusThreadManager::Get()->GetCryptohomeClient()->CheckKeyEx( - id_proto, - auth_proto, - request, + id, auth_proto, request, base::Bind(&HomedirMethodsImpl::OnBaseReplyCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + weak_ptr_factory_.GetWeakPtr(), callback)); } void MountEx(const Identification& id, const Authorization& auth, const MountParameters& request, const MountCallback& callback) override { - cryptohome::AccountIdentifier id_proto; cryptohome::AuthorizationRequest auth_proto; cryptohome::MountRequest request_proto; - FillIdentificationProtobuf(id, &id_proto); FillAuthorizationProtobuf(auth, &auth_proto); if (request.ephemeral) @@ -239,12 +221,9 @@ } DBusThreadManager::Get()->GetCryptohomeClient()->MountEx( - id_proto, - auth_proto, - request_proto, + id, auth_proto, request_proto, base::Bind(&HomedirMethodsImpl::OnMountExCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + weak_ptr_factory_.GetWeakPtr(), callback)); } void AddKeyEx(const Identification& id, @@ -252,43 +231,33 @@ const KeyDefinition& new_key, bool clobber_if_exists, const Callback& callback) override { - cryptohome::AccountIdentifier id_proto; cryptohome::AuthorizationRequest auth_proto; cryptohome::AddKeyRequest request; - FillIdentificationProtobuf(id, &id_proto); FillAuthorizationProtobuf(auth, &auth_proto); FillKeyProtobuf(new_key, request.mutable_key()); request.set_clobber_if_exists(clobber_if_exists); DBusThreadManager::Get()->GetCryptohomeClient()->AddKeyEx( - id_proto, - auth_proto, - request, + id, auth_proto, request, base::Bind(&HomedirMethodsImpl::OnBaseReplyCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + weak_ptr_factory_.GetWeakPtr(), callback)); } void RemoveKeyEx(const Identification& id, const Authorization& auth, const std::string& label, const Callback& callback) override { - cryptohome::AccountIdentifier id_proto; cryptohome::AuthorizationRequest auth_proto; cryptohome::RemoveKeyRequest request; - FillIdentificationProtobuf(id, &id_proto); FillAuthorizationProtobuf(auth, &auth_proto); request.mutable_key()->mutable_data()->set_label(label); DBusThreadManager::Get()->GetCryptohomeClient()->RemoveKeyEx( - id_proto, - auth_proto, - request, + id, auth_proto, request, base::Bind(&HomedirMethodsImpl::OnBaseReplyCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + weak_ptr_factory_.GetWeakPtr(), callback)); } void UpdateKeyEx(const Identification& id, @@ -296,22 +265,17 @@ const KeyDefinition& new_key, const std::string& signature, const Callback& callback) override { - cryptohome::AccountIdentifier id_proto; cryptohome::AuthorizationRequest auth_proto; cryptohome::UpdateKeyRequest pb_update_key; - FillIdentificationProtobuf(id, &id_proto); FillAuthorizationProtobuf(auth, &auth_proto); FillKeyProtobuf(new_key, pb_update_key.mutable_changes()); pb_update_key.set_authorization_signature(signature); DBusThreadManager::Get()->GetCryptohomeClient()->UpdateKeyEx( - id_proto, - auth_proto, - pb_update_key, + id, auth_proto, pb_update_key, base::Bind(&HomedirMethodsImpl::OnBaseReplyCallback, - weak_ptr_factory_.GetWeakPtr(), - callback)); + weak_ptr_factory_.GetWeakPtr(), callback)); } private:
diff --git a/chromeos/cryptohome/homedir_methods_unittest.cc b/chromeos/cryptohome/homedir_methods_unittest.cc index 19b039d..8343fa1d 100644 --- a/chromeos/cryptohome/homedir_methods_unittest.cc +++ b/chromeos/cryptohome/homedir_methods_unittest.cc
@@ -17,6 +17,7 @@ #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/mock_cryptohome_client.h" +#include "components/signin/core/account_id/account_id.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -36,6 +37,10 @@ return actual_value == expected_value; } +MATCHER_P(EqualsIdentification, expected_identification, "") { + return arg == expected_identification; +} + } // namespace const char kUserID[] = "user@example.com"; @@ -68,7 +73,7 @@ chromeos::MockCryptohomeClient* cryptohome_client_; // The reply that |cryptohome_client_| will make. - cryptohome::BaseReply cryptohome_reply_; + BaseReply cryptohome_reply_; // The results of the most recent |HomedirMethods| method call. bool success_; @@ -119,25 +124,22 @@ // Verifies that the result of a GetKeyDataEx() call is correctly parsed. TEST_F(HomedirMethodsTest, GetKeyDataEx) { - AccountIdentifier expected_id; - expected_id.set_email(kUserID); - const cryptohome::AuthorizationRequest expected_auth; - cryptohome::GetKeyDataRequest expected_request; - expected_request.mutable_key()->mutable_data()->set_label(kKeyLabel); + const Identification expected_id(AccountId::FromUserEmail(kUserID)); + const AuthorizationRequest expected_auth; + GetKeyDataRequest expected_request; + expected_request.mutable_key()->mutable_data()->set_label(kKeyLabel); EXPECT_CALL(*cryptohome_client_, - GetKeyDataEx(EqualsProto(expected_id), + GetKeyDataEx(EqualsIdentification(expected_id), EqualsProto(expected_auth), - EqualsProto(expected_request), - _)) + EqualsProto(expected_request), _)) .Times(1) - .WillOnce(WithArg<3>(Invoke( - this, - &HomedirMethodsTest::RunProtobufMethodCallback))); + .WillOnce(WithArg<3>( + Invoke(this, &HomedirMethodsTest::RunProtobufMethodCallback))); // Set up the reply that |cryptohome_client_| will make. - cryptohome::GetKeyDataReply* reply = - cryptohome_reply_.MutableExtension(cryptohome::GetKeyDataReply::reply); + GetKeyDataReply* reply = + cryptohome_reply_.MutableExtension(GetKeyDataReply::reply); KeyData* key_data = reply->add_key_data(); key_data->set_type(KeyData::KEY_TYPE_PASSWORD); key_data->set_label(kKeyLabel); @@ -155,10 +157,9 @@ // Call GetKeyDataEx(). HomedirMethods::GetInstance()->GetKeyDataEx( - Identification(kUserID), - kKeyLabel, - base::Bind(&HomedirMethodsTest::StoreGetKeyDataExResult, - base::Unretained(this))); + Identification(AccountId::FromUserEmail(kUserID)), kKeyLabel, + base::Bind(&HomedirMethodsTest::StoreGetKeyDataExResult, + base::Unretained(this))); // Verify that the call was successful and the result was correctly parsed. EXPECT_TRUE(success_);
diff --git a/chromeos/cryptohome/mock_async_method_caller.h b/chromeos/cryptohome/mock_async_method_caller.h index 97ead2fa..2a3c3b03 100644 --- a/chromeos/cryptohome/mock_async_method_caller.h +++ b/chromeos/cryptohome/mock_async_method_caller.h
@@ -10,6 +10,7 @@ #include "base/callback.h" #include "base/macros.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "testing/gmock/include/gmock/gmock.h" namespace cryptohome { @@ -27,27 +28,32 @@ void SetUp(bool success, MountError return_code); - MOCK_METHOD3(AsyncCheckKey, void(const std::string& user_email, - const std::string& passhash, - Callback callback)); - MOCK_METHOD4(AsyncMigrateKey, void(const std::string& user_email, - const std::string& old_hash, - const std::string& new_hash, - Callback callback)); - MOCK_METHOD4(AsyncMount, void(const std::string& user_email, - const std::string& passhash, - int flags, - Callback callback)); - MOCK_METHOD4(AsyncAddKey, void(const std::string& user_email, - const std::string& passhash, - const std::string& new_key, - Callback callback)); + MOCK_METHOD3(AsyncCheckKey, + void(const Identification& user_id, + const std::string& passhash, + Callback callback)); + MOCK_METHOD4(AsyncMigrateKey, + void(const Identification& user_id, + const std::string& old_hash, + const std::string& new_hash, + Callback callback)); + MOCK_METHOD4(AsyncMount, + void(const Identification& user_id, + const std::string& passhash, + int flags, + Callback callback)); + MOCK_METHOD4(AsyncAddKey, + void(const Identification& user_id, + const std::string& passhash, + const std::string& new_key, + Callback callback)); MOCK_METHOD1(AsyncMountGuest, void(Callback callback)); - MOCK_METHOD3(AsyncMountPublic, void(const std::string& public_mount_id, - int flags, - Callback callback)); - MOCK_METHOD2(AsyncRemove, void(const std::string& user_email, - Callback callback)); + MOCK_METHOD3(AsyncMountPublic, + void(const Identification& public_mount_id, + int flags, + Callback callback)); + MOCK_METHOD2(AsyncRemove, + void(const Identification& user_id, Callback callback)); MOCK_METHOD2(AsyncTpmAttestationCreateEnrollRequest, void(chromeos::attestation::PrivacyCAType pca_type, const DataCallback& callback)); @@ -59,38 +65,37 @@ AsyncTpmAttestationCreateCertRequest, void(chromeos::attestation::PrivacyCAType pca_type, chromeos::attestation::AttestationCertificateProfile profile, - const std::string& user_id, + const Identification& user_id, const std::string& request_origin, const DataCallback& callback)); MOCK_METHOD5(AsyncTpmAttestationFinishCertRequest, void(const std::string& pca_response, chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const DataCallback& callback)); MOCK_METHOD4(TpmAttestationRegisterKey, void(chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const Callback& callback)); - MOCK_METHOD8( - TpmAttestationSignEnterpriseChallenge, - void(chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - const std::string& domain, - const std::string& device_id, - chromeos::attestation::AttestationChallengeOptions options, - const std::string& challenge, - const DataCallback& callback)); + MOCK_METHOD8(TpmAttestationSignEnterpriseChallenge, + void(chromeos::attestation::AttestationKeyType key_type, + const Identification& user_id, + const std::string& key_name, + const std::string& domain, + const std::string& device_id, + chromeos::attestation::AttestationChallengeOptions options, + const std::string& challenge, + const DataCallback& callback)); MOCK_METHOD5(TpmAttestationSignSimpleChallenge, void(chromeos::attestation::AttestationKeyType key_type, - const std::string& user_id, + const Identification& user_id, const std::string& key_name, const std::string& challenge, const DataCallback& callback)); MOCK_METHOD2(AsyncGetSanitizedUsername, - void(const std::string& user, + void(const Identification& user_id, const DataCallback& callback)); private:
diff --git a/chromeos/dbus/cryptohome_client.cc b/chromeos/dbus/cryptohome_client.cc index c2b3e82..0df97a3 100644 --- a/chromeos/dbus/cryptohome_client.cc +++ b/chromeos/dbus/cryptohome_client.cc
@@ -13,6 +13,7 @@ #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "chromeos/cryptohome/async_method_caller.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/blocking_method_caller.h" #include "chromeos/dbus/cryptohome/key.pb.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" @@ -28,8 +29,8 @@ namespace { -// This suffix is appended to user_id to get hash in stub implementation: -// stub_hash = "[user_id]-hash"; +// This suffix is appended to cryptohome_id to get hash in stub implementation: +// stub_hash = "[cryptohome_id]-hash"; static const char kUserIdStubHashSuffix[] = "-hash"; // Timeout for TPM operations. On slow machines it should be larger, than @@ -37,6 +38,11 @@ // is 2 minutes. const int kTpmDBusTimeoutMs = 2 * 60 * 1000; +void FillIdentificationProtobuf(const cryptohome::Identification& id, + cryptohome::AccountIdentifier* id_proto) { + id_proto->set_account_id(id.id()); +} + // The CryptohomeClient implementation. class CryptohomeClientImpl : public CryptohomeClient { public: @@ -77,13 +83,13 @@ } // CryptohomeClient override. - void AsyncCheckKey(const std::string& username, + void AsyncCheckKey(const cryptohome::Identification& cryptohome_id, const std::string& key, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeAsyncCheckKey); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnAsyncMethodCall, @@ -92,14 +98,14 @@ } // CryptohomeClient override. - void AsyncMigrateKey(const std::string& username, + void AsyncMigrateKey(const cryptohome::Identification& cryptohome_id, const std::string& from_key, const std::string& to_key, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeAsyncMigrateKey); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); writer.AppendString(from_key); writer.AppendString(to_key); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , @@ -109,12 +115,12 @@ } // CryptohomeClient override. - void AsyncRemove(const std::string& username, + void AsyncRemove(const cryptohome::Identification& cryptohome_id, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeAsyncRemove); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnAsyncMethodCall, weak_ptr_factory_.GetWeakPtr(), @@ -132,12 +138,12 @@ } // CryptohomeClient override, - void GetSanitizedUsername(const std::string& username, + void GetSanitizedUsername(const cryptohome::Identification& cryptohome_id, const StringDBusMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeGetSanitizedUsername); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnStringMethod, weak_ptr_factory_.GetWeakPtr(), @@ -146,11 +152,11 @@ // CryptohomeClient override. std::string BlockingGetSanitizedUsername( - const std::string& username) override { + const cryptohome::Identification& cryptohome_id) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeGetSanitizedUsername); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); scoped_ptr<dbus::Response> response = blocking_method_caller_->CallMethodAndBlock(&method_call); @@ -165,14 +171,14 @@ } // CryptohomeClient override. - void AsyncMount(const std::string& username, + void AsyncMount(const cryptohome::Identification& cryptohome_id, const std::string& key, int flags, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeAsyncMount); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key); writer.AppendBool(flags & cryptohome::CREATE_IF_MISSING); writer.AppendBool(flags & cryptohome::ENSURE_EPHEMERAL); @@ -185,14 +191,14 @@ } // CryptohomeClient override. - void AsyncAddKey(const std::string& username, + void AsyncAddKey(const cryptohome::Identification& cryptohome_id, const std::string& key, const std::string& new_key, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeAsyncAddKey); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key); writer.AppendString(new_key); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , @@ -212,13 +218,13 @@ } // CryptohomeClient override. - void AsyncMountPublic(const std::string& public_mount_id, + void AsyncMountPublic(const cryptohome::Identification& public_mount_id, int flags, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeAsyncMountPublic); dbus::MessageWriter writer(&method_call); - writer.AppendString(public_mount_id); + writer.AppendString(public_mount_id.id()); writer.AppendBool(flags & cryptohome::CREATE_IF_MISSING); writer.AppendBool(flags & cryptohome::ENSURE_EPHEMERAL); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , @@ -336,13 +342,13 @@ // CryptohomeClient override. void Pkcs11GetTpmTokenInfoForUser( - const std::string& user_email, + const cryptohome::Identification& cryptohome_id, const Pkcs11GetTpmTokenInfoCallback& callback) override { dbus::MethodCall method_call( cryptohome::kCryptohomeInterface, cryptohome::kCryptohomePkcs11GetTpmTokenInfoForUser); dbus::MessageWriter writer(&method_call); - writer.AppendString(user_email); + writer.AppendString(cryptohome_id.id()); proxy_->CallMethod( &method_call, kTpmDBusTimeoutMs , base::Bind( @@ -473,7 +479,7 @@ void AsyncTpmAttestationCreateCertRequest( attestation::PrivacyCAType pca_type, attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& request_origin, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call( @@ -482,7 +488,7 @@ dbus::MessageWriter writer(&method_call); writer.AppendInt32(pca_type); writer.AppendInt32(certificate_profile); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(request_origin); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnAsyncMethodCall, @@ -494,7 +500,7 @@ void AsyncTpmAttestationFinishCertRequest( const std::string& pca_response, attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback) override { dbus::MethodCall method_call( @@ -506,7 +512,7 @@ pca_response.size()); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnAsyncMethodCall, @@ -517,7 +523,7 @@ // CryptohomeClient override. void TpmAttestationDoesKeyExist( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const BoolDBusMethodCallback& callback) override { dbus::MethodCall method_call( @@ -526,7 +532,7 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); CallBoolMethod(&method_call, callback); } @@ -534,7 +540,7 @@ // CryptohomeClient override. void TpmAttestationGetCertificate( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) override { dbus::MethodCall method_call( @@ -543,7 +549,7 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnDataMethod, @@ -552,17 +558,18 @@ } // CryptohomeClient override. - void TpmAttestationGetPublicKey(attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - const DataMethodCallback& callback) override { + void TpmAttestationGetPublicKey( + attestation::AttestationKeyType key_type, + const cryptohome::Identification& cryptohome_id, + const std::string& key_name, + const DataMethodCallback& callback) override { dbus::MethodCall method_call( cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeTpmAttestationGetPublicKey); dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnDataMethod, @@ -571,17 +578,18 @@ } // CryptohomeClient override. - void TpmAttestationRegisterKey(attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - const AsyncMethodCallback& callback) override { + void TpmAttestationRegisterKey( + attestation::AttestationKeyType key_type, + const cryptohome::Identification& cryptohome_id, + const std::string& key_name, + const AsyncMethodCallback& callback) override { dbus::MethodCall method_call( cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeTpmAttestationRegisterKey); dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnAsyncMethodCall, @@ -592,7 +600,7 @@ // CryptohomeClient override. void TpmAttestationSignEnterpriseChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -605,7 +613,7 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); writer.AppendString(domain); writer.AppendArrayOfBytes( @@ -624,7 +632,7 @@ // CryptohomeClient override. void TpmAttestationSignSimpleChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& challenge, const AsyncMethodCallback& callback) override { @@ -634,7 +642,7 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); writer.AppendArrayOfBytes( reinterpret_cast<const uint8_t*>(challenge.data()), challenge.size()); @@ -647,7 +655,7 @@ // CryptohomeClient override. void TpmAttestationGetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) override { dbus::MethodCall method_call( @@ -656,7 +664,7 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); proxy_->CallMethod(&method_call, kTpmDBusTimeoutMs , base::Bind(&CryptohomeClientImpl::OnDataMethod, @@ -667,7 +675,7 @@ // CryptohomeClient override. void TpmAttestationSetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& payload, const BoolDBusMethodCallback& callback) override { @@ -677,7 +685,7 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_name); writer.AppendArrayOfBytes(reinterpret_cast<const uint8_t*>(payload.data()), payload.size()); @@ -687,7 +695,7 @@ // CryptohomeClient override. void TpmAttestationDeleteKeys( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_prefix, const BoolDBusMethodCallback& callback) override { dbus::MethodCall method_call( @@ -696,19 +704,22 @@ dbus::MessageWriter writer(&method_call); bool is_user_specific = (key_type == attestation::KEY_USER); writer.AppendBool(is_user_specific); - writer.AppendString(user_id); + writer.AppendString(cryptohome_id.id()); writer.AppendString(key_prefix); CallBoolMethod(&method_call, callback); } - void GetKeyDataEx(const cryptohome::AccountIdentifier& id, + void GetKeyDataEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::GetKeyDataRequest& request, const ProtobufMethodCallback& callback) override { + cryptohome::AccountIdentifier id_proto; + FillIdentificationProtobuf(id, &id_proto); + dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, cryptohome::kCryptohomeGetKeyDataEx); dbus::MessageWriter writer(&method_call); - writer.AppendProtoAsArrayOfBytes(id); + writer.AppendProtoAsArrayOfBytes(id_proto); writer.AppendProtoAsArrayOfBytes(auth); writer.AppendProtoAsArrayOfBytes(request); @@ -719,7 +730,7 @@ callback)); } - void CheckKeyEx(const cryptohome::AccountIdentifier& id, + void CheckKeyEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::CheckKeyRequest& request, const ProtobufMethodCallback& callback) override { @@ -727,8 +738,11 @@ dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); + cryptohome::AccountIdentifier id_proto; + FillIdentificationProtobuf(id, &id_proto); + dbus::MessageWriter writer(&method_call); - writer.AppendProtoAsArrayOfBytes(id); + writer.AppendProtoAsArrayOfBytes(id_proto); writer.AppendProtoAsArrayOfBytes(auth); writer.AppendProtoAsArrayOfBytes(request); @@ -738,7 +752,7 @@ callback)); } - void MountEx(const cryptohome::AccountIdentifier& id, + void MountEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::MountRequest& request, const ProtobufMethodCallback& callback) override { @@ -746,8 +760,11 @@ dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); + cryptohome::AccountIdentifier id_proto; + FillIdentificationProtobuf(id, &id_proto); + dbus::MessageWriter writer(&method_call); - writer.AppendProtoAsArrayOfBytes(id); + writer.AppendProtoAsArrayOfBytes(id_proto); writer.AppendProtoAsArrayOfBytes(auth); writer.AppendProtoAsArrayOfBytes(request); @@ -757,7 +774,7 @@ callback)); } - void AddKeyEx(const cryptohome::AccountIdentifier& id, + void AddKeyEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::AddKeyRequest& request, const ProtobufMethodCallback& callback) override { @@ -765,8 +782,11 @@ dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); + cryptohome::AccountIdentifier id_proto; + FillIdentificationProtobuf(id, &id_proto); + dbus::MessageWriter writer(&method_call); - writer.AppendProtoAsArrayOfBytes(id); + writer.AppendProtoAsArrayOfBytes(id_proto); writer.AppendProtoAsArrayOfBytes(auth); writer.AppendProtoAsArrayOfBytes(request); @@ -776,7 +796,7 @@ callback)); } - void UpdateKeyEx(const cryptohome::AccountIdentifier& id, + void UpdateKeyEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::UpdateKeyRequest& request, const ProtobufMethodCallback& callback) override { @@ -784,8 +804,11 @@ dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); + cryptohome::AccountIdentifier id_proto; + FillIdentificationProtobuf(id, &id_proto); + dbus::MessageWriter writer(&method_call); - writer.AppendProtoAsArrayOfBytes(id); + writer.AppendProtoAsArrayOfBytes(id_proto); writer.AppendProtoAsArrayOfBytes(auth); writer.AppendProtoAsArrayOfBytes(request); @@ -796,15 +819,18 @@ callback)); } - void RemoveKeyEx(const cryptohome::AccountIdentifier& id, + void RemoveKeyEx(const cryptohome::Identification& id, const cryptohome::AuthorizationRequest& auth, const cryptohome::RemoveKeyRequest& request, const ProtobufMethodCallback& callback) override { const char* method_name = cryptohome::kCryptohomeRemoveKeyEx; dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); + cryptohome::AccountIdentifier id_proto; + FillIdentificationProtobuf(id, &id_proto); + dbus::MessageWriter writer(&method_call); - writer.AppendProtoAsArrayOfBytes(id); + writer.AppendProtoAsArrayOfBytes(id_proto); writer.AppendProtoAsArrayOfBytes(auth); writer.AppendProtoAsArrayOfBytes(request); @@ -1139,8 +1165,8 @@ // static std::string CryptohomeClient::GetStubSanitizedUsername( - const std::string& username) { - return username + kUserIdStubHashSuffix; + const cryptohome::Identification& cryptohome_id) { + return cryptohome_id.id() + kUserIdStubHashSuffix; } } // namespace chromeos
diff --git a/chromeos/dbus/cryptohome_client.h b/chromeos/dbus/cryptohome_client.h index 09116e3..233ff93 100644 --- a/chromeos/dbus/cryptohome_client.h +++ b/chromeos/dbus/cryptohome_client.h
@@ -19,7 +19,6 @@ namespace cryptohome { -class AccountIdentifier; class AddKeyRequest; class AuthorizationRequest; class BaseReply; @@ -32,6 +31,8 @@ class SetBootAttributeRequest; class UpdateKeyRequest; +class Identification; + } // namespace cryptohome namespace chromeos { @@ -95,7 +96,8 @@ static CryptohomeClient* Create(); // Returns the sanitized |username| that the stub implementation would return. - static std::string GetStubSanitizedUsername(const std::string& username); + static std::string GetStubSanitizedUsername( + const cryptohome::Identification& cryptohome_id); // Sets AsyncCallStatus signal handlers. // |handler| is called when results for AsyncXXX methods are returned. @@ -121,20 +123,20 @@ // Calls AsyncCheckKey method. |callback| is called after the method call // succeeds. - virtual void AsyncCheckKey(const std::string& username, + virtual void AsyncCheckKey(const cryptohome::Identification& cryptohome_id, const std::string& key, const AsyncMethodCallback& callback) = 0; // Calls AsyncMigrateKey method. |callback| is called after the method call // succeeds. - virtual void AsyncMigrateKey(const std::string& username, + virtual void AsyncMigrateKey(const cryptohome::Identification& cryptohome_id, const std::string& from_key, const std::string& to_key, const AsyncMethodCallback& callback) = 0; // Calls AsyncRemove method. |callback| is called after the method call // succeeds. - virtual void AsyncRemove(const std::string& username, + virtual void AsyncRemove(const cryptohome::Identification& cryptohome_id, const AsyncMethodCallback& callback) = 0; // Calls GetSystemSalt method. |callback| is called after the method call @@ -144,7 +146,7 @@ // Calls GetSanitizedUsername method. |callback| is called after the method // call succeeds. virtual void GetSanitizedUsername( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const StringDBusMethodCallback& callback) = 0; // Same as GetSanitizedUsername() but blocks until a reply is received, and @@ -154,13 +156,13 @@ // considered acceptable (e.g. restarting the browser after a crash or after // a flag change). virtual std::string BlockingGetSanitizedUsername( - const std::string& username) = 0; + const cryptohome::Identification& cryptohome_id) = 0; // Calls the AsyncMount method to asynchronously mount the cryptohome for // |username|, using |key| to unlock it. For supported |flags|, see the // documentation of AsyncMethodCaller::AsyncMount(). // |callback| is called after the method call succeeds. - virtual void AsyncMount(const std::string& username, + virtual void AsyncMount(const cryptohome::Identification& cryptohome_id, const std::string& key, int flags, const AsyncMethodCallback& callback) = 0; @@ -168,7 +170,7 @@ // Calls the AsyncAddKey method to asynchronously add another |new_key| for // |username|, using |key| to unlock it first. // |callback| is called after the method call succeeds. - virtual void AsyncAddKey(const std::string& username, + virtual void AsyncAddKey(const cryptohome::Identification& cryptohome_id, const std::string& key, const std::string& new_key, const AsyncMethodCallback& callback) = 0; @@ -181,9 +183,10 @@ // |public_mount_id|. For supported |flags|, see the documentation of // AsyncMethodCaller::AsyncMount(). |callback| is called after the method // call succeeds. - virtual void AsyncMountPublic(const std::string& public_mount_id, - int flags, - const AsyncMethodCallback& callback) = 0; + virtual void AsyncMountPublic( + const cryptohome::Identification& public_mount_id, + int flags, + const AsyncMethodCallback& callback) = 0; // Calls TpmIsReady method. virtual void TpmIsReady(const BoolDBusMethodCallback& callback) = 0; @@ -241,11 +244,10 @@ const Pkcs11GetTpmTokenInfoCallback& callback) = 0; // Calls Pkcs11GetTpmTokenInfoForUser method. On success |callback| will - // receive PKCS #11 token information for the user identified by |user_email|. - // The |user_email| must be a canonical email address as returned by - // user_manager::User::email(). + // receive PKCS #11 token information for the user identified by + // |cryptohome_id|. virtual void Pkcs11GetTpmTokenInfoForUser( - const std::string& user_email, + const cryptohome::Identification& cryptohome_id, const Pkcs11GetTpmTokenInfoCallback& callback) = 0; // Calls InstallAttributesGet method and returns true when the call succeeds. @@ -308,19 +310,19 @@ const AsyncMethodCallback& callback) = 0; // Asynchronously creates an attestation certificate request according to - // |certificate_profile|. Some profiles require that the |user_id| of the - // currently active user and an identifier of the |request_origin| be + // |certificate_profile|. Some profiles require that the |cryptohome_id| of + // the currently active user and an identifier of the |request_origin| be // provided. |callback| will be called when the dbus call completes. When // the operation completes, the AsyncCallStatusWithDataHandler signal handler // is called. The data that is sent with the signal is a certificate request // to be sent to the Privacy CA of type |pca_type|. The certificate request // is completed by calling AsyncTpmAttestationFinishCertRequest. The - // |user_id| will not be included in the certificate request for the Privacy - // CA. + // |cryptohome_id| will not be included in the certificate request for the + // Privacy CA. virtual void AsyncTpmAttestationCreateCertRequest( chromeos::attestation::PrivacyCAType pca_type, attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& request_origin, const AsyncMethodCallback& callback) = 0; @@ -331,46 +333,45 @@ // is the response to the certificate request emitted by the Privacy CA. // |key_type| determines whether the certified key is to be associated with // the current user. |key_name| is a name for the key. If |key_type| is - // KEY_USER, a |user_id| must be provided. Otherwise |user_id| is ignored. - // For normal GAIA users the |user_id| is a canonical email address. + // KEY_USER, a |cryptohome_id| must be provided. Otherwise |cryptohome_id| + // is ignored. virtual void AsyncTpmAttestationFinishCertRequest( const std::string& pca_response, attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback) = 0; // Checks if an attestation key already exists. If the key specified by // |key_type| and |key_name| exists, then the result sent to the callback will - // be true. If |key_type| is KEY_USER, a |user_id| must be provided. - // Otherwise |user_id| is ignored. For normal GAIA users the |user_id| is a - // canonical email address. + // be true. If |key_type| is KEY_USER, a |cryptohome_id| must be provided. + // Otherwise |cryptohome_id| is ignored. virtual void TpmAttestationDoesKeyExist( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const BoolDBusMethodCallback& callback) = 0; // Gets the attestation certificate for the key specified by |key_type| and // |key_name|. |callback| will be called when the operation completes. If // the key does not exist the callback |result| parameter will be false. If - // |key_type| is KEY_USER, a |user_id| must be provided. Otherwise |user_id| - // is ignored. For normal GAIA users the |user_id| is a canonical email - // address. + // |key_type| is KEY_USER, a |cryptohome_id| must be provided. Otherwise + // |cryptohome_id| + // is ignored. virtual void TpmAttestationGetCertificate( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) = 0; // Gets the public key for the key specified by |key_type| and |key_name|. // |callback| will be called when the operation completes. If the key does // not exist the callback |result| parameter will be false. If |key_type| is - // KEY_USER, a |user_id| must be provided. Otherwise |user_id| is ignored. - // For normal GAIA users the |user_id| is a canonical email address. + // KEY_USER, a |cryptohome_id| must be provided. Otherwise |cryptohome_id| + // is ignored. virtual void TpmAttestationGetPublicKey( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) = 0; @@ -378,12 +379,11 @@ // PKCS #11 token. The |callback| will be called when the dbus call // completes. When the operation completes, the AsyncCallStatusHandler signal // handler is called. |key_type| and |key_name| specify the key to register. - // If |key_type| is KEY_USER, a |user_id| must be provided. Otherwise - // |user_id| is ignored. For normal GAIA users the |user_id| is a canonical - // email address. + // If |key_type| is KEY_USER, a |cryptohome_id| must be provided. Otherwise + // |cryptohome_id| is ignored. virtual void TpmAttestationRegisterKey( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback) = 0; @@ -393,12 +393,11 @@ // generated. |challenge| must be a valid enterprise attestation challenge. // The |callback| will be called when the dbus call completes. When the // operation completes, the AsyncCallStatusWithDataHandler signal handler is - // called. If |key_type| is KEY_USER, a |user_id| must be provided. - // Otherwise |user_id| is ignored. For normal GAIA users the |user_id| is a - // canonical email address. + // called. If |key_type| is KEY_USER, a |cryptohome_id| must be provided. + // Otherwise |cryptohome_id| is ignored. virtual void TpmAttestationSignEnterpriseChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -412,11 +411,11 @@ // cannot be used to sign arbitrary data. The |callback| will be called when // the dbus call completes. When the operation completes, the // AsyncCallStatusWithDataHandler signal handler is called. If |key_type| is - // KEY_USER, a |user_id| must be provided. Otherwise |user_id| is ignored. - // For normal GAIA users the |user_id| is a canonical email address. + // KEY_USER, a |cryptohome_id| must be provided. Otherwise |cryptohome_id| + // is ignored. virtual void TpmAttestationSignSimpleChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& challenge, const AsyncMethodCallback& callback) = 0; @@ -426,23 +425,22 @@ // If the key does not exist the callback |result| parameter will be false. // If no payload has been set for the key the callback |result| parameter will // be true and the |data| parameter will be empty. If |key_type| is - // KEY_USER, a |user_id| must be provided. Otherwise |user_id| is ignored. - // For normal GAIA users the |user_id| is a canonical email address. + // KEY_USER, a |cryptohome_id| must be provided. Otherwise |cryptohome_id| + // is ignored. virtual void TpmAttestationGetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) = 0; // Sets the |payload| associated with the key specified by |key_type| and // |key_name|. The |callback| will be called when the operation completes. // If the operation succeeds, the callback |result| parameter will be true. - // If |key_type| is KEY_USER, a |user_id| must be provided. Otherwise - // |user_id| is ignored. For normal GAIA users the |user_id| is a canonical - // email address. + // If |key_type| is KEY_USER, a |cryptohome_id| must be provided. Otherwise + // |cryptohome_id| is ignored. virtual void TpmAttestationSetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& payload, const BoolDBusMethodCallback& callback) = 0; @@ -450,14 +448,14 @@ // Deletes certified keys as specified by |key_type| and |key_prefix|. The // |callback| will be called when the operation completes. If the operation // succeeds, the callback |result| parameter will be true. If |key_type| is - // KEY_USER, a |user_id| must be provided. Otherwise |user_id| is ignored. - // For normal GAIA users the |user_id| is a canonical email address. All keys - // where the key name has a prefix matching |key_prefix| will be deleted. All - // meta-data associated with the key, including certificates, will also be - // deleted. + // KEY_USER, a |cryptohome_id| must be provided. Otherwise |cryptohome_id| + // is ignored. + // All keys where the key name has a prefix matching |key_prefix| will be + // deleted. All meta-data associated with the key, including certificates, + // will also be deleted. virtual void TpmAttestationDeleteKeys( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_prefix, const BoolDBusMethodCallback& callback) = 0; @@ -466,56 +464,51 @@ // GetKeyDataEx returns information about the key specified in |request|. At // present, this does not include any secret information and the call should // not be authenticated (|auth| should be empty). - virtual void GetKeyDataEx( - const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::GetKeyDataRequest& request, - const ProtobufMethodCallback& callback) = 0; + virtual void GetKeyDataEx(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::GetKeyDataRequest& request, + const ProtobufMethodCallback& callback) = 0; // Asynchronously calls CheckKeyEx method. |callback| is called after method // call, and with reply protobuf. // CheckKeyEx just checks if authorization information is valid. - virtual void CheckKeyEx( - const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::CheckKeyRequest& request, - const ProtobufMethodCallback& callback) = 0; + virtual void CheckKeyEx(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::CheckKeyRequest& request, + const ProtobufMethodCallback& callback) = 0; // Asynchronously calls MountEx method. |callback| is called after method // call, and with reply protobuf. // MountEx attempts to mount home dir using given authorization, and can // create new home dir if necessary values are specified in |request|. - virtual void MountEx( - const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::MountRequest& request, - const ProtobufMethodCallback& callback) = 0; + virtual void MountEx(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::MountRequest& request, + const ProtobufMethodCallback& callback) = 0; // Asynchronously calls AddKeyEx method. |callback| is called after method // call, and with reply protobuf. // AddKeyEx adds another key to the given key set. |request| also defines // behavior in case when key with specified label already exist. - virtual void AddKeyEx( - const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::AddKeyRequest& request, - const ProtobufMethodCallback& callback) = 0; + virtual void AddKeyEx(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::AddKeyRequest& request, + const ProtobufMethodCallback& callback) = 0; // Asynchronously calls UpdateKeyEx method. |callback| is called after method // call, and with reply protobuf. Reply will contain MountReply extension. // UpdateKeyEx replaces key used for authorization, without affecting any // other keys. If specified at home dir creation time, new key may have // to be signed and/or encrypted. - virtual void UpdateKeyEx( - const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::UpdateKeyRequest& request, - const ProtobufMethodCallback& callback) = 0; + virtual void UpdateKeyEx(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::UpdateKeyRequest& request, + const ProtobufMethodCallback& callback) = 0; // Asynchronously calls RemoveKeyEx method. |callback| is called after method // call, and with reply protobuf. // RemoveKeyEx removes key from the given key set. - virtual void RemoveKeyEx(const cryptohome::AccountIdentifier& id, + virtual void RemoveKeyEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::RemoveKeyRequest& request, const ProtobufMethodCallback& callback) = 0;
diff --git a/chromeos/dbus/fake_cryptohome_client.cc b/chromeos/dbus/fake_cryptohome_client.cc index 236b1f9..2ae91976 100644 --- a/chromeos/dbus/fake_cryptohome_client.cc +++ b/chromeos/dbus/fake_cryptohome_client.cc
@@ -73,14 +73,14 @@ } void FakeCryptohomeClient::AsyncCheckKey( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const std::string& key, const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, false); } void FakeCryptohomeClient::AsyncMigrateKey( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const std::string& from_key, const std::string& to_key, const AsyncMethodCallback& callback) { @@ -88,7 +88,7 @@ } void FakeCryptohomeClient::AsyncRemove( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, false); } @@ -101,30 +101,31 @@ } void FakeCryptohomeClient::GetSanitizedUsername( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const StringDBusMethodCallback& callback) { // Even for stub implementation we have to return different values so that // multi-profiles would work. - std::string sanitized_username = GetStubSanitizedUsername(username); + std::string sanitized_username = GetStubSanitizedUsername(cryptohome_id); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS, sanitized_username)); } std::string FakeCryptohomeClient::BlockingGetSanitizedUsername( - const std::string& username) { - return GetStubSanitizedUsername(username); + const cryptohome::Identification& cryptohome_id) { + return GetStubSanitizedUsername(cryptohome_id); } -void FakeCryptohomeClient::AsyncMount(const std::string& username, - const std::string& key, - int flags, - const AsyncMethodCallback& callback) { +void FakeCryptohomeClient::AsyncMount( + const cryptohome::Identification& cryptohome_id, + const std::string& key, + int flags, + const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, false); } void FakeCryptohomeClient::AsyncAddKey( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const std::string& key, const std::string& new_key, const AsyncMethodCallback& callback) { @@ -137,7 +138,7 @@ } void FakeCryptohomeClient::AsyncMountPublic( - const std::string& public_mount_id, + const cryptohome::Identification& public_mount_id, int flags, const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, false); @@ -228,7 +229,7 @@ } void FakeCryptohomeClient::Pkcs11GetTpmTokenInfoForUser( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const Pkcs11GetTpmTokenInfoCallback& callback) { Pkcs11GetTpmTokenInfo(callback); } @@ -360,7 +361,7 @@ void FakeCryptohomeClient::AsyncTpmAttestationCreateCertRequest( chromeos::attestation::PrivacyCAType pca_type, attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& request_origin, const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, true); @@ -369,7 +370,7 @@ void FakeCryptohomeClient::AsyncTpmAttestationFinishCertRequest( const std::string& pca_response, attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, true); @@ -377,7 +378,7 @@ void FakeCryptohomeClient::TpmAttestationDoesKeyExist( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const BoolDBusMethodCallback& callback) { base::MessageLoop::current()->PostTask( @@ -386,7 +387,7 @@ void FakeCryptohomeClient::TpmAttestationGetCertificate( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) { base::MessageLoop::current()->PostTask( @@ -396,7 +397,7 @@ void FakeCryptohomeClient::TpmAttestationGetPublicKey( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) { base::MessageLoop::current()->PostTask( @@ -406,7 +407,7 @@ void FakeCryptohomeClient::TpmAttestationRegisterKey( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback) { ReturnAsyncMethodResult(callback, true); @@ -414,7 +415,7 @@ void FakeCryptohomeClient::TpmAttestationSignEnterpriseChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -426,7 +427,7 @@ void FakeCryptohomeClient::TpmAttestationSignSimpleChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& challenge, const AsyncMethodCallback& callback) { @@ -435,7 +436,7 @@ void FakeCryptohomeClient::TpmAttestationGetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) { base::MessageLoop::current()->PostTask( @@ -445,7 +446,7 @@ void FakeCryptohomeClient::TpmAttestationSetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& payload, const BoolDBusMethodCallback& callback) { @@ -455,7 +456,7 @@ void FakeCryptohomeClient::TpmAttestationDeleteKeys( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_prefix, const BoolDBusMethodCallback& callback) { base::MessageLoop::current()->PostTask( @@ -463,7 +464,7 @@ } void FakeCryptohomeClient::GetKeyDataEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::GetKeyDataRequest& request, const ProtobufMethodCallback& callback) { @@ -473,7 +474,7 @@ } void FakeCryptohomeClient::CheckKeyEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::CheckKeyRequest& request, const ProtobufMethodCallback& callback) { @@ -482,19 +483,19 @@ } void FakeCryptohomeClient::MountEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::MountRequest& request, const ProtobufMethodCallback& callback) { cryptohome::BaseReply reply; cryptohome::MountReply* mount = reply.MutableExtension(cryptohome::MountReply::reply); - mount->set_sanitized_username(GetStubSanitizedUsername(id.email())); + mount->set_sanitized_username(GetStubSanitizedUsername(cryptohome_id)); ReturnProtobufMethodCallback(reply, callback); } void FakeCryptohomeClient::AddKeyEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::AddKeyRequest& request, const ProtobufMethodCallback& callback) { @@ -503,7 +504,7 @@ } void FakeCryptohomeClient::RemoveKeyEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::RemoveKeyRequest& request, const ProtobufMethodCallback& callback) { @@ -512,7 +513,7 @@ } void FakeCryptohomeClient::UpdateKeyEx( - const cryptohome::AccountIdentifier& id, + const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::UpdateKeyRequest& request, const ProtobufMethodCallback& callback) {
diff --git a/chromeos/dbus/fake_cryptohome_client.h b/chromeos/dbus/fake_cryptohome_client.h index 801faafe..20402dc 100644 --- a/chromeos/dbus/fake_cryptohome_client.h +++ b/chromeos/dbus/fake_cryptohome_client.h
@@ -29,30 +29,30 @@ const WaitForServiceToBeAvailableCallback& callback) override; void IsMounted(const BoolDBusMethodCallback& callback) override; bool Unmount(bool* success) override; - void AsyncCheckKey(const std::string& username, + void AsyncCheckKey(const cryptohome::Identification& cryptohome_id, const std::string& key, const AsyncMethodCallback& callback) override; - void AsyncMigrateKey(const std::string& username, + void AsyncMigrateKey(const cryptohome::Identification& cryptohome_id, const std::string& from_key, const std::string& to_key, const AsyncMethodCallback& callback) override; - void AsyncRemove(const std::string& username, + void AsyncRemove(const cryptohome::Identification& cryptohome_id, const AsyncMethodCallback& callback) override; void GetSystemSalt(const GetSystemSaltCallback& callback) override; - void GetSanitizedUsername(const std::string& username, + void GetSanitizedUsername(const cryptohome::Identification& cryptohome_id, const StringDBusMethodCallback& callback) override; std::string BlockingGetSanitizedUsername( - const std::string& username) override; - void AsyncMount(const std::string& username, + const cryptohome::Identification& cryptohome_id) override; + void AsyncMount(const cryptohome::Identification& cryptohome_id, const std::string& key, int flags, const AsyncMethodCallback& callback) override; - void AsyncAddKey(const std::string& username, + void AsyncAddKey(const cryptohome::Identification& cryptohome_id, const std::string& key, const std::string& new_key, const AsyncMethodCallback& callback) override; void AsyncMountGuest(const AsyncMethodCallback& callback) override; - void AsyncMountPublic(const std::string& public_mount_id, + void AsyncMountPublic(const cryptohome::Identification& public_mount_id, int flags, const AsyncMethodCallback& callback) override; void TpmIsReady(const BoolDBusMethodCallback& callback) override; @@ -70,7 +70,7 @@ void Pkcs11GetTpmTokenInfo( const Pkcs11GetTpmTokenInfoCallback& callback) override; void Pkcs11GetTpmTokenInfoForUser( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const Pkcs11GetTpmTokenInfoCallback& callback) override; bool InstallAttributesGet(const std::string& name, std::vector<uint8_t>* value, @@ -96,36 +96,38 @@ void AsyncTpmAttestationCreateCertRequest( chromeos::attestation::PrivacyCAType pca_type, attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& request_origin, const AsyncMethodCallback& callback) override; void AsyncTpmAttestationFinishCertRequest( const std::string& pca_response, attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback) override; void TpmAttestationDoesKeyExist( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const BoolDBusMethodCallback& callback) override; void TpmAttestationGetCertificate( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback) override; - void TpmAttestationGetPublicKey(attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - const DataMethodCallback& callback) override; - void TpmAttestationRegisterKey(attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - const AsyncMethodCallback& callback) override; + void TpmAttestationGetPublicKey( + attestation::AttestationKeyType key_type, + const cryptohome::Identification& cryptohome_id, + const std::string& key_name, + const DataMethodCallback& callback) override; + void TpmAttestationRegisterKey( + attestation::AttestationKeyType key_type, + const cryptohome::Identification& cryptohome_id, + const std::string& key_name, + const AsyncMethodCallback& callback) override; void TpmAttestationSignEnterpriseChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -134,46 +136,47 @@ const AsyncMethodCallback& callback) override; void TpmAttestationSignSimpleChallenge( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& challenge, const AsyncMethodCallback& callback) override; - void TpmAttestationGetKeyPayload(attestation::AttestationKeyType key_type, - const std::string& user_id, - const std::string& key_name, - const DataMethodCallback& callback) override; + void TpmAttestationGetKeyPayload( + attestation::AttestationKeyType key_type, + const cryptohome::Identification& cryptohome_id, + const std::string& key_name, + const DataMethodCallback& callback) override; void TpmAttestationSetKeyPayload( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& payload, const BoolDBusMethodCallback& callback) override; void TpmAttestationDeleteKeys( attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_prefix, const BoolDBusMethodCallback& callback) override; - void GetKeyDataEx(const cryptohome::AccountIdentifier& id, + void GetKeyDataEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::GetKeyDataRequest& request, const ProtobufMethodCallback& callback) override; - void CheckKeyEx(const cryptohome::AccountIdentifier& id, + void CheckKeyEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::CheckKeyRequest& request, const ProtobufMethodCallback& callback) override; - void MountEx(const cryptohome::AccountIdentifier& id, + void MountEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::MountRequest& request, const ProtobufMethodCallback& callback) override; - void AddKeyEx(const cryptohome::AccountIdentifier& id, + void AddKeyEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::AddKeyRequest& request, const ProtobufMethodCallback& callback) override; - void UpdateKeyEx(const cryptohome::AccountIdentifier& id, + void UpdateKeyEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::UpdateKeyRequest& request, const ProtobufMethodCallback& callback) override; - void RemoveKeyEx(const cryptohome::AccountIdentifier& id, + void RemoveKeyEx(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::RemoveKeyRequest& request, const ProtobufMethodCallback& callback) override;
diff --git a/chromeos/dbus/fake_session_manager_client.cc b/chromeos/dbus/fake_session_manager_client.cc index 77e8b37..e66b15b 100644 --- a/chromeos/dbus/fake_session_manager_client.cc +++ b/chromeos/dbus/fake_session_manager_client.cc
@@ -50,11 +50,12 @@ void FakeSessionManagerClient::RestartJob( const std::vector<std::string>& argv) {} -void FakeSessionManagerClient::StartSession(const std::string& user_email) { - DCHECK_EQ(0UL, user_sessions_.count(user_email)); +void FakeSessionManagerClient::StartSession( + const cryptohome::Identification& cryptohome_id) { + DCHECK_EQ(0UL, user_sessions_.count(cryptohome_id)); std::string user_id_hash = - CryptohomeClient::GetStubSanitizedUsername(user_email); - user_sessions_[user_email] = user_id_hash; + CryptohomeClient::GetStubSanitizedUsername(cryptohome_id); + user_sessions_[cryptohome_id] = user_id_hash; } void FakeSessionManagerClient::StopSession() { @@ -94,15 +95,15 @@ } void FakeSessionManagerClient::RetrievePolicyForUser( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const RetrievePolicyCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::Bind(callback, user_policies_[username])); + FROM_HERE, base::Bind(callback, user_policies_[cryptohome_id])); } std::string FakeSessionManagerClient::BlockingRetrievePolicyForUser( - const std::string& username) { - return user_policies_[username]; + const cryptohome::Identification& cryptohome_id) { + return user_policies_[cryptohome_id]; } void FakeSessionManagerClient::RetrieveDeviceLocalAccountPolicy( @@ -123,10 +124,10 @@ } void FakeSessionManagerClient::StorePolicyForUser( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const std::string& policy_blob, const StorePolicyCallback& callback) { - user_policies_[username] = policy_blob; + user_policies_[cryptohome_id] = policy_blob; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, true)); } @@ -141,9 +142,8 @@ } void FakeSessionManagerClient::SetFlagsForUser( - const std::string& username, - const std::vector<std::string>& flags) { -} + const cryptohome::Identification& cryptohome_id, + const std::vector<std::string>& flags) {} void FakeSessionManagerClient::GetServerBackedStateKeys( const StateKeysCallback& callback) { @@ -178,15 +178,16 @@ } const std::string& FakeSessionManagerClient::user_policy( - const std::string& username) const { - std::map<std::string, std::string>::const_iterator it = - user_policies_.find(username); + const cryptohome::Identification& cryptohome_id) const { + std::map<cryptohome::Identification, std::string>::const_iterator it = + user_policies_.find(cryptohome_id); return it == user_policies_.end() ? base::EmptyString() : it->second; } -void FakeSessionManagerClient::set_user_policy(const std::string& username, - const std::string& policy_blob) { - user_policies_[username] = policy_blob; +void FakeSessionManagerClient::set_user_policy( + const cryptohome::Identification& cryptohome_id, + const std::string& policy_blob) { + user_policies_[cryptohome_id] = policy_blob; } const std::string& FakeSessionManagerClient::device_local_account_policy(
diff --git a/chromeos/dbus/fake_session_manager_client.h b/chromeos/dbus/fake_session_manager_client.h index b281847..4150091 100644 --- a/chromeos/dbus/fake_session_manager_client.h +++ b/chromeos/dbus/fake_session_manager_client.h
@@ -12,6 +12,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/observer_list.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/session_manager_client.h" namespace chromeos { @@ -32,7 +33,7 @@ bool IsScreenLocked() const override; void EmitLoginPromptVisible() override; void RestartJob(const std::vector<std::string>& argv) override; - void StartSession(const std::string& user_email) override; + void StartSession(const cryptohome::Identification& cryptohome_id) override; void StopSession() override; void NotifySupervisedUserCreationStarted() override; void NotifySupervisedUserCreationFinished() override; @@ -42,23 +43,23 @@ void NotifyLockScreenDismissed() override; void RetrieveActiveSessions(const ActiveSessionsCallback& callback) override; void RetrieveDevicePolicy(const RetrievePolicyCallback& callback) override; - void RetrievePolicyForUser(const std::string& username, + void RetrievePolicyForUser(const cryptohome::Identification& cryptohome_id, const RetrievePolicyCallback& callback) override; std::string BlockingRetrievePolicyForUser( - const std::string& username) override; + const cryptohome::Identification& cryptohome_id) override; void RetrieveDeviceLocalAccountPolicy( const std::string& account_id, const RetrievePolicyCallback& callback) override; void StoreDevicePolicy(const std::string& policy_blob, const StorePolicyCallback& callback) override; - void StorePolicyForUser(const std::string& username, + void StorePolicyForUser(const cryptohome::Identification& cryptohome_id, const std::string& policy_blob, const StorePolicyCallback& callback) override; void StoreDeviceLocalAccountPolicy( const std::string& account_id, const std::string& policy_blob, const StorePolicyCallback& callback) override; - void SetFlagsForUser(const std::string& username, + void SetFlagsForUser(const cryptohome::Identification& cryptohome_id, const std::vector<std::string>& flags) override; void GetServerBackedStateKeys(const StateKeysCallback& callback) override; @@ -70,8 +71,9 @@ const std::string& device_policy() const; void set_device_policy(const std::string& policy_blob); - const std::string& user_policy(const std::string& username) const; - void set_user_policy(const std::string& username, + const std::string& user_policy( + const cryptohome::Identification& cryptohome_id) const; + void set_user_policy(const cryptohome::Identification& cryptohome_id, const std::string& policy_blob); const std::string& device_local_account_policy( @@ -105,7 +107,7 @@ private: std::string device_policy_; - std::map<std::string, std::string> user_policies_; + std::map<cryptohome::Identification, std::string> user_policies_; std::map<std::string, std::string> device_local_account_policy_; base::ObserverList<Observer> observers_; SessionManagerClient::ActiveSessionsMap user_sessions_;
diff --git a/chromeos/dbus/mock_cryptohome_client.h b/chromeos/dbus/mock_cryptohome_client.h index 4382d354..c4e166b 100644 --- a/chromeos/dbus/mock_cryptohome_client.h +++ b/chromeos/dbus/mock_cryptohome_client.h
@@ -9,6 +9,7 @@ #include <string> +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" #include "chromeos/dbus/cryptohome_client.h" #include "testing/gmock/include/gmock/gmock.h" @@ -30,35 +31,40 @@ MOCK_METHOD1(IsMounted, void(const BoolDBusMethodCallback& callback)); MOCK_METHOD1(Unmount, bool(bool* success)); MOCK_METHOD3(AsyncCheckKey, - void(const std::string& username, + void(const cryptohome::Identification& cryptohome_id, const std::string& key, const AsyncMethodCallback& callback)); MOCK_METHOD4(AsyncMigrateKey, - void(const std::string& username, + void(const cryptohome::Identification& cryptohome_id, const std::string& from_key, const std::string& to_key, const AsyncMethodCallback& callback)); - MOCK_METHOD2(AsyncRemove, void(const std::string& username, - const AsyncMethodCallback& callback)); + MOCK_METHOD2(AsyncRemove, + void(const cryptohome::Identification& cryptohome_id, + const AsyncMethodCallback& callback)); + MOCK_METHOD1(GetSystemSalt, void(const GetSystemSaltCallback& callback)); MOCK_METHOD2(GetSanitizedUsername, - void(const std::string& username, + void(const cryptohome::Identification& cryptohome_id, const StringDBusMethodCallback& callback)); MOCK_METHOD1(BlockingGetSanitizedUsername, - std::string(const std::string& username)); - MOCK_METHOD4(AsyncMount, void(const std::string& username, - const std::string& key, - int flags, - const AsyncMethodCallback& callback)); - MOCK_METHOD4(AsyncAddKey, void(const std::string& username, - const std::string& key, - const std::string& new_key, - const AsyncMethodCallback& callback)); + std::string(const cryptohome::Identification& cryptohome_id)); + MOCK_METHOD4(AsyncMount, + void(const cryptohome::Identification& cryptohome_id, + const std::string& key, + int flags, + const AsyncMethodCallback& callback)); + MOCK_METHOD4(AsyncAddKey, + void(const cryptohome::Identification& cryptohome_id, + const std::string& key, + const std::string& new_key, + const AsyncMethodCallback& callback)); MOCK_METHOD1(AsyncMountGuest, void(const AsyncMethodCallback& callback)); - MOCK_METHOD3(AsyncMountPublic, void(const std::string& public_mount_id, - int flags, - const AsyncMethodCallback& callback)); + MOCK_METHOD3(AsyncMountPublic, + void(const cryptohome::Identification& public_mount_id, + int flags, + const AsyncMethodCallback& callback)); MOCK_METHOD1(TpmIsReady, void(const BoolDBusMethodCallback& callback)); MOCK_METHOD1(TpmIsEnabled, void(const BoolDBusMethodCallback& callback)); MOCK_METHOD1(CallTpmIsEnabledAndBlock, bool(bool* enabled)); @@ -77,7 +83,7 @@ MOCK_METHOD1(Pkcs11GetTpmTokenInfo, void(const Pkcs11GetTpmTokenInfoCallback& callback)); MOCK_METHOD2(Pkcs11GetTpmTokenInfoForUser, - void(const std::string& username, + void(const cryptohome::Identification& cryptohome_id, const Pkcs11GetTpmTokenInfoCallback& callback)); MOCK_METHOD3(InstallAttributesGet, bool(const std::string& name, @@ -107,38 +113,38 @@ AsyncTpmAttestationCreateCertRequest, void(attestation::PrivacyCAType pca_type, attestation::AttestationCertificateProfile certificate_profile, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& request_origin, const AsyncMethodCallback& callback)); MOCK_METHOD5(AsyncTpmAttestationFinishCertRequest, void(const std::string& pca_response, attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback)); MOCK_METHOD4(TpmAttestationDoesKeyExist, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const BoolDBusMethodCallback& callback)); MOCK_METHOD4(TpmAttestationGetCertificate, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback)); MOCK_METHOD4(TpmAttestationGetPublicKey, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback)); MOCK_METHOD4(TpmAttestationRegisterKey, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const AsyncMethodCallback& callback)); MOCK_METHOD8(TpmAttestationSignEnterpriseChallenge, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& domain, const std::string& device_id, @@ -147,53 +153,53 @@ const AsyncMethodCallback& callback)); MOCK_METHOD5(TpmAttestationSignSimpleChallenge, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& challenge, const AsyncMethodCallback& callback)); MOCK_METHOD4(TpmAttestationGetKeyPayload, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const DataMethodCallback& callback)); MOCK_METHOD5(TpmAttestationSetKeyPayload, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_name, const std::string& payload, const BoolDBusMethodCallback& callback)); MOCK_METHOD4(TpmAttestationDeleteKeys, void(attestation::AttestationKeyType key_type, - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const std::string& key_prefix, const BoolDBusMethodCallback& callback)); MOCK_METHOD4(GetKeyDataEx, - void(const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::GetKeyDataRequest& request, - const ProtobufMethodCallback& callback)); + void(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::GetKeyDataRequest& request, + const ProtobufMethodCallback& callback)); MOCK_METHOD4(CheckKeyEx, - void(const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::CheckKeyRequest& request, - const ProtobufMethodCallback& callback)); + void(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::CheckKeyRequest& request, + const ProtobufMethodCallback& callback)); MOCK_METHOD4(MountEx, - void(const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::MountRequest& request, - const ProtobufMethodCallback& callback)); + void(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::MountRequest& request, + const ProtobufMethodCallback& callback)); MOCK_METHOD4(AddKeyEx, - void(const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::AddKeyRequest& request, - const ProtobufMethodCallback& callback)); + void(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::AddKeyRequest& request, + const ProtobufMethodCallback& callback)); MOCK_METHOD4(UpdateKeyEx, - void(const cryptohome::AccountIdentifier& id, - const cryptohome::AuthorizationRequest& auth, - const cryptohome::UpdateKeyRequest& request, - const ProtobufMethodCallback& callback)); + void(const cryptohome::Identification& cryptohome_id, + const cryptohome::AuthorizationRequest& auth, + const cryptohome::UpdateKeyRequest& request, + const ProtobufMethodCallback& callback)); MOCK_METHOD4(RemoveKeyEx, - void(const cryptohome::AccountIdentifier& id, + void(const cryptohome::Identification& cryptohome_id, const cryptohome::AuthorizationRequest& auth, const cryptohome::RemoveKeyRequest& request, const ProtobufMethodCallback& callback));
diff --git a/chromeos/dbus/mock_session_manager_client.h b/chromeos/dbus/mock_session_manager_client.h index aec901a..dc7d095 100644 --- a/chromeos/dbus/mock_session_manager_client.h +++ b/chromeos/dbus/mock_session_manager_client.h
@@ -7,6 +7,7 @@ #include <string> +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/session_manager_client.h" #include "testing/gmock/include/gmock/gmock.h" @@ -25,7 +26,7 @@ MOCK_CONST_METHOD0(IsScreenLocked, bool(void)); MOCK_METHOD0(EmitLoginPromptVisible, void(void)); MOCK_METHOD1(RestartJob, void(const std::vector<std::string>&)); - MOCK_METHOD1(StartSession, void(const std::string&)); + MOCK_METHOD1(StartSession, void(const cryptohome::Identification&)); MOCK_METHOD0(StopSession, void(void)); MOCK_METHOD0(NotifySupervisedUserCreationStarted, void(void)); MOCK_METHOD0(NotifySupervisedUserCreationFinished, void(void)); @@ -36,9 +37,10 @@ MOCK_METHOD1(RetrieveActiveSessions, void(const ActiveSessionsCallback&)); MOCK_METHOD1(RetrieveDevicePolicy, void(const RetrievePolicyCallback&)); MOCK_METHOD2(RetrievePolicyForUser, - void(const std::string&, + void(const cryptohome::Identification&, const RetrievePolicyCallback&)); - MOCK_METHOD1(BlockingRetrievePolicyForUser, std::string(const std::string&)); + MOCK_METHOD1(BlockingRetrievePolicyForUser, + std::string(const cryptohome::Identification&)); MOCK_METHOD2(RetrieveDeviceLocalAccountPolicy, void(const std::string&, const RetrievePolicyCallback&)); @@ -46,7 +48,7 @@ void(const std::string&, const StorePolicyCallback&)); MOCK_METHOD3(StorePolicyForUser, - void(const std::string&, + void(const cryptohome::Identification&, const std::string&, const StorePolicyCallback&)); MOCK_METHOD3(StoreDeviceLocalAccountPolicy, @@ -54,7 +56,7 @@ const std::string&, const StorePolicyCallback&)); MOCK_METHOD2(SetFlagsForUser, - void(const std::string&, + void(const cryptohome::Identification&, const std::vector<std::string>&)); MOCK_METHOD1(GetServerBackedStateKeys, void(const StateKeysCallback&)); MOCK_METHOD1(CheckArcAvailability, void(const ArcCallback&));
diff --git a/chromeos/dbus/session_manager_client.cc b/chromeos/dbus/session_manager_client.cc index dd9c13ad..95559ea 100644 --- a/chromeos/dbus/session_manager_client.cc +++ b/chromeos/dbus/session_manager_client.cc
@@ -20,6 +20,7 @@ #include "base/task_runner_util.h" #include "base/threading/worker_pool.h" #include "chromeos/chromeos_paths.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/blocking_method_caller.h" #include "chromeos/dbus/cryptohome_client.h" #include "crypto/sha2.h" @@ -34,15 +35,16 @@ namespace { -// Returns a location for |file| that is specific to the given |username|. +// Returns a location for |file| that is specific to the given |cryptohome_id|. // These paths will be relative to DIR_USER_POLICY_KEYS, and can be used only // to store stub files. -base::FilePath GetUserFilePath(const std::string& username, const char* file) { +base::FilePath GetUserFilePath(const cryptohome::Identification& cryptohome_id, + const char* file) { base::FilePath keys_path; if (!PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &keys_path)) return base::FilePath(); const std::string sanitized = - CryptohomeClient::GetStubSanitizedUsername(username); + CryptohomeClient::GetStubSanitizedUsername(cryptohome_id); return keys_path.AppendASCII(sanitized).AppendASCII(file); } @@ -153,11 +155,11 @@ false); } - void StartSession(const std::string& user_email) override { + void StartSession(const cryptohome::Identification& cryptohome_id) override { dbus::MethodCall method_call(login_manager::kSessionManagerInterface, login_manager::kSessionManagerStartSession); dbus::MessageWriter writer(&method_call); - writer.AppendString(user_email); + writer.AppendString(cryptohome_id.id()); writer.AppendString(""); // Unique ID is deprecated session_manager_proxy_->CallMethod( &method_call, @@ -238,21 +240,20 @@ callback)); } - void RetrievePolicyForUser(const std::string& username, + void RetrievePolicyForUser(const cryptohome::Identification& cryptohome_id, const RetrievePolicyCallback& callback) override { CallRetrievePolicyByUsername( - login_manager::kSessionManagerRetrievePolicyForUser, - username, + login_manager::kSessionManagerRetrievePolicyForUser, cryptohome_id.id(), callback); } std::string BlockingRetrievePolicyForUser( - const std::string& username) override { + const cryptohome::Identification& cryptohome_id) override { dbus::MethodCall method_call( login_manager::kSessionManagerInterface, login_manager::kSessionManagerRetrievePolicyForUser); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); scoped_ptr<dbus::Response> response = blocking_method_caller_->CallMethodAndBlock(&method_call); std::string policy; @@ -289,13 +290,11 @@ callback)); } - void StorePolicyForUser(const std::string& username, + void StorePolicyForUser(const cryptohome::Identification& cryptohome_id, const std::string& policy_blob, const StorePolicyCallback& callback) override { CallStorePolicyByUsername(login_manager::kSessionManagerStorePolicyForUser, - username, - policy_blob, - callback); + cryptohome_id.id(), policy_blob, callback); } void StoreDeviceLocalAccountPolicy( @@ -309,12 +308,12 @@ callback); } - void SetFlagsForUser(const std::string& username, + void SetFlagsForUser(const cryptohome::Identification& cryptohome_id, const std::vector<std::string>& flags) override { dbus::MethodCall method_call(login_manager::kSessionManagerInterface, login_manager::kSessionManagerSetFlagsForUser); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(cryptohome_id.id()); writer.AppendArrayOfStrings(flags); session_manager_proxy_->CallMethod( &method_call, @@ -423,12 +422,12 @@ // Helper for RetrieveDeviceLocalAccountPolicy and RetrievePolicyForUser. void CallRetrievePolicyByUsername(const std::string& method_name, - const std::string& username, + const std::string& account_id, const RetrievePolicyCallback& callback) { dbus::MethodCall method_call(login_manager::kSessionManagerInterface, method_name); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(account_id); session_manager_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, @@ -440,13 +439,13 @@ } void CallStorePolicyByUsername(const std::string& method_name, - const std::string& username, + const std::string& account_id, const std::string& policy_blob, const StorePolicyCallback& callback) { dbus::MethodCall method_call(login_manager::kSessionManagerInterface, method_name); dbus::MessageWriter writer(&method_call); - writer.AppendString(username); + writer.AppendString(account_id); // static_cast does not work due to signedness. writer.AppendArrayOfBytes( reinterpret_cast<const uint8_t*>(policy_blob.data()), @@ -544,7 +543,7 @@ LOG(ERROR) << method_name << " response is incorrect: " << response->ToString(); } else { - sessions[key] = value; + sessions[cryptohome::Identification::FromString(key)] = value; } } success = true; @@ -741,7 +740,7 @@ bool IsScreenLocked() const override { return screen_is_locked_; } void EmitLoginPromptVisible() override {} void RestartJob(const std::vector<std::string>& argv) override {} - void StartSession(const std::string& user_email) override {} + void StartSession(const cryptohome::Identification& cryptohome_id) override {} void StopSession() override {} void NotifySupervisedUserCreationStarted() override {} void NotifySupervisedUserCreationFinished() override {} @@ -774,22 +773,23 @@ base::Bind(&GetFileContent, device_policy_path), callback); } - void RetrievePolicyForUser(const std::string& username, + void RetrievePolicyForUser(const cryptohome::Identification& cryptohome_id, const RetrievePolicyCallback& callback) override { base::PostTaskAndReplyWithResult( - base::WorkerPool::GetTaskRunner(false).get(), - FROM_HERE, - base::Bind(&GetFileContent, GetUserFilePath(username, "stub_policy")), + base::WorkerPool::GetTaskRunner(false).get(), FROM_HERE, + base::Bind(&GetFileContent, + GetUserFilePath(cryptohome_id, "stub_policy")), callback); } std::string BlockingRetrievePolicyForUser( - const std::string& username) override { - return GetFileContent(GetUserFilePath(username, "stub_policy")); + const cryptohome::Identification& cryptohome_id) override { + return GetFileContent(GetUserFilePath(cryptohome_id, "stub_policy")); } void RetrieveDeviceLocalAccountPolicy( - const std::string& account_name, + const std::string& account_id, const RetrievePolicyCallback& callback) override { - RetrievePolicyForUser(account_name, callback); + RetrievePolicyForUser(cryptohome::Identification::FromString(account_id), + callback); } void StoreDevicePolicy(const std::string& policy_blob, const StorePolicyCallback& callback) override { @@ -821,7 +821,7 @@ base::Bind(callback, true), false); } - void StorePolicyForUser(const std::string& username, + void StorePolicyForUser(const cryptohome::Identification& cryptohome_id, const std::string& policy_blob, const StorePolicyCallback& callback) override { // The session manager writes the user policy key to a well-known @@ -834,7 +834,7 @@ } if (response.has_new_public_key()) { - base::FilePath key_path = GetUserFilePath(username, "policy.pub"); + base::FilePath key_path = GetUserFilePath(cryptohome_id, "policy.pub"); base::WorkerPool::PostTask( FROM_HERE, base::Bind(&StoreFile, key_path, response.new_public_key()), @@ -843,7 +843,8 @@ // This file isn't read directly by Chrome, but is used by this class to // reload the user policy across restarts. - base::FilePath stub_policy_path = GetUserFilePath(username, "stub_policy"); + base::FilePath stub_policy_path = + GetUserFilePath(cryptohome_id, "stub_policy"); base::WorkerPool::PostTaskAndReply( FROM_HERE, base::Bind(&StoreFile, stub_policy_path, policy_blob), @@ -851,12 +852,13 @@ false); } void StoreDeviceLocalAccountPolicy( - const std::string& account_name, + const std::string& account_id, const std::string& policy_blob, const StorePolicyCallback& callback) override { - StorePolicyForUser(account_name, policy_blob, callback); + StorePolicyForUser(cryptohome::Identification::FromString(account_id), + policy_blob, callback); } - void SetFlagsForUser(const std::string& username, + void SetFlagsForUser(const cryptohome::Identification& cryptohome_id, const std::vector<std::string>& flags) override {} void GetServerBackedStateKeys(const StateKeysCallback& callback) override {
diff --git a/chromeos/dbus/session_manager_client.h b/chromeos/dbus/session_manager_client.h index 4fd4c09..d0e3566 100644 --- a/chromeos/dbus/session_manager_client.h +++ b/chromeos/dbus/session_manager_client.h
@@ -16,6 +16,10 @@ #include "chromeos/dbus/dbus_client.h" #include "chromeos/dbus/dbus_client_implementation_type.h" +namespace cryptohome { +class Identification; +} + namespace chromeos { // SessionManagerClient is used to communicate with the session manager. @@ -78,7 +82,8 @@ virtual void RestartJob(const std::vector<std::string>& argv) = 0; // Starts the session for the user. - virtual void StartSession(const std::string& user_email) = 0; + virtual void StartSession( + const cryptohome::Identification& cryptohome_id) = 0; // Stops the current session. virtual void StopSession() = 0; @@ -102,19 +107,19 @@ virtual void NotifySupervisedUserCreationFinished() = 0; // Map that is used to describe the set of active user sessions where |key| - // is user_id and |value| is user_id_hash. - typedef std::map<std::string, std::string> ActiveSessionsMap; + // is cryptohome id and |value| is user_id_hash. + using ActiveSessionsMap = std::map<cryptohome::Identification, std::string>; // The ActiveSessionsCallback is used for the RetrieveActiveSessions() - // method. It receives |sessions| argument where the keys are user_ids for - // all users that are currently active and |success| argument which indicates - // whether or not the request succeded. + // method. It receives |sessions| argument where the keys are cryptohome_ids + // for all users that are currently active and |success| argument which + // indicates whether or not the request succeded. typedef base::Callback<void(const ActiveSessionsMap& sessions, bool success)> ActiveSessionsCallback; // Enumerates active user sessions. Usually Chrome naturally keeps track of // active users when they are added into current session. When Chrome is - // restarted after crash by session_manager it only receives user_id and + // restarted after crash by session_manager it only receives cryptohome id and // user_id_hash for one user. This method is used to retrieve list of all // active users. virtual void RetrieveActiveSessions( @@ -131,10 +136,10 @@ virtual void RetrieveDevicePolicy(const RetrievePolicyCallback& callback) = 0; // Fetches the user policy blob stored by the session manager for the given - // |username|. Upon completion of the retrieve attempt, we will call the + // |cryptohome_id|. Upon completion of the retrieve attempt, we will call the // provided callback. virtual void RetrievePolicyForUser( - const std::string& username, + const cryptohome::Identification& cryptohome_id, const RetrievePolicyCallback& callback) = 0; // Same as RetrievePolicyForUser() but blocks until a reply is received, and @@ -144,7 +149,7 @@ // considered acceptable (e.g. restarting the browser after a crash or after // a flag change). virtual std::string BlockingRetrievePolicyForUser( - const std::string& username) = 0; + const cryptohome::Identification& cryptohome_id) = 0; // Fetches the policy blob associated with the specified device-local account // from session manager. |callback| is invoked up on completion. @@ -162,11 +167,13 @@ virtual void StoreDevicePolicy(const std::string& policy_blob, const StorePolicyCallback& callback) = 0; - // Attempts to asynchronously store |policy_blob| as user policy for the given - // |username|. Upon completion of the store attempt, we will call callback. - virtual void StorePolicyForUser(const std::string& username, - const std::string& policy_blob, - const StorePolicyCallback& callback) = 0; + // Attempts to asynchronously store |policy_blob| as user policy for the + // given |cryptohome_id|. Upon completion of the store attempt, we will call + // callback. + virtual void StorePolicyForUser( + const cryptohome::Identification& cryptohome_id, + const std::string& policy_blob, + const StorePolicyCallback& callback) = 0; // Sends a request to store a policy blob for the specified device-local // account. The result of the operation is reported through |callback|. @@ -177,7 +184,7 @@ // Sets the flags to be applied next time by the session manager when Chrome // is restarted inside an already started session for a particular user. - virtual void SetFlagsForUser(const std::string& username, + virtual void SetFlagsForUser(const cryptohome::Identification& cryptohome_id, const std::vector<std::string>& flags) = 0; typedef base::Callback<void(const std::vector<std::string>& state_keys)>
diff --git a/chromeos/login/auth/authenticator.h b/chromeos/login/auth/authenticator.h index 1f05bce..422cccd 100644 --- a/chromeos/login/auth/authenticator.h +++ b/chromeos/login/auth/authenticator.h
@@ -13,6 +13,8 @@ #include "chromeos/login/auth/auth_status_consumer.h" #include "google_apis/gaia/gaia_auth_consumer.h" +class AccountId; + namespace content { class BrowserContext; } @@ -56,11 +58,11 @@ // Initiates login into the public account identified by |user_context|. virtual void LoginAsPublicSession(const UserContext& user_context) = 0; - // Initiates login into kiosk mode account identified by |app_user_id|. - // The |app_user_id| is a generated username for the account. + // Initiates login into kiosk mode account identified by |app_account_id|. + // The |app_account_id| is a generated account id for the account. // |use_guest_mount| specifies whether to force the session to use a // guest mount. If this is false, we use mount a public cryptohome. - virtual void LoginAsKioskAccount(const std::string& app_user_id, + virtual void LoginAsKioskAccount(const AccountId& app_account_id, bool use_guest_mount) = 0; // Notifies caller that login was successful. Must be called on the UI thread.
diff --git a/chromeos/login/auth/cryptohome_authenticator.cc b/chromeos/login/auth/cryptohome_authenticator.cc index df430d08d..913af5d 100644 --- a/chromeos/login/auth/cryptohome_authenticator.cc +++ b/chromeos/login/auth/cryptohome_authenticator.cc
@@ -149,8 +149,7 @@ } cryptohome::HomedirMethods::GetInstance()->MountEx( - cryptohome::Identification( - attempt->user_context.GetAccountId().GetUserEmail()), + cryptohome::Identification(attempt->user_context.GetAccountId()), cryptohome::Authorization(auth_key), mount, base::Bind(&OnMount, attempt, resolver)); } @@ -267,8 +266,7 @@ } cryptohome::HomedirMethods::GetInstance()->GetKeyDataEx( - cryptohome::Identification( - attempt->user_context.GetAccountId().GetUserEmail()), + cryptohome::Identification(attempt->user_context.GetAccountId()), kCryptohomeGAIAKeyLabel, base::Bind(&OnGetKeyDataEx, attempt, resolver, ephemeral, create_if_nonexistent)); } @@ -284,7 +282,7 @@ attempt, resolver)); cryptohome::AsyncMethodCaller::GetInstance()->AsyncGetSanitizedUsername( - attempt->user_context.GetAccountId().GetUserEmail(), + cryptohome::Identification(attempt->user_context.GetAccountId()), base::Bind(&TriggerResolveHash, attempt, resolver)); } @@ -293,11 +291,11 @@ scoped_refptr<CryptohomeAuthenticator> resolver, int flags) { cryptohome::AsyncMethodCaller::GetInstance()->AsyncMountPublic( - attempt->user_context.GetAccountId().GetUserEmail(), flags, + cryptohome::Identification(attempt->user_context.GetAccountId()), flags, base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeMountPublic-End", attempt, resolver)); cryptohome::AsyncMethodCaller::GetInstance()->AsyncGetSanitizedUsername( - attempt->user_context.GetAccountId().GetUserEmail(), + cryptohome::Identification(attempt->user_context.GetAccountId()), base::Bind(&TriggerResolveHash, attempt, resolver)); } @@ -320,13 +318,13 @@ TransformKeyIfNeeded(*attempt->user_context.GetKey(), system_salt); if (passing_old_hash) { caller->AsyncMigrateKey( - attempt->user_context.GetAccountId().GetUserEmail(), + cryptohome::Identification(attempt->user_context.GetAccountId()), old_key->GetSecret(), new_key->GetSecret(), base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeMount-End", attempt, resolver)); } else { caller->AsyncMigrateKey( - attempt->user_context.GetAccountId().GetUserEmail(), + cryptohome::Identification(attempt->user_context.GetAccountId()), new_key->GetSecret(), old_key->GetSecret(), base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeMount-End", attempt, resolver)); @@ -339,7 +337,7 @@ chromeos::LoginEventRecorder::Get()->AddLoginTimeMarker( "CryptohomeRemove-Start", false); cryptohome::AsyncMethodCaller::GetInstance()->AsyncRemove( - attempt->user_context.GetAccountId().GetUserEmail(), + cryptohome::Identification(attempt->user_context.GetAccountId()), base::Bind(&TriggerResolveWithLoginTimeMarker, "CryptohomeRemove-End", attempt, resolver)); } @@ -351,8 +349,8 @@ scoped_ptr<Key> key = TransformKeyIfNeeded(*attempt->user_context.GetKey(), system_salt); cryptohome::AsyncMethodCaller::GetInstance()->AsyncCheckKey( - attempt->user_context.GetAccountId().GetUserEmail(), key->GetSecret(), - base::Bind(&TriggerResolve, attempt, resolver)); + cryptohome::Identification(attempt->user_context.GetAccountId()), + key->GetSecret(), base::Bind(&TriggerResolve, attempt, resolver)); } } // namespace @@ -447,12 +445,11 @@ void CryptohomeAuthenticator::LoginOffTheRecord() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - current_state_.reset( - new AuthAttemptState(UserContext(user_manager::USER_TYPE_GUEST, - login::GuestAccountId().GetUserEmail()), - false, // unlock - false, // online_complete - false)); // user_is_new + current_state_.reset(new AuthAttemptState( + UserContext(user_manager::USER_TYPE_GUEST, login::GuestAccountId()), + false, // unlock + false, // online_complete + false)); // user_is_new remove_user_data_on_failure_ = false; ephemeral_mount_attempted_ = true; MountGuestAndGetHash(current_state_->AsWeakPtr(), @@ -477,14 +474,14 @@ } void CryptohomeAuthenticator::LoginAsKioskAccount( - const std::string& app_user_id, + const AccountId& app_account_id, bool use_guest_mount) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); - const std::string user_id = - use_guest_mount ? login::GuestAccountId().GetUserEmail() : app_user_id; + const AccountId& account_id = + use_guest_mount ? login::GuestAccountId() : app_account_id; current_state_.reset(new AuthAttemptState( - UserContext(user_manager::USER_TYPE_KIOSK_APP, user_id), + UserContext(user_manager::USER_TYPE_KIOSK_APP, account_id), false, // unlock false, // online_complete false)); // user_is_new
diff --git a/chromeos/login/auth/cryptohome_authenticator.h b/chromeos/login/auth/cryptohome_authenticator.h index d767bd9..cfac3d3 100644 --- a/chromeos/login/auth/cryptohome_authenticator.h +++ b/chromeos/login/auth/cryptohome_authenticator.h
@@ -129,12 +129,12 @@ // success/failure. void LoginAsPublicSession(const UserContext& user_context) override; - // Initiates login into the kiosk mode account identified by |app_user_id|. + // Initiates login into the kiosk mode account identified by |app_account_id|. // Mounts an ephemeral guest cryptohome if |use_guest_mount| is |true|. // Otherwise, mounts a public cryptohome, which will be ephemeral if the // |DeviceEphemeralUsersEnabled| policy is enabled and non-ephemeral // otherwise. - void LoginAsKioskAccount(const std::string& app_user_id, + void LoginAsKioskAccount(const AccountId& app_account_id, bool use_guest_mount) override; // These methods must be called on the UI thread, as they make DBus calls
diff --git a/chromeos/login/auth/extended_authenticator.h b/chromeos/login/auth/extended_authenticator.h index deaa6c4..0a0a877 100644 --- a/chromeos/login/auth/extended_authenticator.h +++ b/chromeos/login/auth/extended_authenticator.h
@@ -15,6 +15,8 @@ #include "chromeos/chromeos_export.h" #include "chromeos/cryptohome/cryptohome_parameters.h" +class AccountId; + namespace chromeos { class AuthStatusConsumer; @@ -68,12 +70,13 @@ virtual void AuthenticateToCheck(const UserContext& context, const base::Closure& success_callback) = 0; - // This call will create and mount the home dir for |user_id| with the given - // |keys| if the home dir is missing. If the home dir exists already, a mount - // attempt will be performed using the first key in |keys| for authentication. - // Note that all |keys| should have been transformed from plain text already. + // This call will create and mount the home dir for |account_id| with the + // given |keys| if the home dir is missing. If the home dir exists already, a + // mount attempt will be performed using the first key in |keys| for + // authentication. Note that all |keys| should have been transformed from + // plain text already. // This method does not alter them. - virtual void CreateMount(const std::string& user_id, + virtual void CreateMount(const AccountId& account_id, const std::vector<cryptohome::KeyDefinition>& keys, const ResultCallback& success_callback) = 0;
diff --git a/chromeos/login/auth/extended_authenticator_impl.cc b/chromeos/login/auth/extended_authenticator_impl.cc index 25d95207..98ec0b9 100644 --- a/chromeos/login/auth/extended_authenticator_impl.cc +++ b/chromeos/login/auth/extended_authenticator_impl.cc
@@ -82,19 +82,18 @@ } void ExtendedAuthenticatorImpl::CreateMount( - const std::string& user_id, + const AccountId& account_id, const std::vector<cryptohome::KeyDefinition>& keys, const ResultCallback& success_callback) { RecordStartMarker("MountEx"); - std::string canonicalized = gaia::CanonicalizeEmail(user_id); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(account_id); cryptohome::Authorization auth(keys.front()); cryptohome::MountParameters mount(false); for (size_t i = 0; i < keys.size(); i++) { mount.create_keys.push_back(keys[i]); } - UserContext context(AccountId::FromUserEmail(user_id)); + UserContext context(account_id); Key key(keys.front().secret); key.SetLabel(keys.front().label); context.SetKey(key); @@ -189,9 +188,7 @@ const UserContext& user_context) { RecordStartMarker("MountEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(user_context.GetAccountId()); const Key* const key = user_context.GetKey(); cryptohome::Authorization auth(key->GetSecret(), key->GetLabel()); cryptohome::MountParameters mount(false); @@ -212,9 +209,7 @@ const UserContext& user_context) { RecordStartMarker("CheckKeyEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(user_context.GetAccountId()); const Key* const key = user_context.GetKey(); cryptohome::Authorization auth(key->GetSecret(), key->GetLabel()); @@ -234,9 +229,7 @@ const UserContext& user_context) { RecordStartMarker("AddKeyEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(user_context.GetAccountId()); const Key* const auth_key = user_context.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel()); @@ -259,9 +252,7 @@ const UserContext& user_context) { RecordStartMarker("UpdateKeyAuthorized"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(user_context.GetAccountId()); const Key* const auth_key = user_context.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel()); @@ -282,9 +273,7 @@ const UserContext& user_context) { RecordStartMarker("RemoveKeyEx"); - const std::string canonicalized = - gaia::CanonicalizeEmail(user_context.GetAccountId().GetUserEmail()); - cryptohome::Identification id(canonicalized); + cryptohome::Identification id(user_context.GetAccountId()); const Key* const auth_key = user_context.GetKey(); cryptohome::Authorization auth(auth_key->GetSecret(), auth_key->GetLabel());
diff --git a/chromeos/login/auth/extended_authenticator_impl.h b/chromeos/login/auth/extended_authenticator_impl.h index a292e9e..550ba3f 100644 --- a/chromeos/login/auth/extended_authenticator_impl.h +++ b/chromeos/login/auth/extended_authenticator_impl.h
@@ -15,6 +15,8 @@ #include "chromeos/login/auth/extended_authenticator.h" #include "third_party/cros_system_api/dbus/service_constants.h" +class AccountId; + namespace chromeos { class AuthStatusConsumer; @@ -32,7 +34,7 @@ const ResultCallback& success_callback) override; void AuthenticateToCheck(const UserContext& context, const base::Closure& success_callback) override; - void CreateMount(const std::string& user_id, + void CreateMount(const AccountId& account_id, const std::vector<cryptohome::KeyDefinition>& keys, const ResultCallback& success_callback) override; void AddKey(const UserContext& context,
diff --git a/chromeos/login/auth/fake_extended_authenticator.cc b/chromeos/login/auth/fake_extended_authenticator.cc index e57755b9..b44255b 100644 --- a/chromeos/login/auth/fake_extended_authenticator.cc +++ b/chromeos/login/auth/fake_extended_authenticator.cc
@@ -65,9 +65,10 @@ AuthFailure(AuthFailure::UNLOCK_FAILED)); } -void FakeExtendedAuthenticator::CreateMount(const std::string& user_id, - const std::vector<cryptohome::KeyDefinition>& keys, - const ResultCallback& success_callback) { +void FakeExtendedAuthenticator::CreateMount( + const AccountId& account_id, + const std::vector<cryptohome::KeyDefinition>& keys, + const ResultCallback& success_callback) { NOTREACHED(); }
diff --git a/chromeos/login/auth/fake_extended_authenticator.h b/chromeos/login/auth/fake_extended_authenticator.h index 96dc4f4..ee48944 100644 --- a/chromeos/login/auth/fake_extended_authenticator.h +++ b/chromeos/login/auth/fake_extended_authenticator.h
@@ -10,6 +10,8 @@ #include "chromeos/login/auth/extended_authenticator.h" #include "chromeos/login/auth/user_context.h" +class AccountId; + namespace chromeos { class AuthFailure; @@ -27,7 +29,7 @@ const ResultCallback& success_callback) override; void AuthenticateToCheck(const UserContext& context, const base::Closure& success_callback) override; - void CreateMount(const std::string& user_id, + void CreateMount(const AccountId& account_id, const std::vector<cryptohome::KeyDefinition>& keys, const ResultCallback& success_callback) override; void AddKey(const UserContext& context,
diff --git a/chromeos/login/auth/login_performer.cc b/chromeos/login/auth/login_performer.cc index b358105..6d949f4 100644 --- a/chromeos/login/auth/login_performer.cc +++ b/chromeos/login/auth/login_performer.cc
@@ -228,14 +228,13 @@ base::Bind(&Authenticator::LoginOffTheRecord, authenticator_.get())); } -void LoginPerformer::LoginAsKioskAccount(const std::string& app_user_id, +void LoginPerformer::LoginAsKioskAccount(const AccountId& app_account_id, bool use_guest_mount) { EnsureAuthenticator(); - task_runner_->PostTask(FROM_HERE, - base::Bind(&Authenticator::LoginAsKioskAccount, - authenticator_.get(), - app_user_id, - use_guest_mount)); + task_runner_->PostTask( + FROM_HERE, + base::Bind(&Authenticator::LoginAsKioskAccount, authenticator_.get(), + app_account_id, use_guest_mount)); } void LoginPerformer::RecoverEncryptedData(const std::string& old_password) {
diff --git a/chromeos/login/auth/login_performer.h b/chromeos/login/auth/login_performer.h index 915ee35..3eb2c4f6 100644 --- a/chromeos/login/auth/login_performer.h +++ b/chromeos/login/auth/login_performer.h
@@ -79,8 +79,8 @@ // Performs public session login with a given |user_context|. void LoginAsPublicSession(const UserContext& user_context); - // Performs a login into the kiosk mode account with |app_user_id|. - void LoginAsKioskAccount(const std::string& app_user_id, + // Performs a login into the kiosk mode account with |app_account_id|. + void LoginAsKioskAccount(const AccountId& app_account_id, bool use_guest_mount); // AuthStatusConsumer implementation:
diff --git a/chromeos/login/auth/stub_authenticator.cc b/chromeos/login/auth/stub_authenticator.cc index 371453d8..d48d5964 100644 --- a/chromeos/login/auth/stub_authenticator.cc +++ b/chromeos/login/auth/stub_authenticator.cc
@@ -75,7 +75,7 @@ } void StubAuthenticator::LoginAsKioskAccount( - const std::string& /* app_user_id */, + const AccountId& /* app_account_id */, bool use_guest_mount) { UserContext user_context(expected_user_context_.GetAccountId()); user_context.SetIsUsingOAuth(false);
diff --git a/chromeos/login/auth/stub_authenticator.h b/chromeos/login/auth/stub_authenticator.h index 8c67874..10f9775 100644 --- a/chromeos/login/auth/stub_authenticator.h +++ b/chromeos/login/auth/stub_authenticator.h
@@ -13,6 +13,8 @@ #include "chromeos/login/auth/authenticator.h" #include "chromeos/login/auth/user_context.h" +class AccountId; + namespace content { class BrowserContext; } @@ -35,7 +37,7 @@ void LoginAsSupervisedUser(const UserContext& user_context) override; void LoginOffTheRecord() override; void LoginAsPublicSession(const UserContext& user_context) override; - void LoginAsKioskAccount(const std::string& app_user_id, + void LoginAsKioskAccount(const AccountId& app_account_id, bool use_guest_mount) override; void OnAuthSuccess() override; void OnAuthFailure(const AuthFailure& failure) override;
diff --git a/chromeos/login/auth/user_context.cc b/chromeos/login/auth/user_context.cc index 0060e3c4..7eed5e0 100644 --- a/chromeos/login/auth/user_context.cc +++ b/chromeos/login/auth/user_context.cc
@@ -11,7 +11,6 @@ UserContext::UserContext(const UserContext& other) : account_id_(other.account_id_), - gaia_id_(other.gaia_id_), key_(other.key_), auth_code_(other.auth_code_), refresh_token_(other.refresh_token_), @@ -32,20 +31,19 @@ } UserContext::UserContext(user_manager::UserType user_type, - const std::string& user_id) - : account_id_(EmptyAccountId()), user_type_(user_type) { + const AccountId& account_id) + : account_id_(account_id), user_type_(user_type) { if (user_type_ == user_manager::USER_TYPE_REGULAR) - account_id_ = AccountId::FromUserEmail(login::CanonicalizeUserID(user_id)); - else - account_id_ = AccountId::FromUserEmail(user_id); + account_id_.SetUserEmail( + login::CanonicalizeUserID(account_id_.GetUserEmail())); } UserContext::~UserContext() { } bool UserContext::operator==(const UserContext& context) const { - return context.account_id_ == account_id_ && context.gaia_id_ == gaia_id_ && - context.key_ == key_ && context.auth_code_ == auth_code_ && + return context.account_id_ == account_id_ && context.key_ == key_ && + context.auth_code_ == auth_code_ && context.refresh_token_ == refresh_token_ && context.access_token_ == access_token_ && context.user_id_hash_ == user_id_hash_ && @@ -64,7 +62,7 @@ } const std::string& UserContext::GetGaiaID() const { - return gaia_id_; + return account_id_.GetGaiaId(); } const Key* UserContext::GetKey() const { @@ -124,12 +122,8 @@ !auth_code_.empty(); } -void UserContext::SetUserID(const std::string& user_id) { - account_id_ = AccountId::FromUserEmail(login::CanonicalizeUserID(user_id)); -} - -void UserContext::SetGaiaID(const std::string& gaia_id) { - gaia_id_ = gaia_id; +void UserContext::SetAccountId(const AccountId& account_id) { + account_id_ = account_id; } void UserContext::SetKey(const Key& key) {
diff --git a/chromeos/login/auth/user_context.h b/chromeos/login/auth/user_context.h index a4440cc..6f29645a 100644 --- a/chromeos/login/auth/user_context.h +++ b/chromeos/login/auth/user_context.h
@@ -40,7 +40,7 @@ UserContext(); UserContext(const UserContext& other); explicit UserContext(const AccountId& account_id); - UserContext(user_manager::UserType user_type, const std::string& user_id); + UserContext(user_manager::UserType user_type, const AccountId& account_id); ~UserContext(); bool operator==(const UserContext& context) const; @@ -64,8 +64,7 @@ bool HasCredentials() const; - void SetUserID(const std::string& user_id); - void SetGaiaID(const std::string& gaia_id); + void SetAccountId(const AccountId& account_id); void SetKey(const Key& key); void SetAuthCode(const std::string& auth_code); void SetRefreshToken(const std::string& refresh_token); @@ -83,7 +82,6 @@ private: AccountId account_id_; - std::string gaia_id_; Key key_; std::string auth_code_; std::string refresh_token_;
diff --git a/chromeos/tpm/tpm_token_info_getter.cc b/chromeos/tpm/tpm_token_info_getter.cc index e51392f..31a3089 100644 --- a/chromeos/tpm/tpm_token_info_getter.cc +++ b/chromeos/tpm/tpm_token_info_getter.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/location.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/cryptohome_client.h" namespace { @@ -43,22 +44,20 @@ // static scoped_ptr<TPMTokenInfoGetter> TPMTokenInfoGetter::CreateForUserToken( - const std::string& user_id, + const AccountId& account_id, CryptohomeClient* cryptohome_client, const scoped_refptr<base::TaskRunner>& delayed_task_runner) { - CHECK(!user_id.empty()); - return scoped_ptr<TPMTokenInfoGetter>( - new TPMTokenInfoGetter( - TYPE_USER, user_id, cryptohome_client, delayed_task_runner)); + CHECK(account_id.is_valid()); + return scoped_ptr<TPMTokenInfoGetter>(new TPMTokenInfoGetter( + TYPE_USER, account_id, cryptohome_client, delayed_task_runner)); } // static scoped_ptr<TPMTokenInfoGetter> TPMTokenInfoGetter::CreateForSystemToken( CryptohomeClient* cryptohome_client, const scoped_refptr<base::TaskRunner>& delayed_task_runner) { - return scoped_ptr<TPMTokenInfoGetter>( - new TPMTokenInfoGetter( - TYPE_SYSTEM, std::string(), cryptohome_client, delayed_task_runner)); + return scoped_ptr<TPMTokenInfoGetter>(new TPMTokenInfoGetter( + TYPE_SYSTEM, EmptyAccountId(), cryptohome_client, delayed_task_runner)); } TPMTokenInfoGetter::~TPMTokenInfoGetter() {} @@ -75,18 +74,17 @@ TPMTokenInfoGetter::TPMTokenInfoGetter( TPMTokenInfoGetter::Type type, - const std::string& user_id, + const AccountId& account_id, CryptohomeClient* cryptohome_client, const scoped_refptr<base::TaskRunner>& delayed_task_runner) : delayed_task_runner_(delayed_task_runner), type_(type), state_(TPMTokenInfoGetter::STATE_INITIAL), - user_id_(user_id), + account_id_(account_id), tpm_request_delay_( base::TimeDelta::FromMilliseconds(kInitialRequestDelayMs)), cryptohome_client_(cryptohome_client), - weak_factory_(this) { -} + weak_factory_(this) {} void TPMTokenInfoGetter::Continue() { switch (state_) { @@ -105,9 +103,9 @@ weak_factory_.GetWeakPtr())); } else { // if (type_ == TYPE_USER) cryptohome_client_->Pkcs11GetTpmTokenInfoForUser( - user_id_, - base::Bind(&TPMTokenInfoGetter::OnPkcs11GetTpmTokenInfo, - weak_factory_.GetWeakPtr())); + cryptohome::Identification(account_id_), + base::Bind(&TPMTokenInfoGetter::OnPkcs11GetTpmTokenInfo, + weak_factory_.GetWeakPtr())); } break; case STATE_DONE:
diff --git a/chromeos/tpm/tpm_token_info_getter.h b/chromeos/tpm/tpm_token_info_getter.h index 1612dc5f..964c831 100644 --- a/chromeos/tpm/tpm_token_info_getter.h +++ b/chromeos/tpm/tpm_token_info_getter.h
@@ -14,6 +14,7 @@ #include "base/time/time.h" #include "chromeos/chromeos_export.h" #include "chromeos/dbus/dbus_method_call_status.h" +#include "components/signin/core/account_id/account_id.h" namespace base { class TaskRunner; @@ -47,7 +48,7 @@ // Factory method for TPMTokenInfoGetter for a user token. static scoped_ptr<TPMTokenInfoGetter> CreateForUserToken( - const std::string& user_id, + const AccountId& account_id, CryptohomeClient* cryptohome_client, const scoped_refptr<base::TaskRunner>& delayed_task_runner); @@ -80,7 +81,7 @@ TPMTokenInfoGetter( Type type, - const std::string& user_id, + const AccountId& account_id, CryptohomeClient* cryptohome_client, const scoped_refptr<base::TaskRunner>& delayed_task_runner); @@ -107,8 +108,9 @@ Type type_; State state_; - // The user id associated with the TPMTokenInfoGetter. Empty for system token. - std::string user_id_; + // The account id associated with the TPMTokenInfoGetter. Empty for system + // token. + AccountId account_id_; TPMTokenInfoCallback callback_;
diff --git a/chromeos/tpm/tpm_token_info_getter_unittest.cc b/chromeos/tpm/tpm_token_info_getter_unittest.cc index 013c22ab..5bdfa6f 100644 --- a/chromeos/tpm/tpm_token_info_getter_unittest.cc +++ b/chromeos/tpm/tpm_token_info_getter_unittest.cc
@@ -15,6 +15,7 @@ #include "base/single_thread_task_runner.h" #include "base/task_runner.h" #include "base/thread_task_runner_handle.h" +#include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/tpm/tpm_token_info_getter.h" #include "testing/gtest/include/gtest/gtest.h" @@ -84,17 +85,16 @@ // TPMTokenInfoGetter tests. class TestCryptohomeClient : public chromeos::FakeCryptohomeClient { public: - // |user_id|: The user associated with the TPMTokenInfoGetter that will be + // |account_id|: The user associated with the TPMTokenInfoGetter that will be // using the TestCryptohomeClient. Should be empty for system token. - explicit TestCryptohomeClient(const std::string& user_id) - : user_id_(user_id), + explicit TestCryptohomeClient(const AccountId& account_id) + : account_id_(account_id), tpm_is_enabled_(true), tpm_is_enabled_failure_count_(0), tpm_is_enabled_succeeded_(false), get_tpm_token_info_failure_count_(0), get_tpm_token_info_not_set_count_(0), - get_tpm_token_info_succeeded_(false) { - } + get_tpm_token_info_succeeded_(false) {} ~TestCryptohomeClient() override {} @@ -152,22 +152,22 @@ void Pkcs11GetTpmTokenInfo( const Pkcs11GetTpmTokenInfoCallback& callback) override { - ASSERT_TRUE(user_id_.empty()); + ASSERT_TRUE(account_id_.empty()); HandleGetTpmTokenInfo(callback); } void Pkcs11GetTpmTokenInfoForUser( - const std::string& user_id, + const cryptohome::Identification& cryptohome_id, const Pkcs11GetTpmTokenInfoCallback& callback) override { - ASSERT_FALSE(user_id_.empty()); - ASSERT_EQ(user_id_, user_id); + ASSERT_FALSE(cryptohome_id.id().empty()); + ASSERT_EQ(account_id_, cryptohome_id.GetAccountId()); HandleGetTpmTokenInfo(callback); } // Handles Pkcs11GetTpmTokenInfo calls (both for system and user token). The - // CryptohomeClient method overrides should make sure that |user_id_| is + // CryptohomeClient method overrides should make sure that |account_id_| is // properly set before calling this. void HandleGetTpmTokenInfo(const Pkcs11GetTpmTokenInfoCallback& callback) { ASSERT_TRUE(tpm_is_enabled_succeeded_); @@ -218,7 +218,7 @@ tpm_token_info_.slot_id); } - std::string user_id_; + AccountId account_id_; bool tpm_is_enabled_; int tpm_is_enabled_failure_count_; bool tpm_is_enabled_succeeded_; @@ -237,7 +237,7 @@ ~SystemTPMTokenInfoGetterTest() override {} void SetUp() override { - cryptohome_client_.reset(new TestCryptohomeClient(std::string())); + cryptohome_client_.reset(new TestCryptohomeClient(EmptyAccountId())); tpm_token_info_getter_ = chromeos::TPMTokenInfoGetter::CreateForSystemToken( cryptohome_client_.get(), @@ -258,23 +258,22 @@ class UserTPMTokenInfoGetterTest : public testing::Test { public: - UserTPMTokenInfoGetterTest() : user_id_("user") {} + UserTPMTokenInfoGetterTest() + : account_id_(AccountId::FromUserEmail("user")) {} ~UserTPMTokenInfoGetterTest() override {} void SetUp() override { - cryptohome_client_.reset(new TestCryptohomeClient(user_id_)); - tpm_token_info_getter_ = - chromeos::TPMTokenInfoGetter::CreateForUserToken( - user_id_, - cryptohome_client_.get(), - scoped_refptr<base::TaskRunner>(new FakeTaskRunner(&delays_))); + cryptohome_client_.reset(new TestCryptohomeClient(account_id_)); + tpm_token_info_getter_ = chromeos::TPMTokenInfoGetter::CreateForUserToken( + account_id_, cryptohome_client_.get(), + scoped_refptr<base::TaskRunner>(new FakeTaskRunner(&delays_))); } protected: scoped_ptr<TestCryptohomeClient> cryptohome_client_; scoped_ptr<chromeos::TPMTokenInfoGetter> tpm_token_info_getter_; - std::string user_id_; + const AccountId account_id_; std::vector<int64_t> delays_; private:
diff --git a/components/BUILD.gn b/components/BUILD.gn index bceb9aa..7e991817 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -69,7 +69,7 @@ "//components/variations:unit_tests", "//components/variations/service:unit_tests", "//components/web_resource:unit_tests", - "//mojo/edk/embedder:headers", + "//mojo/edk/system", "//net", "//testing/gtest", "//ui/base",
diff --git a/components/autofill/core/browser/credit_card_field.cc b/components/autofill/core/browser/credit_card_field.cc index 2fa9f658..d268b73 100644 --- a/components/autofill/core/browser/credit_card_field.cc +++ b/components/autofill/core/browser/credit_card_field.cc
@@ -146,10 +146,11 @@ continue; } + // TODO(crbug.com/591816): Make sure parsing cc-numbers of type password + // doesn't have bad side effects. AutofillField* current_number_field; - if (ParseFieldSpecifics(scanner, - base::UTF8ToUTF16(kCardNumberRe), - kMatchNumAndTel, + if (ParseFieldSpecifics(scanner, base::UTF8ToUTF16(kCardNumberRe), + kMatchNumAndTel | MATCH_PASSWORD, ¤t_number_field)) { // Avoid autofilling any credit card number field having very low or high // |start_index| on the HTML form.
diff --git a/components/components_tests.gyp b/components/components_tests.gyp index 6b1b3a74..f2675b1 100644 --- a/components/components_tests.gyp +++ b/components/components_tests.gyp
@@ -746,6 +746,7 @@ 'sync_driver/about_sync_util_unittest.cc', 'sync_driver/backend_migrator_unittest.cc', 'sync_driver/data_type_manager_impl_unittest.cc', + 'sync_driver/device_count_metrics_provider_unittest.cc', 'sync_driver/device_info_data_type_controller_unittest.cc', 'sync_driver/device_info_service_unittest.cc', 'sync_driver/device_info_sync_service_unittest.cc',
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc index c60fd70..26bc2db 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.cc
@@ -372,7 +372,6 @@ net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); WritePrefs(); - pref_change_registrar_.RemoveAll(); } void DataReductionProxyCompressionStats::Init() { @@ -447,21 +446,6 @@ switches::kClearDataReductionProxyDataSavings)) { ClearDataSavingStatistics(); } - - pref_change_registrar_.Init(pref_service_); - pref_change_registrar_.Add( - prefs::kUpdateDailyReceivedContentLengths, - base::Bind(&DataReductionProxyCompressionStats::OnUpdateContentLengths, - weak_factory_.GetWeakPtr())); -} - -void DataReductionProxyCompressionStats::OnUpdateContentLengths() { - DCHECK(thread_checker_.CalledOnValidThread()); - if (!pref_service_->GetBoolean(prefs::kUpdateDailyReceivedContentLengths)) - return; - - WritePrefs(); - pref_service_->SetBoolean(prefs::kUpdateDailyReceivedContentLengths, false); } void DataReductionProxyCompressionStats::UpdateContentLengths(
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h index 59eca58c..d3dfc73 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h
@@ -13,7 +13,6 @@ #include "base/containers/scoped_ptr_hash_map.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" @@ -23,7 +22,6 @@ #include "components/data_reduction_proxy/core/browser/db_data_owner.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h" #include "components/data_reduction_proxy/proto/data_store.pb.h" -#include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_member.h" #include "net/base/network_change_notifier.h" @@ -237,7 +235,6 @@ const base::TimeDelta delay_; DataReductionProxyPrefMap pref_map_; DataReductionProxyListPrefMap list_pref_map_; - PrefChangeRegistrar pref_change_registrar_; BooleanPrefMember data_usage_reporting_enabled_; ConnectionType connection_type_;
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc index d4604af..6906d2e 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats_unittest.cc
@@ -498,21 +498,6 @@ } TEST_F(DataReductionProxyCompressionStatsTest, - WritePrefsOnUpdateDailyReceivedContentLengths) { - ResetCompressionStatsWithDelay( - base::TimeDelta::FromMinutes(kWriteDelayMinutes)); - SetUpPrefs(); - - pref_service()->SetBoolean( - prefs::kUpdateDailyReceivedContentLengths, true); - - VerifyPrefWasWritten(prefs::kHttpOriginalContentLength); - VerifyPrefWasWritten(prefs::kHttpReceivedContentLength); - VerifyPrefListWasWritten(prefs::kDailyHttpOriginalContentLength); - VerifyPrefListWasWritten(prefs::kDailyHttpReceivedContentLength); -} - -TEST_F(DataReductionProxyCompressionStatsTest, HistoricNetworkStatsInfoToValue) { const int64_t kOriginalLength = 150; const int64_t kReceivedLength = 100;
diff --git a/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.cc b/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.cc index cb51e34..71af0f3 100644 --- a/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.cc +++ b/components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.cc
@@ -39,8 +39,6 @@ registry->RegisterInt64Pref(prefs::kHttpOriginalContentLength, 0); registry->RegisterBooleanPref(prefs::kStatisticsPrefsMigrated, false); - registry->RegisterBooleanPref(prefs::kUpdateDailyReceivedContentLengths, - false); registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength); registry->RegisterInt64Pref(prefs::kDailyHttpOriginalContentLengthApplication, 0L); @@ -140,8 +138,6 @@ registry->RegisterInt64Pref(prefs::kDailyHttpReceivedContentLengthVideo, 0L); registry->RegisterInt64Pref(prefs::kDailyHttpReceivedContentLengthUnknown, 0L); - registry->RegisterBooleanPref(prefs::kUpdateDailyReceivedContentLengths, - false); registry->RegisterListPref( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled); registry->RegisterInt64Pref(
diff --git a/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.cc b/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.cc index db8f181..b2c01d19 100644 --- a/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.cc +++ b/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.cc
@@ -230,12 +230,5 @@ const char kStatisticsPrefsMigrated[] = "data_reduction.statistics_prefs_migrated"; -// Pref to indicate that the kDailyHttpOriginalContentLength and -// kDailyHttpReceivedContentLength prefs must be updated with their latest -// value. These values are cached in memory on platforms other than Android and -// iOS for performance reasons. -const char kUpdateDailyReceivedContentLengths[] = - "data_reduction.update_daily_lengths"; - } // namespace prefs } // namespace data_reduction_proxy
diff --git a/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h b/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h index d358f04b..d830a94b 100644 --- a/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h +++ b/components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h
@@ -56,7 +56,6 @@ extern const char kLoFiWasUsedThisSession[]; extern const char kSimulatedConfigRetrieveTime[]; extern const char kStatisticsPrefsMigrated[]; -extern const char kUpdateDailyReceivedContentLengths[]; } // namespace prefs } // namespace data_reduction_proxy
diff --git a/components/exo/buffer.cc b/components/exo/buffer.cc index 86c04a23..d2b3031 100644 --- a/components/exo/buffer.cc +++ b/components/exo/buffer.cc
@@ -346,16 +346,19 @@ texture_target_(GL_TEXTURE_2D), query_type_(GL_COMMANDS_COMPLETED_CHROMIUM), use_zero_copy_(true), + is_overlay_candidate_(false), use_count_(0) {} Buffer::Buffer(scoped_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer, unsigned texture_target, unsigned query_type, - bool use_zero_copy) + bool use_zero_copy, + bool is_overlay_candidate) : gpu_memory_buffer_(std::move(gpu_memory_buffer)), texture_target_(texture_target), query_type_(query_type), use_zero_copy_(use_zero_copy), + is_overlay_candidate_(is_overlay_candidate), use_count_(0) {} Buffer::~Buffer() {} @@ -412,11 +415,9 @@ // This binds the latest contents of this buffer to |texture|. gpu::SyncToken sync_token = texture->BindTexImage(); - // TODO(reveman): Set to true when GMBs can be imported for SCANOUT. - bool is_overlay_candidate = false; - *texture_mailbox = - cc::TextureMailbox(texture->mailbox(), sync_token, texture_target_, - gpu_memory_buffer_->GetSize(), is_overlay_candidate); + *texture_mailbox = cc::TextureMailbox( + texture->mailbox(), sync_token, texture_target_, + gpu_memory_buffer_->GetSize(), is_overlay_candidate_); // The contents texture will be released when no longer used by the // compositor. return cc::SingleReleaseCallback::Create( @@ -440,7 +441,7 @@ base::Passed(&contents_texture_))); *texture_mailbox = cc::TextureMailbox( texture->mailbox(), sync_token, GL_TEXTURE_2D, - gpu_memory_buffer_->GetSize(), false /* is_overlay_candidate*/); + gpu_memory_buffer_->GetSize(), false /* is_overlay_candidate */); // The mailbox texture will be released when no longer used by the // compositor. return cc::SingleReleaseCallback::Create(
diff --git a/components/exo/buffer.h b/components/exo/buffer.h index 84e744ea..c5f5c636 100644 --- a/components/exo/buffer.h +++ b/components/exo/buffer.h
@@ -41,7 +41,8 @@ Buffer(scoped_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer, unsigned texture_target, unsigned query_type, - bool use_zero_copy); + bool use_zero_copy, + bool is_overlay_candidate); ~Buffer(); // Set the callback to run when the buffer is no longer used by the @@ -93,6 +94,9 @@ // True if zero copy is used when producing a texture mailbox for buffer. const bool use_zero_copy_; + // True if this buffer is an overlay candidate. + const bool is_overlay_candidate_; + // This is incremented when a texture mailbox is produced and decremented // when a texture mailbox is released. It is used to determine when we should // notify the client that buffer has been released.
diff --git a/components/exo/display.cc b/components/exo/display.cc index 4d3bafc..f411252 100644 --- a/components/exo/display.cc +++ b/components/exo/display.cc
@@ -4,6 +4,7 @@ #include "components/exo/display.h" +#include <iterator> #include <utility> #include "base/trace_event/trace_event.h" @@ -74,10 +75,17 @@ // Using zero-copy for optimal performance. bool use_zero_copy = true; - return make_scoped_ptr( - new Buffer(std::move(gpu_memory_buffer), GL_TEXTURE_EXTERNAL_OES, - // COMMANDS_COMPLETED queries are required by native pixmaps. - GL_COMMANDS_COMPLETED_CHROMIUM, use_zero_copy)); + // List of overlay formats that are known to be supported. + // TODO(reveman): Determine this at runtime. + const gfx::BufferFormat kOverlayFormats[] = {gfx::BufferFormat::BGRX_8888}; + bool is_overlay_candidate = + std::find(std::begin(kOverlayFormats), std::end(kOverlayFormats), + format) != std::end(kOverlayFormats); + + return make_scoped_ptr(new Buffer( + std::move(gpu_memory_buffer), GL_TEXTURE_EXTERNAL_OES, + // COMMANDS_COMPLETED queries are required by native pixmaps. + GL_COMMANDS_COMPLETED_CHROMIUM, use_zero_copy, is_overlay_candidate)); } #endif
diff --git a/components/exo/shared_memory.cc b/components/exo/shared_memory.cc index 07f8269..d169f1a 100644 --- a/components/exo/shared_memory.cc +++ b/components/exo/shared_memory.cc
@@ -88,7 +88,8 @@ // buffers as binding to texture is implemented using a call to // glTexImage2D and the buffer can be reused as soon as that // command has been issued. - GL_COMMANDS_ISSUED_CHROMIUM, use_zero_copy)); + GL_COMMANDS_ISSUED_CHROMIUM, use_zero_copy, + false /* is_overlay_candidate */)); } } // namespace exo
diff --git a/components/filesystem/file_system_app.cc b/components/filesystem/file_system_app.cc index 8bb5354..e4620ba8 100644 --- a/components/filesystem/file_system_app.cc +++ b/components/filesystem/file_system_app.cc
@@ -39,7 +39,8 @@ void FileSystemApp::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); }
diff --git a/components/filesystem/file_system_app.h b/components/filesystem/file_system_app.h index f71eae98..9a5983cb 100644 --- a/components/filesystem/file_system_app.h +++ b/components/filesystem/file_system_app.h
@@ -32,7 +32,7 @@ // |mojo::ShellClient| override: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // |InterfaceFactory<Files>| implementation:
diff --git a/components/font_service/font_service_app.cc b/components/font_service/font_service_app.cc index d599b092..d0c0c1c5 100644 --- a/components/font_service/font_service_app.cc +++ b/components/font_service/font_service_app.cc
@@ -60,7 +60,7 @@ void FontServiceApp::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, uint32_t id) { tracing_.Initialize(connector, url); }
diff --git a/components/font_service/font_service_app.h b/components/font_service/font_service_app.h index 71d29cc..52b1f03 100644 --- a/components/font_service/font_service_app.h +++ b/components/font_service/font_service_app.h
@@ -28,7 +28,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // mojo::InterfaceFactory<FontService>:
diff --git a/components/leveldb/leveldb_app.cc b/components/leveldb/leveldb_app.cc index 952d4f3..3dfd509d 100644 --- a/components/leveldb/leveldb_app.cc +++ b/components/leveldb/leveldb_app.cc
@@ -15,8 +15,8 @@ void LevelDBApp::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); service_.reset(new LevelDBServiceImpl); }
diff --git a/components/leveldb/leveldb_app.h b/components/leveldb/leveldb_app.h index d9877d9..886f349 100644 --- a/components/leveldb/leveldb_app.h +++ b/components/leveldb/leveldb_app.h
@@ -23,8 +23,8 @@ // |ShellClient| override: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) override; + const std::string& user_id, + uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // TODO(erg): What do we have to do on shell error?
diff --git a/components/message_port.gypi b/components/message_port.gypi index 4acee9c8..be03075 100644 --- a/components/message_port.gypi +++ b/components/message_port.gypi
@@ -10,7 +10,7 @@ 'dependencies': [ '../base/base.gyp:base', '../mojo/mojo_public.gyp:mojo_message_pump_lib', - '../mojo/mojo_public.gyp:mojo_system_cpp_headers', + '../mojo/mojo_public.gyp:mojo_cpp_system', '../third_party/WebKit/public/blink.gyp:blink', ], 'include_dirs': [
diff --git a/components/mus/BUILD.gn b/components/mus/BUILD.gn index b29f28e6..5891ffa9 100644 --- a/components/mus/BUILD.gn +++ b/components/mus/BUILD.gn
@@ -75,6 +75,9 @@ "mus_app.h", ] + public_deps = [ + "//components/mus/common:mus_common", + ] deps = [ ":resources_100", ":resources_200", @@ -82,7 +85,6 @@ "//base", "//cc", "//cc/surfaces", - "//components/mus/common", "//components/mus/gles2", "//components/mus/public/interfaces", "//components/mus/surfaces", @@ -103,9 +105,7 @@ if (use_x11) { public_configs = [ "//build/config/linux:x11" ] - public_deps = [ - "//ui/events/platform/x11", - ] + public_deps += [ "//ui/events/platform/x11" ] } if (use_ozone) {
diff --git a/components/mus/DEPS b/components/mus/DEPS index 05f5c20..9ccd854 100644 --- a/components/mus/DEPS +++ b/components/mus/DEPS
@@ -2,7 +2,7 @@ "+cc", "+components/resource_provider", "+components/gpu", - "+mojo/shell", + "+ipc", "+mojo/common", "+mojo/converters", "+mojo/public",
diff --git a/components/mus/common/BUILD.gn b/components/mus/common/BUILD.gn index d0cc5d71..6f765c1 100644 --- a/components/mus/common/BUILD.gn +++ b/components/mus/common/BUILD.gn
@@ -2,16 +2,49 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -source_set("common") { +import("//testing/test.gni") + +component("mus_common") { sources = [ "args.cc", "args.h", + "event_param_traits.cc", + "event_param_traits.h", + "event_param_traits_macros.h", + "mus_common_export.h", "transient_window_utils.h", "types.h", "util.h", "window_tracker.h", ] + + defines = [ "MUS_IPC_IMPLEMENTATION" ] + deps = [ "//components/mus/public/interfaces", + "//ipc:ipc", + "//mojo/public/c/system:for_component", + "//ui/events:events", + "//ui/gfx/ipc", + ] +} + +test("mus_common_unittests") { + sources = [ + "event_param_traits_unittest.cc", + ] + public_deps = [ + ":mus_common", + ] + deps = [ + "//base", + "//base/test:run_all_unittests", + "//base/test:test_config", + "//ipc:ipc", + "//mojo/edk/test:test_support", + "//testing/gtest", + "//ui/events:events", + "//ui/gfx:test_support", + "//ui/gfx/ipc", ] }
diff --git a/components/mus/common/args.cc b/components/mus/common/args.cc index c60d591..634828a 100644 --- a/components/mus/common/args.cc +++ b/components/mus/common/args.cc
@@ -3,11 +3,12 @@ // found in the LICENSE file. #include "components/mus/common/args.h" +#include "components/mus/common/mus_common_export.h" namespace mus { // Initializes X11 in threaded mode, and sets the |override_redirect| flag when // creating X11 windows. -const char kUseX11TestConfig[] = "use-x11-test-config"; +const char MUS_COMMON_EXPORT kUseX11TestConfig[] = "use-x11-test-config"; } // namespace mus
diff --git a/components/mus/common/args.h b/components/mus/common/args.h index 29c3de8..02c1b52 100644 --- a/components/mus/common/args.h +++ b/components/mus/common/args.h
@@ -5,11 +5,13 @@ #ifndef COMPONENTS_MUS_COMMON_ARGS_H_ #define COMPONENTS_MUS_COMMON_ARGS_H_ +#include "components/mus/common/mus_common_export.h" + namespace mus { // All args in alphabetical order. The switches should be documented // alongside the definition of their values in the .cc file. -extern const char kUseX11TestConfig[]; +extern const char MUS_COMMON_EXPORT kUseX11TestConfig[]; } // namespace mus
diff --git a/components/mus/common/event_param_traits.cc b/components/mus/common/event_param_traits.cc new file mode 100644 index 0000000..2fd40dbf --- /dev/null +++ b/components/mus/common/event_param_traits.cc
@@ -0,0 +1,277 @@ +// Copyright (c) 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 "components/mus/common/event_param_traits.h" + +#include <string.h> + +#include "ipc/ipc_message_utils.h" +#include "ipc/ipc_param_traits.h" +#include "ui/events/event.h" +#include "ui/gfx/ipc/gfx_param_traits.h" + +// Generate param traits size methods. +#include "ipc/param_traits_size_macros.h" +namespace IPC { +#include "components/mus/common/event_param_traits_macros.h" +} + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC { +#include "components/mus/common/event_param_traits_macros.h" +} + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC { +#include "components/mus/common/event_param_traits_macros.h" +} + +// Generate param traits log methods. +#include "ipc/param_traits_log_macros.h" +namespace IPC { +#include "components/mus/common/event_param_traits_macros.h" +} + +namespace IPC { + +// Implements (Write|Read|Log)Event for event type-qualified functions. Every +// such function invokes an implementation according to the event type and +// flags, or else invokes a default implementation. Event constructors require +// |type|, |time_stamp|, and |flags| (hence the common arguments passed to each +// implementation). +#define EVENT_IMPL(ReturnType, methodName, implName, defaultCase, ...) \ + ReturnType ParamTraits<ui::ScopedEvent>::methodName( \ + ui::EventType type, base::TimeDelta time_stamp, int flags, \ + ##__VA_ARGS__) { \ + switch (type) { \ + case ui::EventType::ET_MOUSE_PRESSED: \ + case ui::EventType::ET_MOUSE_DRAGGED: \ + case ui::EventType::ET_MOUSE_RELEASED: \ + case ui::EventType::ET_MOUSE_MOVED: \ + case ui::EventType::ET_MOUSE_ENTERED: \ + case ui::EventType::ET_MOUSE_EXITED: \ + case ui::EventType::ET_MOUSE_CAPTURE_CHANGED: \ + implName(ui::MouseEvent) \ + case ui::EventType::ET_KEY_PRESSED: \ + case ui::EventType::ET_KEY_RELEASED: \ + implName(ui::KeyEvent) \ + case ui::EventType::ET_MOUSEWHEEL: \ + implName(ui::MouseWheelEvent) \ + case ui::EventType::ET_TOUCH_RELEASED: \ + case ui::EventType::ET_TOUCH_PRESSED: \ + case ui::EventType::ET_TOUCH_MOVED: \ + case ui::EventType::ET_TOUCH_CANCELLED: \ + case ui::EventType::ET_DROP_TARGET_EVENT: \ + implName(ui::TouchEvent) \ + case ui::EventType::ET_GESTURE_SCROLL_BEGIN: \ + case ui::EventType::ET_GESTURE_SCROLL_END: \ + case ui::EventType::ET_GESTURE_SCROLL_UPDATE: \ + case ui::EventType::ET_GESTURE_SHOW_PRESS: \ + case ui::EventType::ET_GESTURE_WIN8_EDGE_SWIPE: \ + case ui::EventType::ET_GESTURE_TAP: \ + case ui::EventType::ET_GESTURE_TAP_DOWN: \ + case ui::EventType::ET_GESTURE_TAP_CANCEL: \ + case ui::EventType::ET_GESTURE_BEGIN: \ + case ui::EventType::ET_GESTURE_END: \ + case ui::EventType::ET_GESTURE_TWO_FINGER_TAP: \ + case ui::EventType::ET_GESTURE_PINCH_BEGIN: \ + case ui::EventType::ET_GESTURE_PINCH_END: \ + case ui::EventType::ET_GESTURE_PINCH_UPDATE: \ + case ui::EventType::ET_GESTURE_LONG_PRESS: \ + case ui::EventType::ET_GESTURE_LONG_TAP: \ + case ui::EventType::ET_GESTURE_SWIPE: \ + case ui::EventType::ET_GESTURE_TAP_UNCONFIRMED: \ + case ui::EventType::ET_GESTURE_DOUBLE_TAP: \ + implName(ui::GestureEvent) \ + case ui::EventType::ET_SCROLL: \ + implName(ui::ScrollEvent) \ + case ui::EventType::ET_SCROLL_FLING_START: \ + case ui::EventType::ET_SCROLL_FLING_CANCEL: \ + if (flags & ui::MouseEventFlags::EF_FROM_TOUCH) { \ + implName(ui::GestureEvent) \ + } else { \ + implName(ui::MouseEvent) \ + } \ + case ui::EventType::ET_CANCEL_MODE: \ + implName(ui::CancelModeEvent) \ + default: \ + defaultCase; \ + } \ + } + +// Concrete event type (T) implementation procedures: size, write, read, log. +#define SIZE_EVENT(T) ParamTraits<T>::GetSize(s, *static_cast<T*>(p.get())); +#define WRITE_EVENT(T) \ + ParamTraits<T>::Write(m, *static_cast<T*>(p.get())); \ + break; +#define READ_EVENT(T) \ + { \ + scoped_ptr<T> event(new T(type, time_stamp, flags)); \ + if (!ParamTraits<T>::Read(m, iter, event.get())) { \ + p->reset(); \ + return false; \ + } else { \ + *p = std::move(event); \ + return true; \ + } \ + } +#define LOG_EVENT(T) return ParamTraits<T>::Log(*static_cast<T*>(p.get()), l); + +// void SizeEvent(ui::EventType type, int flags, base::PickleSizer* s, +// const ui::ScopedEvent& p) { ... } +EVENT_IMPL(void, + SizeEvent, + SIZE_EVENT, + /* default switch/case: no-op */, + base::PickleSizer* s, + const ui::ScopedEvent& p) + +// void WriteEvent(ui::EventType type, int flags, base::Pickle* m, +// const ui::ScopedEvent& p) { ... } +EVENT_IMPL(void, + WriteEvent, + WRITE_EVENT, + /* default switch/case: no-op */, + base::Pickle* m, + const ui::ScopedEvent& p) + +// bool ReadEvent(ui::EventType type, int flags, base::Pickle* m, +// base::PickleIterator* iter, ui::ScopedEvent* p) { ... } +EVENT_IMPL(bool, + ReadEvent, + READ_EVENT, + return false;, + const base::Pickle* m, + base::PickleIterator* iter, + ui::ScopedEvent* p) + +// void LogEvent(ui::EventType type, int flags, const ui::ScopedEvent& p, +// std::string* l) { ... } +EVENT_IMPL(void, + LogEvent, + LOG_EVENT, + /* default switch/case: no-op */, + const ui::ScopedEvent& p, + std::string* l) + +#undef SIZE_EVENT +#undef WRITE_EVENT +#undef READ_EVENT +#undef LOG_EVENT +#undef EVENT_IMPL + +void ParamTraits<ui::ScopedEvent>::GetSize(base::PickleSizer* s, + const param_type& p) { + DCHECK(p); + GetParamSize(s, p->type_); + GetParamSize(s, p->name_); + GetParamSize(s, p->time_stamp_); + GetParamSize(s, p->flags_); + GetParamSize(s, p->phase_); + GetParamSize(s, p->result_); + GetParamSize(s, p->cancelable_); + SizeEvent(p->type_, p->time_stamp_, p->flags_, s, p); +} + +void ParamTraits<ui::ScopedEvent>::Write(base::Pickle* m, const param_type& p) { + DCHECK(p); + WriteParam(m, p->type_); + WriteParam(m, p->name_); + WriteParam(m, p->time_stamp_); + WriteParam(m, p->flags_); + WriteParam(m, p->phase_); + WriteParam(m, p->result_); + WriteParam(m, p->cancelable_); + WriteEvent(p->type_, p->time_stamp_, p->flags_, m, p); +} + +bool ParamTraits<ui::ScopedEvent>::Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* p) { + // Expect: valid ui::ScopedEvent that does not (yet) point to anything. + DCHECK(p && !*p); + + ui::EventType type; + std::string name; + base::TimeDelta time_stamp; + int flags; + ui::EventPhase phase; + ui::EventResult result; + bool cancelable; + + // Read initial params, then invoke ReadEvent which will reset() |p| to an + // instance of the correct concrete event type. + if (!ReadParam(m, iter, &type) || !ReadParam(m, iter, &name) || + !ReadParam(m, iter, &time_stamp) || !ReadParam(m, iter, &flags) || + !ReadParam(m, iter, &phase) || !ReadParam(m, iter, &result) || + !ReadParam(m, iter, &cancelable) || + !ReadEvent(type, time_stamp, flags, m, iter, p)) + return false; + + // Fill in abstract event information. + (*p)->type_ = type; + (*p)->name_ = name; + (*p)->time_stamp_ = time_stamp; + (*p)->flags_ = flags; + (*p)->phase_ = phase; + (*p)->result_ = result; + (*p)->cancelable_ = cancelable; + + return true; +} + +void ParamTraits<ui::ScopedEvent>::Log(const param_type& p, std::string* l) { + l->append("<UI Event: "); + LogEvent(p->type_, p->time_stamp_, p->flags_, p, l); + l->append(">"); +} + +void ParamTraits<ui::CancelModeEvent>::GetSize(base::PickleSizer* s, + const param_type& p) {} + +void ParamTraits<ui::CancelModeEvent>::Write(base::Pickle* m, + const param_type& p) {} + +bool ParamTraits<ui::CancelModeEvent>::Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* p) { + return true; +} + +void ParamTraits<ui::CancelModeEvent>::Log(const param_type& p, + std::string* l) { + l->append("<ui::CancelModeEvent>"); +} + +void ParamTraits<ui::GestureEventDetails::Details>::GetSize( + base::PickleSizer* s, + const param_type& p) { + s->AddBytes(sizeof(param_type)); +} + +void ParamTraits<ui::GestureEventDetails::Details>::Write(base::Pickle* m, + const param_type& p) { + m->WriteBytes(&p, sizeof(param_type)); +} + +bool ParamTraits<ui::GestureEventDetails::Details>::Read( + const base::Pickle* m, + base::PickleIterator* iter, + param_type* p) { + const char* data; + if (!iter->ReadBytes(&data, sizeof(param_type))) + return false; + + memcpy(p, data, sizeof(param_type)); + return true; +} + +void ParamTraits<ui::GestureEventDetails::Details>::Log(const param_type& p, + std::string* l) { + l->append("<ui::GestureEventDetails::Details>"); +} + +} // namespace IPC
diff --git a/components/mus/common/event_param_traits.h b/components/mus/common/event_param_traits.h new file mode 100644 index 0000000..c7702d9 --- /dev/null +++ b/components/mus/common/event_param_traits.h
@@ -0,0 +1,95 @@ +// Copyright (c) 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 COMPONENTS_MUS_COMMON_EVENT_PARAM_TRAITS_H_ +#define COMPONENTS_MUS_COMMON_EVENT_PARAM_TRAITS_H_ + +#include <string> + +#include "components/mus/common/event_param_traits_macros.h" +#include "components/mus/common/mus_common_export.h" +#include "ui/events/event.h" +#include "ui/events/gesture_event_details.h" + +namespace base { +class Pickle; +class PickleIterator; +} + +namespace ui { +class Event; +} + +namespace IPC { + +// Non-serialized data: +// +// Some event data only makes sense and/or is needed in the context where the +// raw event came from. As such, some data are explicitly NOT +// serialized. These data are as follows: +// base::NativeEvent native_event_; +// LatencyInfo* latency_; +// int source_device_id_; + +template <> +struct MUS_COMMON_EXPORT ParamTraits<ui::ScopedEvent> { + typedef ui::ScopedEvent param_type; + static void GetSize(base::PickleSizer* s, const param_type& p); + static void Write(base::Pickle* m, const param_type& p); + static bool Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* p); + static void Log(const param_type& p, std::string* l); + + static void SizeEvent(ui::EventType type, + base::TimeDelta time_stamp, + int flags, + base::PickleSizer* s, + const ui::ScopedEvent& p); + static void WriteEvent(ui::EventType type, + base::TimeDelta time_stamp, + int flags, + base::Pickle* m, + const ui::ScopedEvent& p); + static bool ReadEvent(ui::EventType type, + base::TimeDelta time_stamp, + int flags, + const base::Pickle* m, + base::PickleIterator* iter, + ui::ScopedEvent* p); + static void LogEvent(ui::EventType type, + base::TimeDelta time_stamp, + int flags, + const ui::ScopedEvent& p, + std::string* l); +}; + +// Manually implements no-op implementation for ui::CancelModeEvent because IPC +// BEGIN/END macros with no MEMBER or PARENT in between cause compiler +// errors. +template <> +struct ParamTraits<ui::CancelModeEvent> { + typedef ui::CancelModeEvent param_type; + static void GetSize(base::PickleSizer* s, const param_type& p); + static void Write(base::Pickle* m, const param_type& p); + static bool Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* p); + static void Log(const param_type& p, std::string* l); +}; + +template <> +struct ParamTraits<ui::GestureEventDetails::Details> { + typedef ui::GestureEventDetails::Details param_type; + static void GetSize(base::PickleSizer* s, const param_type& p); + static void Write(base::Pickle* m, const param_type& p); + static bool Read(const base::Pickle* m, + base::PickleIterator* iter, + param_type* p); + static void Log(const param_type& p, std::string* l); +}; + +} // namespace IPC + +#endif // COMPONENTS_MUS_COMMON_EVENT_PARAM_TRAITS_H_
diff --git a/components/mus/common/event_param_traits_macros.h b/components/mus/common/event_param_traits_macros.h new file mode 100644 index 0000000..10b4f36 --- /dev/null +++ b/components/mus/common/event_param_traits_macros.h
@@ -0,0 +1,101 @@ +// Copyright (c) 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 "components/mus/common/mus_common_export.h" +#include "ipc/ipc_message_utils.h" +#include "ipc/param_traits_macros.h" +#include "ui/events/event.h" +#include "ui/events/event_constants.h" + +#undef IPC_MESSAGE_EXPORT +#define IPC_MESSAGE_EXPORT MUS_COMMON_EXPORT + +IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::EventType, + ui::EventType::ET_UNKNOWN, + ui::EventType::ET_LAST) + +IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::EventResult, + ui::EventResult::ER_UNHANDLED, + ui::EventResult::ER_DISABLE_SYNC_HANDLING) + +IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::EventPhase, + ui::EventPhase::EP_PREDISPATCH, + ui::EventPhase::EP_POSTDISPATCH) + +IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::EventPointerType, + ui::EventPhase::EP_PREDISPATCH, + ui::EventPhase::EP_POSTDISPATCH) + +IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::KeyboardCode, + ui::KeyboardCode::VKEY_UNKNOWN, /* 0x00 */ + ui::KeyboardCode::VKEY_OEM_CLEAR /* 0xFE */) + +IPC_ENUM_TRAITS_MIN_MAX_VALUE(ui::DomCode, 0, 0x0c028c) + +IPC_STRUCT_TRAITS_BEGIN(ui::PointerDetails) + IPC_STRUCT_TRAITS_MEMBER(pointer_type) + IPC_STRUCT_TRAITS_MEMBER(radius_x) + IPC_STRUCT_TRAITS_MEMBER(radius_y) + IPC_STRUCT_TRAITS_MEMBER(force) + IPC_STRUCT_TRAITS_MEMBER(tilt_x) + IPC_STRUCT_TRAITS_MEMBER(tilt_y) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::LocatedEvent) + IPC_STRUCT_TRAITS_MEMBER(location_) + IPC_STRUCT_TRAITS_MEMBER(root_location_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::MouseEvent) + IPC_STRUCT_TRAITS_PARENT(ui::LocatedEvent) + IPC_STRUCT_TRAITS_MEMBER(changed_button_flags_) + IPC_STRUCT_TRAITS_MEMBER(pointer_details_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::MouseWheelEvent) + IPC_STRUCT_TRAITS_PARENT(ui::MouseEvent) + IPC_STRUCT_TRAITS_MEMBER(offset_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::TouchEvent) + IPC_STRUCT_TRAITS_PARENT(ui::LocatedEvent) + IPC_STRUCT_TRAITS_MEMBER(touch_id_) + IPC_STRUCT_TRAITS_MEMBER(unique_event_id_) + IPC_STRUCT_TRAITS_MEMBER(rotation_angle_) + IPC_STRUCT_TRAITS_MEMBER(may_cause_scrolling_) + IPC_STRUCT_TRAITS_MEMBER(pointer_details_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::DomKey) + IPC_STRUCT_TRAITS_MEMBER(value_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::KeyEvent) + IPC_STRUCT_TRAITS_MEMBER(is_char_) + IPC_STRUCT_TRAITS_MEMBER(key_code_) + IPC_STRUCT_TRAITS_MEMBER(code_) + IPC_STRUCT_TRAITS_MEMBER(key_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::ScrollEvent) + IPC_STRUCT_TRAITS_PARENT(ui::MouseEvent) + IPC_STRUCT_TRAITS_MEMBER(x_offset_) + IPC_STRUCT_TRAITS_MEMBER(y_offset_) + IPC_STRUCT_TRAITS_MEMBER(x_offset_ordinal_) + IPC_STRUCT_TRAITS_MEMBER(y_offset_ordinal_) + IPC_STRUCT_TRAITS_MEMBER(finger_count_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::GestureEventDetails) + IPC_STRUCT_TRAITS_MEMBER(type_) + IPC_STRUCT_TRAITS_MEMBER(data_) + IPC_STRUCT_TRAITS_MEMBER(touch_points_) + IPC_STRUCT_TRAITS_MEMBER(bounding_box_) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(ui::GestureEvent) + IPC_STRUCT_TRAITS_PARENT(ui::LocatedEvent) + IPC_STRUCT_TRAITS_MEMBER(details_) +IPC_STRUCT_TRAITS_END()
diff --git a/components/mus/common/event_param_traits_unittest.cc b/components/mus/common/event_param_traits_unittest.cc new file mode 100644 index 0000000..966f9ab --- /dev/null +++ b/components/mus/common/event_param_traits_unittest.cc
@@ -0,0 +1,468 @@ +// Copyright (c) 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 "components/mus/common/event_param_traits.h" + +#include <limits> + +#include "ipc/ipc_message.h" +#include "ipc/ipc_param_traits.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/events/event.h" +#include "ui/events/event_constants.h" +#include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/rect_f.h" +#include "ui/gfx/geometry/vector2d.h" + +namespace ui { +namespace { + +#define CAST_EVENT(T, e) (*static_cast<const T*>(e.get())) +#define FEQ(a, b) (a == b || (std::isnan(a) && std::isnan(b))) +#define ASSERT_FEQ(a, b) ASSERT_TRUE(FEQ(a, b)) +#define MIN(T) std::numeric_limits<T>::min() +#define MAX(T) std::numeric_limits<T>::max() +#define IMIN MIN(int) +#define IMAX MAX(int) +#define FMIN MIN(float) +#define FMAX MAX(float) +#define FNAN std::numeric_limits<float>::quiet_NaN() + +class EventParamTraitsTest : public testing::Test { + protected: + // Implements event downcasting as performed by param traits. This enables + // testing the interface that client code actually uses: (de)serialization of + // scoped Event pointers that contain a concrete type. + static void CompareEvents(const ScopedEvent& a, const ScopedEvent& b) { + ASSERT_EQ(!!a, !!b); + ASSERT_EQ(a->type(), b->type()); + switch (a->type()) { + case EventType::ET_MOUSE_PRESSED: + case EventType::ET_MOUSE_DRAGGED: + case EventType::ET_MOUSE_RELEASED: + case EventType::ET_MOUSE_MOVED: + case EventType::ET_MOUSE_ENTERED: + case EventType::ET_MOUSE_EXITED: + case EventType::ET_MOUSE_CAPTURE_CHANGED: + Compare(CAST_EVENT(MouseEvent, a), CAST_EVENT(MouseEvent, b)); + break; + case EventType::ET_KEY_PRESSED: + case EventType::ET_KEY_RELEASED: + Compare(CAST_EVENT(KeyEvent, a), CAST_EVENT(KeyEvent, b)); + break; + case EventType::ET_MOUSEWHEEL: + Compare(CAST_EVENT(MouseWheelEvent, a), CAST_EVENT(MouseWheelEvent, b)); + break; + case EventType::ET_TOUCH_RELEASED: + case EventType::ET_TOUCH_PRESSED: + case EventType::ET_TOUCH_MOVED: + case EventType::ET_TOUCH_CANCELLED: + case EventType::ET_DROP_TARGET_EVENT: + Compare(CAST_EVENT(TouchEvent, a), CAST_EVENT(TouchEvent, b)); + break; + case EventType::ET_GESTURE_SCROLL_BEGIN: + case EventType::ET_GESTURE_SCROLL_END: + case EventType::ET_GESTURE_SCROLL_UPDATE: + case EventType::ET_GESTURE_SHOW_PRESS: + case EventType::ET_GESTURE_WIN8_EDGE_SWIPE: + case EventType::ET_GESTURE_TAP: + case EventType::ET_GESTURE_TAP_DOWN: + case EventType::ET_GESTURE_TAP_CANCEL: + case EventType::ET_GESTURE_BEGIN: + case EventType::ET_GESTURE_END: + case EventType::ET_GESTURE_TWO_FINGER_TAP: + case EventType::ET_GESTURE_PINCH_BEGIN: + case EventType::ET_GESTURE_PINCH_END: + case EventType::ET_GESTURE_PINCH_UPDATE: + case EventType::ET_GESTURE_LONG_PRESS: + case EventType::ET_GESTURE_LONG_TAP: + case EventType::ET_GESTURE_SWIPE: + case EventType::ET_GESTURE_TAP_UNCONFIRMED: + case EventType::ET_GESTURE_DOUBLE_TAP: + Compare(CAST_EVENT(GestureEvent, a), CAST_EVENT(GestureEvent, b)); + break; + case EventType::ET_SCROLL: + Compare(CAST_EVENT(ScrollEvent, a), CAST_EVENT(ScrollEvent, b)); + break; + case EventType::ET_SCROLL_FLING_START: + case EventType::ET_SCROLL_FLING_CANCEL: + ASSERT_EQ(!!a->flags() & MouseEventFlags::EF_FROM_TOUCH, + !!b->flags() & MouseEventFlags::EF_FROM_TOUCH); + if (a->flags() & MouseEventFlags::EF_FROM_TOUCH) { + Compare(CAST_EVENT(GestureEvent, a), CAST_EVENT(GestureEvent, b)); + } else { + Compare(CAST_EVENT(MouseEvent, a), CAST_EVENT(MouseEvent, b)); + } + break; + case EventType::ET_CANCEL_MODE: + Compare(CAST_EVENT(CancelModeEvent, a), CAST_EVENT(CancelModeEvent, b)); + break; + default: + NOTREACHED(); + } + } + +#undef CAST_EVENT + +#define CAST_EVENT(T, e) static_cast<const T&>(e) +#define COMPARE_BASE(T, a, b) Compare(CAST_EVENT(T, a), CAST_EVENT(T, b)) + + static void Compare(const Event& a, const Event& b) { + ASSERT_EQ(a.type(), b.type()); + ASSERT_EQ(a.name(), b.name()); + ASSERT_EQ(a.time_stamp(), b.time_stamp()); + ASSERT_EQ(a.flags(), b.flags()); + ASSERT_EQ(a.phase(), b.phase()); + ASSERT_EQ(a.result(), b.result()); + ASSERT_EQ(a.cancelable(), b.cancelable()); + ASSERT_EQ(a.IsShiftDown(), b.IsShiftDown()); + ASSERT_EQ(a.IsControlDown(), b.IsControlDown()); + ASSERT_EQ(a.IsAltDown(), b.IsAltDown()); + ASSERT_EQ(a.IsCommandDown(), b.IsCommandDown()); + ASSERT_EQ(a.IsAltGrDown(), b.IsAltGrDown()); + ASSERT_EQ(a.IsCapsLockOn(), b.IsCapsLockOn()); + ASSERT_EQ(a.IsKeyEvent(), b.IsKeyEvent()); + ASSERT_EQ(a.IsMouseEvent(), b.IsMouseEvent()); + ASSERT_EQ(a.IsTouchEvent(), b.IsTouchEvent()); + ASSERT_EQ(a.IsGestureEvent(), b.IsGestureEvent()); + ASSERT_EQ(a.IsEndingEvent(), b.IsEndingEvent()); + ASSERT_EQ(a.IsScrollEvent(), b.IsScrollEvent()); + ASSERT_EQ(a.IsScrollGestureEvent(), b.IsScrollGestureEvent()); + ASSERT_EQ(a.IsFlingScrollEvent(), b.IsFlingScrollEvent()); + ASSERT_EQ(a.IsMouseWheelEvent(), b.IsMouseWheelEvent()); + ASSERT_EQ(a.IsLocatedEvent(), b.IsLocatedEvent()); + ASSERT_EQ(a.handled(), b.handled()); + } + + static void Compare(const CancelModeEvent& a, const CancelModeEvent& b) { + COMPARE_BASE(Event, a, b); + } + + static void Compare(const LocatedEvent& a, const LocatedEvent& b) { + COMPARE_BASE(Event, a, b); + + ASSERT_EQ(a.x(), b.x()); + ASSERT_EQ(a.y(), b.y()); + ASSERT_EQ(a.location(), b.location()); + ASSERT_EQ(a.location_f(), b.location_f()); + ASSERT_EQ(a.root_location(), b.root_location()); + ASSERT_EQ(a.root_location_f(), b.root_location_f()); + } + + static void Compare(const MouseEvent& a, const MouseEvent& b) { + COMPARE_BASE(LocatedEvent, a, b); + + ASSERT_EQ(a.IsOnlyLeftMouseButton(), b.IsOnlyLeftMouseButton()); + ASSERT_EQ(a.IsLeftMouseButton(), b.IsLeftMouseButton()); + ASSERT_EQ(a.IsOnlyMiddleMouseButton(), b.IsOnlyMiddleMouseButton()); + ASSERT_EQ(a.IsMiddleMouseButton(), b.IsMiddleMouseButton()); + ASSERT_EQ(a.IsOnlyRightMouseButton(), b.IsOnlyRightMouseButton()); + ASSERT_EQ(a.IsRightMouseButton(), b.IsRightMouseButton()); + ASSERT_EQ(a.IsAnyButton(), b.IsAnyButton()); + ASSERT_EQ(a.button_flags(), b.button_flags()); + ASSERT_EQ(a.GetClickCount(), b.GetClickCount()); + ASSERT_EQ(a.changed_button_flags(), b.changed_button_flags()); + + Compare(a.pointer_details(), b.pointer_details()); + } + + static void Compare(const MouseWheelEvent& a, const MouseWheelEvent& b) { + COMPARE_BASE(MouseEvent, a, b); + + ASSERT_EQ(a.x_offset(), b.x_offset()); + ASSERT_EQ(a.y_offset(), b.y_offset()); + ASSERT_EQ(a.offset(), b.offset()); + } + + static void Compare(const TouchEvent& a, const TouchEvent& b) { + COMPARE_BASE(LocatedEvent, a, b); + + ASSERT_EQ(a.touch_id(), b.touch_id()); + ASSERT_EQ(a.unique_event_id(), b.unique_event_id()); + ASSERT_FEQ(a.rotation_angle(), b.rotation_angle()); + ASSERT_EQ(a.may_cause_scrolling(), b.may_cause_scrolling()); + ASSERT_EQ(a.synchronous_handling_disabled(), + b.synchronous_handling_disabled()); + + Compare(a.pointer_details(), b.pointer_details()); + } + + static void Compare(const KeyEvent& a, const KeyEvent& b) { + COMPARE_BASE(Event, a, b); + + ASSERT_EQ(a.GetCharacter(), b.GetCharacter()); + ASSERT_EQ(a.GetUnmodifiedText(), b.GetUnmodifiedText()); + ASSERT_EQ(a.GetText(), b.GetText()); + ASSERT_EQ(a.is_char(), b.is_char()); + ASSERT_EQ(a.is_repeat(), b.is_repeat()); + ASSERT_EQ(a.key_code(), b.key_code()); + ASSERT_EQ(a.GetLocatedWindowsKeyboardCode(), + b.GetLocatedWindowsKeyboardCode()); + ASSERT_EQ(a.GetConflatedWindowsKeyCode(), b.GetConflatedWindowsKeyCode()); + ASSERT_EQ(a.IsUnicodeKeyCode(), b.IsUnicodeKeyCode()); + ASSERT_EQ(a.code(), b.code()); + ASSERT_EQ(a.GetCodeString(), b.GetCodeString()); + ASSERT_EQ(a.GetDomKey(), b.GetDomKey()); + } + + static void Compare(const ScrollEvent& a, const ScrollEvent& b) { + COMPARE_BASE(MouseEvent, a, b); + + ASSERT_FEQ(a.x_offset(), b.x_offset()); + ASSERT_FEQ(a.y_offset(), b.y_offset()); + ASSERT_FEQ(a.x_offset_ordinal(), b.x_offset_ordinal()); + ASSERT_FEQ(a.y_offset_ordinal(), b.y_offset_ordinal()); + ASSERT_EQ(a.finger_count(), b.finger_count()); + } + + static void Compare(const GestureEvent& a, const GestureEvent& b) { + COMPARE_BASE(LocatedEvent, a, b); + + ASSERT_EQ(a.details(), b.details()); + } + + static void Compare(const PointerDetails& a, const PointerDetails& b) { + ASSERT_EQ(a.pointer_type, b.pointer_type); + ASSERT_FEQ(a.radius_x, b.radius_x); + ASSERT_FEQ(a.radius_y, b.radius_y); + ASSERT_FEQ(a.force, b.force); + ASSERT_FEQ(a.tilt_x, b.tilt_x); + ASSERT_FEQ(a.tilt_y, b.tilt_y); + } + + static void Verify(const ScopedEvent& event_in) { + IPC::Message msg; + IPC::ParamTraits<ScopedEvent>::Write(&msg, event_in); + + ScopedEvent event_out; + base::PickleIterator iter(msg); + EXPECT_TRUE(IPC::ParamTraits<ScopedEvent>::Read(&msg, &iter, &event_out)); + + CompareEvents(event_in, event_out); + + // Perform a sanity check that logging doesn't explode. + std::string event_in_string; + IPC::ParamTraits<ScopedEvent>::Log(event_in, &event_in_string); + std::string event_out_string; + IPC::ParamTraits<ScopedEvent>::Log(event_out, &event_out_string); + ASSERT_FALSE(event_in_string.empty()); + EXPECT_EQ(event_in_string, event_out_string); + } + + static GestureEventDetails CreateCornerCaseGestureEventDetails( + EventType type) { + GestureEventDetails details; + + // Only some types support |delta_x| and |delta_y| parameters. + if (type == EventType::ET_GESTURE_SCROLL_BEGIN || + type == EventType::ET_GESTURE_SCROLL_UPDATE || + type == EventType::ET_SCROLL_FLING_START || + type == EventType::ET_GESTURE_TWO_FINGER_TAP || + type == EventType::ET_GESTURE_SWIPE) { + details = GestureEventDetails(type, FMIN, FMAX); + } else { + details = GestureEventDetails(type); + } + + details.set_bounding_box(gfx::RectF(FMIN, FMAX, FNAN, FNAN)); + + // Note: Positive values and |type| check dodges DCHECKs that are not being + // tested here. + details.set_touch_points(IMAX); + if (type == EventType::ET_GESTURE_TAP || + type == EventType::ET_GESTURE_TAP_UNCONFIRMED || + type == EventType::ET_GESTURE_DOUBLE_TAP) { + details.set_tap_count(IMAX); + } + if (type == EventType::ET_GESTURE_PINCH_UPDATE) { + details.set_scale(FMAX); + } + + return details; + } +}; + +TEST_F(EventParamTraitsTest, GoodCancelModeEvent) { + ScopedEvent event(new CancelModeEvent()); + Verify(event); +} + +TEST_F(EventParamTraitsTest, GoodSimpleMouseEvent) { + EventType event_types[7] = { + EventType::ET_MOUSE_PRESSED, EventType::ET_MOUSE_DRAGGED, + EventType::ET_MOUSE_RELEASED, EventType::ET_MOUSE_MOVED, + EventType::ET_MOUSE_ENTERED, EventType::ET_MOUSE_EXITED, + EventType::ET_MOUSE_CAPTURE_CHANGED, + }; + for (int i = 0; i < 7; i++) { + ScopedEvent event(new MouseEvent(event_types[i], gfx::Point(), gfx::Point(), + base::TimeDelta(), 0, 0)); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodCornerCaseMouseEvent) { + EventType event_types[7] = { + EventType::ET_MOUSE_PRESSED, EventType::ET_MOUSE_DRAGGED, + EventType::ET_MOUSE_RELEASED, EventType::ET_MOUSE_MOVED, + EventType::ET_MOUSE_ENTERED, EventType::ET_MOUSE_EXITED, + EventType::ET_MOUSE_CAPTURE_CHANGED, + }; + for (int i = 0; i < 7; i++) { + ScopedEvent event(new MouseEvent(event_types[i], gfx::Point(IMIN, IMIN), + gfx::Point(IMAX, IMAX), + base::TimeDelta::Max(), IMIN, IMAX)); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodSimpleMouseWheelEvent) { + ScopedEvent event(new MouseWheelEvent(gfx::Vector2d(), gfx::Point(), + gfx::Point(), base::TimeDelta(), 0, 0)); + Verify(event); +} + +TEST_F(EventParamTraitsTest, GoodCornerCaseMouseWheelEvent) { + ScopedEvent event(new MouseWheelEvent( + gfx::Vector2d(IMIN, IMAX), gfx::Point(IMIN, IMIN), gfx::Point(IMAX, IMAX), + base::TimeDelta::Max(), IMIN, IMAX)); + Verify(event); +} + +TEST_F(EventParamTraitsTest, GoodSimpleTouchEvent) { + EventType event_types[5] = { + EventType::ET_TOUCH_RELEASED, EventType::ET_TOUCH_PRESSED, + EventType::ET_TOUCH_MOVED, EventType::ET_TOUCH_CANCELLED, + EventType::ET_DROP_TARGET_EVENT, + }; + for (int i = 0; i < 5; i++) { + ScopedEvent event(new TouchEvent(event_types[i], gfx::Point(), 0, 0, + base::TimeDelta(), 0.0, 0.0, 0.0, 0.0)); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodCornerCaseTouchEvent) { + EventType event_types[5] = { + EventType::ET_TOUCH_RELEASED, EventType::ET_TOUCH_PRESSED, + EventType::ET_TOUCH_MOVED, EventType::ET_TOUCH_CANCELLED, + EventType::ET_DROP_TARGET_EVENT, + }; + for (int i = 0; i < 5; i++) { + ScopedEvent event(new TouchEvent(event_types[i], gfx::Point(IMIN, IMAX), + IMIN, IMAX, base::TimeDelta::Max(), FMIN, + FMAX, FNAN, FNAN)); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodSimpleKeyEvent) { + EventType event_types[2] = { + EventType::ET_KEY_PRESSED, EventType::ET_KEY_RELEASED, + }; + for (int i = 0; i < 2; i++) { + ScopedEvent event(new KeyEvent(event_types[i], KeyboardCode::VKEY_UNKNOWN, + static_cast<DomCode>(0), 0, DomKey(0), + base::TimeDelta())); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodCornerCaseKeyEvent) { + EventType event_types[2] = { + EventType::ET_KEY_PRESSED, EventType::ET_KEY_RELEASED, + }; + for (int i = 0; i < 2; i++) { + ScopedEvent event(new KeyEvent(event_types[i], KeyboardCode::VKEY_OEM_CLEAR, + static_cast<DomCode>(0x0c028c), IMIN, + MIN(DomKey), base::TimeDelta::Max())); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodSimpleScrollEvent) { + ScopedEvent event(new ScrollEvent(EventType::ET_SCROLL, gfx::Point(), + base::TimeDelta(), 0, 0.0, 0.0, 0.0, 0.0, + 0)); + Verify(event); +} + +TEST_F(EventParamTraitsTest, GoodCornerCaseScrollEvent) { + ScopedEvent event(new ScrollEvent(EventType::ET_SCROLL, gfx::Point(), + base::TimeDelta(), IMIN, FMIN, FMAX, FNAN, + FMIN, IMAX)); + Verify(event); +} + +TEST_F(EventParamTraitsTest, GoodSimpleGestureEvent) { + EventType event_types[19] = { + EventType::ET_GESTURE_SCROLL_BEGIN, + EventType::ET_GESTURE_SCROLL_END, + EventType::ET_GESTURE_SCROLL_UPDATE, + EventType::ET_GESTURE_SHOW_PRESS, + EventType::ET_GESTURE_WIN8_EDGE_SWIPE, + EventType::ET_GESTURE_TAP, + EventType::ET_GESTURE_TAP_DOWN, + EventType::ET_GESTURE_TAP_CANCEL, + EventType::ET_GESTURE_BEGIN, + EventType::ET_GESTURE_END, + EventType::ET_GESTURE_TWO_FINGER_TAP, + EventType::ET_GESTURE_PINCH_BEGIN, + EventType::ET_GESTURE_PINCH_END, + EventType::ET_GESTURE_PINCH_UPDATE, + EventType::ET_GESTURE_LONG_PRESS, + EventType::ET_GESTURE_LONG_TAP, + EventType::ET_GESTURE_SWIPE, + EventType::ET_GESTURE_TAP_UNCONFIRMED, + EventType::ET_GESTURE_DOUBLE_TAP, + }; + for (int i = 0; i < 19; i++) { + ScopedEvent event(new GestureEvent(0.0, 0.0, 0, base::TimeDelta(), + GestureEventDetails(event_types[i]))); + Verify(event); + } +} + +TEST_F(EventParamTraitsTest, GoodCornerCaseGestureEvent) { + EventType event_types[17] = { + EventType::ET_GESTURE_SCROLL_UPDATE, + EventType::ET_GESTURE_SHOW_PRESS, + EventType::ET_GESTURE_WIN8_EDGE_SWIPE, + EventType::ET_GESTURE_TAP, + EventType::ET_GESTURE_TAP_DOWN, + EventType::ET_GESTURE_TAP_CANCEL, + EventType::ET_GESTURE_BEGIN, + EventType::ET_GESTURE_END, + EventType::ET_GESTURE_TWO_FINGER_TAP, + EventType::ET_GESTURE_PINCH_BEGIN, + EventType::ET_GESTURE_PINCH_END, + EventType::ET_GESTURE_PINCH_UPDATE, + EventType::ET_GESTURE_LONG_PRESS, + EventType::ET_GESTURE_LONG_TAP, + EventType::ET_GESTURE_SWIPE, + EventType::ET_GESTURE_TAP_UNCONFIRMED, + EventType::ET_GESTURE_DOUBLE_TAP, + }; + for (int i = 0; i < 17; i++) { + ScopedEvent event( + new GestureEvent(0.0, 0.0, 0, base::TimeDelta(), + CreateCornerCaseGestureEventDetails(event_types[i]))); + Verify(event); + } +} + +#undef FEQ +#undef ASSERT_FEQ +#undef CAST_EVENT +#undef COMPARE_BASE +#undef MIN +#undef MAX +#undef IMIN +#undef IMAX +#undef FMIN +#undef FMAX +#undef FNAN + +} // namespace +} // namespace ui
diff --git a/components/mus/common/mus_common_export.h b/components/mus/common/mus_common_export.h new file mode 100644 index 0000000..3a2e930 --- /dev/null +++ b/components/mus/common/mus_common_export.h
@@ -0,0 +1,29 @@ +// Copyright (c) 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 COMPONENTS_MUS_COMMON_MUS_COMMON_EXPORT_H_ +#define COMPONENTS_MUS_COMMON_MUS_COMMON_EXPORT_H_ + +#if defined(COMPONENT_BUILD) +#if defined(WIN32) + +#if defined(MUS_IPC_IMPLEMENTATION) +#define MUS_COMMON_EXPORT __declspec(dllexport) +#else +#define MUS_COMMON_EXPORT __declspec(dllimport) +#endif // defined(MUS_IPC_IMPLEMENTATION) + +#else // defined(WIN32) +#if defined(MUS_IPC_IMPLEMENTATION) +#define MUS_COMMON_EXPORT __attribute__((visibility("default"))) +#else +#define MUS_COMMON_EXPORT +#endif +#endif + +#else // defined(COMPONENT_BUILD) +#define MUS_COMMON_EXPORT +#endif + +#endif // COMPONENTS_MUS_COMMON_MUS_COMMON_EXPORT_H_
diff --git a/components/mus/mus_app.cc b/components/mus/mus_app.cc index 1b42c95a..f9ec70ad 100644 --- a/components/mus/mus_app.cc +++ b/components/mus/mus_app.cc
@@ -95,8 +95,8 @@ void MandolineUIServicesApp::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { connector_ = connector; surfaces_state_ = new SurfacesState;
diff --git a/components/mus/mus_app.h b/components/mus/mus_app.h index 2e2193f2..f471723c 100644 --- a/components/mus/mus_app.h +++ b/components/mus/mus_app.h
@@ -64,7 +64,7 @@ // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // ConnectionManagerDelegate:
diff --git a/components/mus/public/cpp/BUILD.gn b/components/mus/public/cpp/BUILD.gn index b2bb6df..d750a9d7 100644 --- a/components/mus/public/cpp/BUILD.gn +++ b/components/mus/public/cpp/BUILD.gn
@@ -49,7 +49,7 @@ "//cc", "//cc/surfaces", "//cc/surfaces:surface_id", - "//components/mus/common", + "//components/mus/common:mus_common", "//mojo/converters/geometry", "//mojo/converters/surfaces", "//mojo/gles2",
diff --git a/components/mus/public/cpp/tests/BUILD.gn b/components/mus/public/cpp/tests/BUILD.gn index dde0ebf..f89b23f 100644 --- a/components/mus/public/cpp/tests/BUILD.gn +++ b/components/mus/public/cpp/tests/BUILD.gn
@@ -49,7 +49,7 @@ ":unittest_support", "//base", "//base/test:test_support", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/public/cpp", "//mojo/common:common_base", "//mojo/converters/geometry",
diff --git a/components/mus/public/interfaces/BUILD.gn b/components/mus/public/interfaces/BUILD.gn index 40ebaf8..7cba5cec 100644 --- a/components/mus/public/interfaces/BUILD.gn +++ b/components/mus/public/interfaces/BUILD.gn
@@ -38,5 +38,5 @@ ] typemaps = [ "//gpu/command_buffer/common/mojo.typemap" ] - typemap_deps = [ "//gpu/ipc" ] + typemap_deps = [ "//gpu/ipc/common" ] }
diff --git a/components/mus/ws/BUILD.gn b/components/mus/ws/BUILD.gn index 76329040..4c6eadb 100644 --- a/components/mus/ws/BUILD.gn +++ b/components/mus/ws/BUILD.gn
@@ -76,7 +76,7 @@ "//cc", "//cc/surfaces", "//cc/surfaces:surface_id", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/gles2", "//components/mus/public/interfaces", "//components/mus/surfaces", @@ -115,7 +115,7 @@ deps = [ "//base", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/public/cpp", "//components/mus/public/interfaces", "//mojo/common", @@ -160,7 +160,7 @@ "//base", "//base/test:test_config", "//cc:cc", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/public/cpp", "//components/mus/public/interfaces", "//components/mus/surfaces", @@ -200,7 +200,7 @@ ":test_support", "//base", "//base/test:test_config", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/public/cpp", "//components/mus/public/cpp/tests:test_support", "//components/mus/public/interfaces",
diff --git a/components/mus/ws/display.cc b/components/mus/ws/display.cc index 52d140f5..3ee54d13 100644 --- a/components/mus/ws/display.cc +++ b/components/mus/ws/display.cc
@@ -19,6 +19,7 @@ #include "mojo/common/common_type_converters.h" #include "mojo/converters/geometry/geometry_type_converters.h" #include "mojo/converters/input_events/input_events_type_converters.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mus { namespace ws { @@ -186,7 +187,8 @@ : window_manager_state_map_.begin()->second.get(); } -WindowManagerState* Display::GetWindowManagerStateForUser(UserId user_id) { +WindowManagerState* Display::GetWindowManagerStateForUser( + const UserId& user_id) { auto iter = window_manager_state_map_.find(user_id); return iter == window_manager_state_map_.end() ? nullptr : iter->second.get(); } @@ -302,7 +304,8 @@ WindowManagerState* wms = wms_ptr.get(); // For this case we never create additional WindowManagerStates, so any // id works. - window_manager_state_map_[0u] = std::move(wms_ptr); + window_manager_state_map_[mojo::shell::mojom::kRootUserID] = + std::move(wms_ptr); wms->tree_ = binding_->CreateWindowTree(wms->root()); } else { CreateWindowManagerStatesFromRegistry(); @@ -614,13 +617,13 @@ window->RemoveObserver(this); } -void Display::OnActiveUserIdChanged(UserId id) { +void Display::OnActiveUserIdChanged(const UserId& id) { // TODO(sky): this likely needs to cancel any pending events and all that. } -void Display::OnUserIdAdded(UserId id) {} +void Display::OnUserIdAdded(const UserId& id) {} -void Display::OnUserIdRemoved(UserId id) { +void Display::OnUserIdRemoved(const UserId& id) { if (binding_) return;
diff --git a/components/mus/ws/display.h b/components/mus/ws/display.h index 6fa03ea..6cf8975 100644 --- a/components/mus/ws/display.h +++ b/components/mus/ws/display.h
@@ -109,7 +109,7 @@ WindowManagerState* GetWindowManagerStateWithRoot(const ServerWindow* window); // TODO(sky): this is wrong, plumb through user_id. WindowManagerState* GetFirstWindowManagerState(); - WindowManagerState* GetWindowManagerStateForUser(UserId user_id); + WindowManagerState* GetWindowManagerStateForUser(const UserId& user_id); size_t num_window_manger_states() const { return window_manager_state_map_.size(); } @@ -160,7 +160,7 @@ friend class test::DisplayTestApi; using WindowManagerStateMap = - std::map<uint32_t, scoped_ptr<WindowManagerState>>; + std::map<UserId, scoped_ptr<WindowManagerState>>; // There are two types of events that may be queued, both occur only when // waiting for an ack from a client. @@ -242,9 +242,9 @@ void OnWindowDestroyed(ServerWindow* window) override; // UserIdTrackerObserver: - void OnActiveUserIdChanged(UserId id) override; - void OnUserIdAdded(UserId id) override; - void OnUserIdRemoved(UserId id) override; + void OnActiveUserIdChanged(const UserId& id) override; + void OnUserIdAdded(const UserId& id) override; + void OnUserIdRemoved(const UserId& id) override; // WindowManagerFactoryRegistryObserver: void OnWindowManagerFactorySet(WindowManagerFactoryService* service) override;
diff --git a/components/mus/ws/display_unittest.cc b/components/mus/ws/display_unittest.cc index ef830166..663e04c1 100644 --- a/components/mus/ws/display_unittest.cc +++ b/components/mus/ws/display_unittest.cc
@@ -78,8 +78,8 @@ const int kNumHostsToCreate = 2; connection_manager_delegate_.set_num_displays_to_create(kNumHostsToCreate); - const UserId kTestId1 = 2; - const UserId kTestId2 = 21; + const UserId kTestId1 = "2"; + const UserId kTestId2 = "21"; WindowManagerFactoryRegistryTestApi( connection_manager_->window_manager_factory_registry()) .AddService(kTestId1, &test_window_manager_factory_); @@ -116,8 +116,8 @@ TEST_F(DisplayTest, Destruction) { connection_manager_delegate_.set_num_displays_to_create(1); - const UserId kTestId1 = 2; - const UserId kTestId2 = 21; + const UserId kTestId1 = "2"; + const UserId kTestId2 = "21"; WindowManagerFactoryRegistryTestApi( connection_manager_->window_manager_factory_registry()) .AddService(kTestId1, &test_window_manager_factory_);
diff --git a/components/mus/ws/test_utils.cc b/components/mus/ws/test_utils.cc index e6d1644c..55dc179 100644 --- a/components/mus/ws/test_utils.cc +++ b/components/mus/ws/test_utils.cc
@@ -70,7 +70,7 @@ WindowManagerFactoryRegistryTestApi::~WindowManagerFactoryRegistryTestApi() {} void WindowManagerFactoryRegistryTestApi::AddService( - UserId user_id, + const UserId& user_id, mojom::WindowManagerFactory* factory) { scoped_ptr<WindowManagerFactoryService> service_ptr( new WindowManagerFactoryService(registry_, user_id));
diff --git a/components/mus/ws/test_utils.h b/components/mus/ws/test_utils.h index b3b52236..216d3a0b 100644 --- a/components/mus/ws/test_utils.h +++ b/components/mus/ws/test_utils.h
@@ -28,7 +28,7 @@ WindowManagerFactoryRegistryTestApi(WindowManagerFactoryRegistry* registry); ~WindowManagerFactoryRegistryTestApi(); - void AddService(UserId user_id, mojom::WindowManagerFactory* factory); + void AddService(const UserId& user_id, mojom::WindowManagerFactory* factory); private: WindowManagerFactoryRegistry* registry_;
diff --git a/components/mus/ws/user_id.h b/components/mus/ws/user_id.h index 26c9bb3..f019701 100644 --- a/components/mus/ws/user_id.h +++ b/components/mus/ws/user_id.h
@@ -5,12 +5,12 @@ #ifndef COMPONENTS_MUS_WS_USER_ID_H_ #define COMPONENTS_MUS_WS_USER_ID_H_ -#include <stdint.h> +#include <string> namespace mus { namespace ws { -using UserId = uint32_t; +using UserId = std::string; } // namespace ws } // namespace mus
diff --git a/components/mus/ws/user_id_tracker.cc b/components/mus/ws/user_id_tracker.cc index 912de1e..453fde6d 100644 --- a/components/mus/ws/user_id_tracker.cc +++ b/components/mus/ws/user_id_tracker.cc
@@ -5,22 +5,22 @@ #include "components/mus/ws/user_id_tracker.h" #include "components/mus/ws/user_id_tracker_observer.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mus { namespace ws { UserIdTracker::UserIdTracker() - : active_id_(mojo::shell::mojom::Connector::kInvalidApplicationID) {} + : active_id_(mojo::shell::mojom::kRootUserID) {} UserIdTracker::~UserIdTracker() { DCHECK(ids_.empty()); } -bool UserIdTracker::IsValidUserId(UserId id) const { +bool UserIdTracker::IsValidUserId(const UserId& id) const { return ids_.count(id) > 0; } -void UserIdTracker::SetActiveUserId(UserId id) { +void UserIdTracker::SetActiveUserId(const UserId& id) { if (id == active_id_) return; @@ -29,13 +29,13 @@ OnActiveUserIdChanged(id)); } -void UserIdTracker::AddUserId(UserId id) { +void UserIdTracker::AddUserId(const UserId& id) { DCHECK(!IsValidUserId(id)); ids_.insert(id); FOR_EACH_OBSERVER(UserIdTrackerObserver, observers_, OnUserIdAdded(id)); } -void UserIdTracker::RemoveUserId(UserId id) { +void UserIdTracker::RemoveUserId(const UserId& id) { DCHECK(IsValidUserId(id)); ids_.erase(id); FOR_EACH_OBSERVER(UserIdTrackerObserver, observers_, OnUserIdRemoved(id));
diff --git a/components/mus/ws/user_id_tracker.h b/components/mus/ws/user_id_tracker.h index 5a97e6e..45d577d5e 100644 --- a/components/mus/ws/user_id_tracker.h +++ b/components/mus/ws/user_id_tracker.h
@@ -24,11 +24,11 @@ UserIdTracker(); ~UserIdTracker(); - bool IsValidUserId(UserId id) const; + bool IsValidUserId(const UserId& id) const; - void SetActiveUserId(UserId id); - void AddUserId(UserId id); - void RemoveUserId(UserId id); + void SetActiveUserId(const UserId& id); + void AddUserId(const UserId& id); + void RemoveUserId(const UserId& id); void AddObserver(UserIdTrackerObserver* observer); void RemoveObserver(UserIdTrackerObserver* observer);
diff --git a/components/mus/ws/user_id_tracker_observer.h b/components/mus/ws/user_id_tracker_observer.h index d6b5a86..840c410b 100644 --- a/components/mus/ws/user_id_tracker_observer.h +++ b/components/mus/ws/user_id_tracker_observer.h
@@ -14,9 +14,9 @@ class UserIdTrackerObserver { public: - virtual void OnActiveUserIdChanged(UserId id) = 0; - virtual void OnUserIdAdded(UserId id) = 0; - virtual void OnUserIdRemoved(UserId id) = 0; + virtual void OnActiveUserIdChanged(const UserId& id) = 0; + virtual void OnUserIdAdded(const UserId& id) = 0; + virtual void OnUserIdRemoved(const UserId& id) = 0; protected: virtual ~UserIdTrackerObserver() {}
diff --git a/components/mus/ws/window_manager_client_apptest.cc b/components/mus/ws/window_manager_client_apptest.cc index b3da12c..fe3cc179 100644 --- a/components/mus/ws/window_manager_client_apptest.cc +++ b/components/mus/ws/window_manager_client_apptest.cc
@@ -845,7 +845,8 @@ ValidIndexOf(parent->children(), child1)); } -TEST_F(WindowServerTest, ActivationNext) { +// Very flaky: http://crbug.com/592313. +TEST_F(WindowServerTest, DISABLED_ActivationNext) { Window* parent = GetFirstWMRoot(); Window* child1 = NewVisibleWindow(parent, window_manager()); Window* child2 = NewVisibleWindow(parent, window_manager());
diff --git a/components/mus/ws/window_manager_factory_registry.cc b/components/mus/ws/window_manager_factory_registry.cc index f861329..d7bb5762 100644 --- a/components/mus/ws/window_manager_factory_registry.cc +++ b/components/mus/ws/window_manager_factory_registry.cc
@@ -24,7 +24,7 @@ } void WindowManagerFactoryRegistry::Register( - UserId user_id, + const UserId& user_id, mojo::InterfaceRequest<mojom::WindowManagerFactoryService> request) { if (ContainsServiceForUser(user_id)) return; @@ -58,7 +58,7 @@ } bool WindowManagerFactoryRegistry::ContainsServiceForUser( - UserId user_id) const { + const UserId& user_id) const { for (auto& service_ptr : services_) { if (service_ptr->user_id() == user_id) { LOG(ERROR) << "WindowManagerFactoryService already registered for " @@ -93,11 +93,11 @@ connection_manager_->OnFirstWindowManagerFactorySet(); } -void WindowManagerFactoryRegistry::OnActiveUserIdChanged(UserId id) {} +void WindowManagerFactoryRegistry::OnActiveUserIdChanged(const UserId& id) {} -void WindowManagerFactoryRegistry::OnUserIdAdded(UserId id) {} +void WindowManagerFactoryRegistry::OnUserIdAdded(const UserId& id) {} -void WindowManagerFactoryRegistry::OnUserIdRemoved(UserId id) { +void WindowManagerFactoryRegistry::OnUserIdRemoved(const UserId& id) { for (auto iter = services_.begin(); iter != services_.end(); ++iter) { if ((*iter)->user_id() == id) { services_.erase(iter);
diff --git a/components/mus/ws/window_manager_factory_registry.h b/components/mus/ws/window_manager_factory_registry.h index 0bb721b7..efd29a4 100644 --- a/components/mus/ws/window_manager_factory_registry.h +++ b/components/mus/ws/window_manager_factory_registry.h
@@ -36,7 +36,7 @@ ~WindowManagerFactoryRegistry() override; void Register( - UserId user_id, + const UserId& user_id, mojo::InterfaceRequest<mojom::WindowManagerFactoryService> request); std::vector<WindowManagerFactoryService*> GetServices(); @@ -50,15 +50,15 @@ void AddServiceImpl(scoped_ptr<WindowManagerFactoryService> service); - bool ContainsServiceForUser(UserId user_id) const; + bool ContainsServiceForUser(const UserId& user_id) const; void OnWindowManagerFactoryConnectionLost( WindowManagerFactoryService* service); void OnWindowManagerFactorySet(WindowManagerFactoryService* service); // UserIdTrackerObserver: - void OnActiveUserIdChanged(UserId id) override; - void OnUserIdAdded(UserId id) override; - void OnUserIdRemoved(UserId id) override; + void OnActiveUserIdChanged(const UserId& id) override; + void OnUserIdAdded(const UserId& id) override; + void OnUserIdRemoved(const UserId& id) override; // Set to true the first time a valid factory has been found. bool got_valid_factory_ = false;
diff --git a/components/mus/ws/window_manager_factory_service.cc b/components/mus/ws/window_manager_factory_service.cc index a9a522f..f1d2460 100644 --- a/components/mus/ws/window_manager_factory_service.cc +++ b/components/mus/ws/window_manager_factory_service.cc
@@ -12,7 +12,7 @@ WindowManagerFactoryService::WindowManagerFactoryService( WindowManagerFactoryRegistry* registry, - UserId user_id, + const UserId& user_id, mojo::InterfaceRequest<mojom::WindowManagerFactoryService> request) : registry_(registry), user_id_(user_id), @@ -31,7 +31,7 @@ WindowManagerFactoryService::WindowManagerFactoryService( WindowManagerFactoryRegistry* registry, - UserId user_id) + const UserId& user_id) : registry_(registry), user_id_(user_id), binding_(this),
diff --git a/components/mus/ws/window_manager_factory_service.h b/components/mus/ws/window_manager_factory_service.h index 1032174..6e1b6cd 100644 --- a/components/mus/ws/window_manager_factory_service.h +++ b/components/mus/ws/window_manager_factory_service.h
@@ -25,11 +25,11 @@ public: WindowManagerFactoryService( WindowManagerFactoryRegistry* registry, - UserId user_id, + const UserId& user_id, mojo::InterfaceRequest<mojom::WindowManagerFactoryService> request); ~WindowManagerFactoryService() override; - UserId user_id() const { return user_id_; } + const UserId& user_id() const { return user_id_; } mojom::WindowManagerFactory* window_manager_factory() { return window_manager_factory_; @@ -43,7 +43,7 @@ // Used by tests. WindowManagerFactoryService(WindowManagerFactoryRegistry* registry, - UserId user_id); + const UserId& user_id); void SetWindowManagerFactoryImpl(mojom::WindowManagerFactory* factory); void OnConnectionLost();
diff --git a/components/mus/ws/window_manager_state.cc b/components/mus/ws/window_manager_state.cc index 3f0b6f4..f017dca6 100644 --- a/components/mus/ws/window_manager_state.cc +++ b/components/mus/ws/window_manager_state.cc
@@ -6,21 +6,22 @@ #include "components/mus/ws/connection_manager.h" #include "components/mus/ws/server_window.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mus { namespace ws { WindowManagerState::WindowManagerState(Display* display) - : WindowManagerState(display, false, 0u) {} + : WindowManagerState(display, false, mojo::shell::mojom::kRootUserID) {} -WindowManagerState::WindowManagerState(Display* display, uint32_t user_id) +WindowManagerState::WindowManagerState(Display* display, const UserId& user_id) : WindowManagerState(display, true, user_id) {} WindowManagerState::~WindowManagerState() {} WindowManagerState::WindowManagerState(Display* display, bool is_user_id_valid, - uint32_t user_id) + const UserId& user_id) : display_(display), is_user_id_valid_(is_user_id_valid), user_id_(user_id) {
diff --git a/components/mus/ws/window_manager_state.h b/components/mus/ws/window_manager_state.h index 0d9077d..adc30c1 100644 --- a/components/mus/ws/window_manager_state.h +++ b/components/mus/ws/window_manager_state.h
@@ -8,6 +8,7 @@ #include <stdint.h> #include "base/memory/scoped_ptr.h" +#include "components/mus/ws/user_id.h" namespace mus { namespace ws { @@ -22,7 +23,7 @@ public: // Creates a WindowManagerState that can host content from any user. explicit WindowManagerState(Display* display); - WindowManagerState(Display* display, uint32_t user_id); + WindowManagerState(Display* display, const UserId& user_id); ~WindowManagerState(); bool is_user_id_valid() const { return is_user_id_valid_; } @@ -36,14 +37,15 @@ private: friend class Display; - WindowManagerState(Display* display, bool is_user_id_valid, uint32_t user_id); + WindowManagerState(Display* display, bool is_user_id_valid, + const UserId& user_id); Display* display_; // If this was created implicitly by a call // WindowTreeHostFactory::CreateWindowTreeHost(), then |is_user_id_valid_| // is false. const bool is_user_id_valid_; - const uint32_t user_id_; + const UserId user_id_; scoped_ptr<ServerWindow> root_; WindowTree* tree_ = nullptr;
diff --git a/components/plugins/renderer/loadable_plugin_placeholder.cc b/components/plugins/renderer/loadable_plugin_placeholder.cc index f28c1963..b13ece5 100644 --- a/components/plugins/renderer/loadable_plugin_placeholder.cc +++ b/components/plugins/renderer/loadable_plugin_placeholder.cc
@@ -4,7 +4,6 @@ #include "components/plugins/renderer/loadable_plugin_placeholder.h" -#include "base/auto_reset.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/json/string_escape.h" @@ -35,11 +34,6 @@ namespace plugins { -// TODO(tommycli): After a size update, re-check the size after this delay, as -// Blink can report incorrect sizes to plugins while the compositing state is -// dirty. Chosen because it seems to work. -const int kSizeChangeRecheckDelayMilliseconds = 100; - void LoadablePluginPlaceholder::BlockForPowerSaverPoster() { DCHECK(!is_blocked_for_power_saver_poster_); is_blocked_for_power_saver_poster_ = true; @@ -71,7 +65,6 @@ premade_throttler_(nullptr), allow_loading_(false), finished_loading_(false), - in_size_recheck_(false), heuristic_run_before_(premade_throttler_ != nullptr), weak_factory_(this) {} @@ -190,25 +183,48 @@ void LoadablePluginPlaceholder::OnUnobscuredRectUpdate( const gfx::Rect& unobscured_rect) { DCHECK(content::RenderThread::Get()); - if (!power_saver_enabled_ || !finished_loading_) + if (!plugin() || !power_saver_enabled_ || !finished_loading_) return; - // Only update the unobscured rect during the recheck phase. Also early exit - // to prevent reentrancy issues. - if (in_size_recheck_) { - unobscured_rect_ = unobscured_rect; + if (unobscured_rect_ == unobscured_rect) return; - } - if (!size_update_timer_.IsRunning()) { - // TODO(tommycli): We have to post a delayed task to recheck the size, as - // Blink can report wrong sizes for partially obscured plugins while the - // compositing state is dirty. https://crbug.com/343769 - size_update_timer_.Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(kSizeChangeRecheckDelayMilliseconds), - base::Bind(&LoadablePluginPlaceholder::RecheckSizeAndMaybeUnthrottle, - weak_factory_.GetWeakPtr())); + unobscured_rect_ = unobscured_rect; + + float zoom_factor = plugin()->container()->pageZoomFactor(); + int width = roundf(unobscured_rect_.width() / zoom_factor); + int height = roundf(unobscured_rect_.height() / zoom_factor); + + if (is_blocked_for_power_saver_poster_) { + // Adjust poster container padding and dimensions to center play button for + // plugins and plugin posters that have their top or left portions obscured. + int x = roundf(unobscured_rect_.x() / zoom_factor); + int y = roundf(unobscured_rect_.y() / zoom_factor); + std::string script = base::StringPrintf( + "window.resizePoster('%dpx', '%dpx', '%dpx', '%dpx')", x, y, width, + height); + plugin()->web_view()->mainFrame()->executeScript( + blink::WebScriptSource(base::UTF8ToUTF16(script))); + + // On a size update check if we now qualify as a essential plugin. + url::Origin content_origin = url::Origin(GetPluginParams().url); + auto status = render_frame()->GetPeripheralContentStatus( + render_frame()->GetWebFrame()->top()->securityOrigin(), content_origin, + gfx::Size(width, height)); + if (status != content::RenderFrame::CONTENT_STATUS_PERIPHERAL) { + MarkPluginEssential( + heuristic_run_before_ + ? PluginInstanceThrottler::UNTHROTTLE_METHOD_BY_SIZE_CHANGE + : PluginInstanceThrottler::UNTHROTTLE_METHOD_DO_NOT_RECORD); + + if (!heuristic_run_before_ && + status == + content::RenderFrame::CONTENT_STATUS_ESSENTIAL_CROSS_ORIGIN_BIG) { + render_frame()->WhitelistContentOrigin(content_origin); + } + } + + heuristic_run_before_ = true; } } @@ -327,59 +343,4 @@ is_blocked_for_prerendering_; } -void LoadablePluginPlaceholder::RecheckSizeAndMaybeUnthrottle() { - DCHECK(content::RenderThread::Get()); - DCHECK(!in_size_recheck_); - DCHECK(finished_loading_); - - base::AutoReset<bool> recheck_scope(&in_size_recheck_, true); - - if (!plugin()) - return; - - gfx::Rect old_rect = unobscured_rect_; - - // Re-check the size in case the reported size was incorrect. - plugin()->container()->reportGeometry(); - - if (old_rect == unobscured_rect_) - return; - - float zoom_factor = plugin()->container()->pageZoomFactor(); - int width = roundf(unobscured_rect_.width() / zoom_factor); - int height = roundf(unobscured_rect_.height() / zoom_factor); - - if (is_blocked_for_power_saver_poster_) { - // Adjust poster container padding and dimensions to center play button for - // plugins and plugin posters that have their top or left portions obscured. - int x = roundf(unobscured_rect_.x() / zoom_factor); - int y = roundf(unobscured_rect_.y() / zoom_factor); - std::string script = base::StringPrintf( - "window.resizePoster('%dpx', '%dpx', '%dpx', '%dpx')", x, y, width, - height); - plugin()->web_view()->mainFrame()->executeScript( - blink::WebScriptSource(base::UTF8ToUTF16(script))); - - // On a size update check if we now qualify as a essential plugin. - url::Origin content_origin = url::Origin(GetPluginParams().url); - auto status = render_frame()->GetPeripheralContentStatus( - render_frame()->GetWebFrame()->top()->securityOrigin(), content_origin, - gfx::Size(width, height)); - if (status != content::RenderFrame::CONTENT_STATUS_PERIPHERAL) { - MarkPluginEssential( - heuristic_run_before_ - ? PluginInstanceThrottler::UNTHROTTLE_METHOD_BY_SIZE_CHANGE - : PluginInstanceThrottler::UNTHROTTLE_METHOD_DO_NOT_RECORD); - - if (!heuristic_run_before_ && - status == - content::RenderFrame::CONTENT_STATUS_ESSENTIAL_CROSS_ORIGIN_BIG) { - render_frame()->WhitelistContentOrigin(content_origin); - } - } - - heuristic_run_before_ = true; - } -} - } // namespace plugins
diff --git a/components/plugins/renderer/loadable_plugin_placeholder.h b/components/plugins/renderer/loadable_plugin_placeholder.h index bc5114e..5cddaed 100644 --- a/components/plugins/renderer/loadable_plugin_placeholder.h +++ b/components/plugins/renderer/loadable_plugin_placeholder.h
@@ -88,7 +88,6 @@ void UpdateMessage(); bool LoadingBlocked() const; - void RecheckSizeAndMaybeUnthrottle(); // Plugin creation is embedder-specific. virtual blink::WebPlugin* CreatePlugin() = 0; @@ -120,10 +119,7 @@ bool finished_loading_; std::string identifier_; - // Used to prevent re-entrancy during the size recheck for throttled plugins. - bool in_size_recheck_; gfx::Rect unobscured_rect_; - base::OneShotTimer size_update_timer_; // True if the power saver heuristic has already been run on this content. bool heuristic_run_before_;
diff --git a/components/plugins/renderer/webview_plugin.cc b/components/plugins/renderer/webview_plugin.cc index b6ddb46..05611db 100644 --- a/components/plugins/renderer/webview_plugin.cc +++ b/components/plugins/renderer/webview_plugin.cc
@@ -57,7 +57,8 @@ web_view_(WebView::create(this)), finished_loading_(false), focused_(false), - is_painting_(false) { + is_painting_(false), + is_resizing_(false) { // ApplyWebPreferences before making a WebLocalFrame so that the frame sees a // consistent view of our preferences. content::RenderView::ApplyWebPreferences(preferences, web_view_); @@ -199,14 +200,22 @@ const WebRect& unobscured_rect, const WebVector<WebRect>& cut_outs_rects, bool is_visible) { + base::AutoReset<bool> is_resizing( + &is_resizing_, true); + if (static_cast<gfx::Rect>(window_rect) != rect_) { rect_ = window_rect; WebSize newSize(window_rect.width, window_rect.height); web_view_->resize(newSize); } - if (delegate_) + if (delegate_) { delegate_->OnUnobscuredRectUpdate(gfx::Rect(unobscured_rect)); + // The delegate may have dirtied style and layout of the WebView. + // See for example the resizePoster function in plugin_poster.html. + // Run the lifecycle now so that it is clean. + web_view_->updateAllLifecyclePhases(); + } } void WebViewPlugin::updateFocus(bool focused, blink::WebFocusType focus_type) { @@ -293,6 +302,14 @@ } void WebViewPlugin::scheduleAnimation() { + // Resizes must be self-contained: any lifecycle updating must + // be triggerd from within the WebView or this WebViewPlugin. + // This is because this WebViewPlugin is contained in another + // Web View which may be in the middle of updating its lifecycle, + // but after layout is done, and it is illegal to dirty earlier + // lifecycle stages during later ones. + if (is_resizing_) + return; if (container_) { // This should never happen; see also crbug.com/545039 for context. CHECK(!is_painting_);
diff --git a/components/plugins/renderer/webview_plugin.h b/components/plugins/renderer/webview_plugin.h index a2682cb6..4f86b6d 100644 --- a/components/plugins/renderer/webview_plugin.h +++ b/components/plugins/renderer/webview_plugin.h
@@ -178,6 +178,7 @@ bool finished_loading_; bool focused_; bool is_painting_; + bool is_resizing_; }; #endif // COMPONENTS_PLUGINS_RENDERER_WEBVIEW_PLUGIN_H_
diff --git a/components/profile_service/profile_app.cc b/components/profile_service/profile_app.cc index 6ec8c0d..5be0fd9 100644 --- a/components/profile_service/profile_app.cc +++ b/components/profile_service/profile_app.cc
@@ -13,8 +13,8 @@ namespace { -base::LazyInstance<std::map<uint32_t, base::FilePath>> g_user_id_to_data_dir = - LAZY_INSTANCE_INITIALIZER; +base::LazyInstance<std::map<std::string, base::FilePath>> + g_user_id_to_data_dir = LAZY_INSTANCE_INITIALIZER; } // namespace @@ -30,15 +30,15 @@ // static void ProfileApp::AssociateMojoUserIDWithProfileDir( - uint32_t user_id, + const std::string& user_id, const base::FilePath& profile_data_dir) { g_user_id_to_data_dir.Get()[user_id] = profile_data_dir; } void ProfileApp::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); leveldb_service_.reset(new leveldb::LevelDBServiceImpl); @@ -54,7 +54,7 @@ } void ProfileApp::Create(mojo::Connection* connection, - mojo::InterfaceRequest<ProfileService> request) { + ProfileServiceRequest request) { // No, we need one of these per connection. new ProfileServiceImpl(connection, std::move(request), @@ -62,9 +62,8 @@ lock_table_.get()); } -void ProfileApp::Create( - mojo::Connection* connection, - mojo::InterfaceRequest<leveldb::LevelDBService> request) { +void ProfileApp::Create(mojo::Connection* connection, + leveldb::LevelDBServiceRequest request) { leveldb_bindings_.AddBinding(leveldb_service_.get(), std::move(request)); }
diff --git a/components/profile_service/profile_app.h b/components/profile_service/profile_app.h index 80c0130..12f0d4e 100644 --- a/components/profile_service/profile_app.h +++ b/components/profile_service/profile_app.h
@@ -50,24 +50,24 @@ // applications inside of chrome in general; this system won't work once // ProfileApp gets put in its own sandboxed process. static void AssociateMojoUserIDWithProfileDir( - uint32_t user_id, + const std::string& user_id, const base::FilePath& profile_data_dir); private: // |ShellClient| override: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) override; + const std::string& user_id, + uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // |InterfaceFactory<ProfileService>| implementation: void Create(mojo::Connection* connection, - mojo::InterfaceRequest<ProfileService> request) override; + ProfileServiceRequest request) override; // |InterfaceFactory<LevelDBService>| implementation: void Create(mojo::Connection* connection, - mojo::InterfaceRequest<leveldb::LevelDBService> request) override; + leveldb::LevelDBServiceRequest request) override; mojo::TracingImpl tracing_;
diff --git a/components/resource_provider/public/cpp/resource_loader.cc b/components/resource_provider/public/cpp/resource_loader.cc index fc33a36..aa225ba 100644 --- a/components/resource_provider/public/cpp/resource_loader.cc +++ b/components/resource_provider/public/cpp/resource_loader.cc
@@ -12,8 +12,8 @@ #include "mojo/common/common_type_converters.h" #include "mojo/platform_handle/platform_handle_functions.h" #include "mojo/shell/public/cpp/connector.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" namespace resource_provider { namespace {
diff --git a/components/resource_provider/resource_provider_app.cc b/components/resource_provider/resource_provider_app.cc index a3cbbbe..43412393 100644 --- a/components/resource_provider/resource_provider_app.cc +++ b/components/resource_provider/resource_provider_app.cc
@@ -23,7 +23,8 @@ void ResourceProviderApp::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); }
diff --git a/components/resource_provider/resource_provider_app.h b/components/resource_provider/resource_provider_app.h index 0f2d0f08..14b867a 100644 --- a/components/resource_provider/resource_provider_app.h +++ b/components/resource_provider/resource_provider_app.h
@@ -26,7 +26,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // mojo::InterfaceFactory<ResourceProvider>:
diff --git a/components/signin/core/account_id/account_id.cc b/components/signin/core/account_id/account_id.cc index 45dee4d..c2a8a39 100644 --- a/components/signin/core/account_id/account_id.cc +++ b/components/signin/core/account_id/account_id.cc
@@ -9,6 +9,7 @@ #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/memory/singleton.h" +#include "base/strings/string_util.h" #include "base/values.h" #include "google_apis/gaia/gaia_auth_util.h" @@ -49,6 +50,12 @@ AccountId::AccountId(const std::string& gaia_id, const std::string& user_email) : gaia_id_(gaia_id), user_email_(user_email) { + // Fail if e-mail looks similar to GaiaIdKey. + LOG_ASSERT(!base::StartsWith(user_email, kKeyGaiaIdPrefix, + base::CompareCase::SENSITIVE) || + user_email.find('@') != std::string::npos) + << "Bad e-mail: '" << user_email << "' with gaia_id='" << gaia_id << "'"; + // TODO(alemate): DCHECK(!email.empty()); // TODO(alemate): check gaia_id is not empty once it is required. } @@ -98,7 +105,14 @@ } const std::string AccountId::GetGaiaIdKey() const { +#ifdef NDEBUG + if (gaia_id_.empty()) + LOG(FATAL) << "GetGaiaIdKey(): no gaia id for " << Serialize(); + +#else CHECK(!gaia_id_.empty()); +#endif + return std::string(kKeyGaiaIdPrefix) + gaia_id_; }
diff --git a/components/sync_driver.gypi b/components/sync_driver.gypi index d42fb2b..95d4bea19 100644 --- a/components/sync_driver.gypi +++ b/components/sync_driver.gypi
@@ -16,6 +16,7 @@ '../third_party/cacheinvalidation/cacheinvalidation.gyp:cacheinvalidation_proto_cpp', 'data_use_measurement_core', 'invalidation_public', + 'metrics', 'os_crypt', 'signin_core_browser', 'version_info', @@ -48,6 +49,8 @@ 'sync_driver/data_type_manager_observer.h', 'sync_driver/data_type_status_table.cc', 'sync_driver/data_type_status_table.h', + 'sync_driver/device_count_metrics_provider.cc', + 'sync_driver/device_count_metrics_provider.h', 'sync_driver/device_info.cc', 'sync_driver/device_info.h', 'sync_driver/device_info_data_type_controller.cc',
diff --git a/components/sync_driver/BUILD.gn b/components/sync_driver/BUILD.gn index 5ef2241..7730b73 100644 --- a/components/sync_driver/BUILD.gn +++ b/components/sync_driver/BUILD.gn
@@ -27,6 +27,8 @@ "data_type_manager_observer.h", "data_type_status_table.cc", "data_type_status_table.h", + "device_count_metrics_provider.cc", + "device_count_metrics_provider.h", "device_info.cc", "device_info.h", "device_info_data_type_controller.cc", @@ -131,6 +133,7 @@ "//base/third_party/dynamic_annotations", "//components/data_use_measurement/core", "//components/invalidation/public", + "//components/metrics", "//components/os_crypt", "//components/pref_registry", "//components/prefs", @@ -207,6 +210,7 @@ "about_sync_util_unittest.cc", "backend_migrator_unittest.cc", "data_type_manager_impl_unittest.cc", + "device_count_metrics_provider_unittest.cc", "device_info_data_type_controller_unittest.cc", "device_info_service_unittest.cc", "device_info_sync_service_unittest.cc",
diff --git a/components/sync_driver/DEPS b/components/sync_driver/DEPS index 2d6a2a3..468edb1 100644 --- a/components/sync_driver/DEPS +++ b/components/sync_driver/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+components/data_use_measurement/core", "+components/invalidation", + "+components/metrics", "+components/os_crypt", "+components/policy", "+components/pref_registry",
diff --git a/components/sync_driver/device_count_metrics_provider.cc b/components/sync_driver/device_count_metrics_provider.cc new file mode 100644 index 0000000..7467bc6 --- /dev/null +++ b/components/sync_driver/device_count_metrics_provider.cc
@@ -0,0 +1,36 @@ +// 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 "components/sync_driver/device_count_metrics_provider.h" + +#include <algorithm> + +#include "base/metrics/sparse_histogram.h" +#include "components/sync_driver/device_info_tracker.h" + +namespace sync_driver { + +DeviceCountMetricsProvider::DeviceCountMetricsProvider( + const ProvideTrackersCallback& provide_trackers) + : provide_trackers_(provide_trackers) {} + +DeviceCountMetricsProvider::~DeviceCountMetricsProvider() {} + +int DeviceCountMetricsProvider::MaxActiveDeviceCount() const { + std::vector<const sync_driver::DeviceInfoTracker*> trackers; + provide_trackers_.Run(&trackers); + int max = 0; + for (auto* tracker : trackers) { + max = std::max(max, tracker->CountActiveDevices()); + } + return max; +} + +void DeviceCountMetricsProvider::ProvideGeneralMetrics( + metrics::ChromeUserMetricsExtension* uma_proto) { + UMA_HISTOGRAM_SPARSE_SLOWLY("Sync.DeviceCount", + std::min(MaxActiveDeviceCount(), 100)); +} + +} // namespace sync_driver
diff --git a/components/sync_driver/device_count_metrics_provider.h b/components/sync_driver/device_count_metrics_provider.h new file mode 100644 index 0000000..44ff228c --- /dev/null +++ b/components/sync_driver/device_count_metrics_provider.h
@@ -0,0 +1,53 @@ +// 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 COMPONENTS_SYNC_DRIVER_DEVICE_COUNT_METRICS_PROVIDER_H_ +#define COMPONENTS_SYNC_DRIVER_DEVICE_COUNT_METRICS_PROVIDER_H_ + +#include <vector> + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "components/metrics/metrics_provider.h" + +namespace sync_driver { + +class DeviceInfoTracker; + +// A registerable metrics provider that will emit the number of active syncing +// devices a user has upon UMA upload. When there are multiple active profiles +// that are aware of syncable devices, the largest count is used. This approach +// is useful for several reasons. We're significantly interested in "power" +// users that have multiple devices and profiles, and if we skipped emitting any +// metrics in multi profile cases, then we'd be unaware of this entire segment +// of the population. If we emitted multiple metrics, we would have much more +// noise and discerning which metrics actually belonged to non-syncing users +// would be much trickier. +class DeviceCountMetricsProvider : public metrics::MetricsProvider { + public: + typedef base::Callback<void( + std::vector<const sync_driver::DeviceInfoTracker*>* trackers)> + ProvideTrackersCallback; + + explicit DeviceCountMetricsProvider( + const ProvideTrackersCallback& provide_trackers); + ~DeviceCountMetricsProvider() override; + + // MetricsProvider: + void ProvideGeneralMetrics( + metrics::ChromeUserMetricsExtension* uma_proto) override; + + private: + // Returns the max number of active devices across all accounts. + int MaxActiveDeviceCount() const; + + const ProvideTrackersCallback provide_trackers_; + + DISALLOW_COPY_AND_ASSIGN(DeviceCountMetricsProvider); +}; + +} // namespace sync_driver + +#endif // COMPONENTS_SYNC_DRIVER_DEVICE_COUNT_METRICS_PROVIDER_H_
diff --git a/components/sync_driver/device_count_metrics_provider_unittest.cc b/components/sync_driver/device_count_metrics_provider_unittest.cc new file mode 100644 index 0000000..63222f8 --- /dev/null +++ b/components/sync_driver/device_count_metrics_provider_unittest.cc
@@ -0,0 +1,103 @@ +// 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 "components/sync_driver/device_count_metrics_provider.h" + +#include <string> +#include <vector> + +#include "base/bind.h" +#include "base/memory/scoped_ptr.h" +#include "base/test/histogram_tester.h" +#include "components/sync_driver/device_info.h" +#include "components/sync_driver/device_info_tracker.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace sync_driver { + +namespace { + +class FakeTracker : public DeviceInfoTracker { + public: + explicit FakeTracker(const int count) : count_(count) {} + + // DeviceInfoTracker + bool IsSyncing() const override { return false; } + scoped_ptr<DeviceInfo> GetDeviceInfo( + const std::string& client_id) const override { + return scoped_ptr<DeviceInfo>(); + } + ScopedVector<DeviceInfo> GetAllDeviceInfo() const override { + return ScopedVector<DeviceInfo>(); + } + void AddObserver(Observer* observer) override {} + void RemoveObserver(Observer* observer) override {} + int CountActiveDevices() const override { return count_; } + + private: + int count_; +}; + +} // namespace + +class DeviceCountMetricsProviderTest : public testing::Test { + public: + DeviceCountMetricsProviderTest() + : metrics_provider_( + base::Bind(&DeviceCountMetricsProviderTest::GetTrackers, + base::Unretained(this))) {} + + void AddTracker(const int count) { + trackers_.push_back(scoped_ptr<DeviceInfoTracker>(new FakeTracker(count))); + } + void GetTrackers(std::vector<const DeviceInfoTracker*>* trackers) { + for (const auto& tracker : trackers_) { + trackers->push_back(tracker.get()); + } + } + + void TestProvider(int expected_device_count) { + base::HistogramTester histogram_tester; + metrics_provider_.ProvideGeneralMetrics(nullptr); + histogram_tester.ExpectUniqueSample("Sync.DeviceCount", + expected_device_count, 1); + } + + private: + DeviceCountMetricsProvider metrics_provider_; + std::vector<scoped_ptr<DeviceInfoTracker>> trackers_; +}; + +namespace { + +TEST_F(DeviceCountMetricsProviderTest, NoTrackers) { + TestProvider(0); +} + +TEST_F(DeviceCountMetricsProviderTest, SingleTracker) { + AddTracker(2); + TestProvider(2); +} + +TEST_F(DeviceCountMetricsProviderTest, MultipileTrackers) { + AddTracker(1); + AddTracker(5); + AddTracker(-123); + AddTracker(0); + TestProvider(5); +} + +TEST_F(DeviceCountMetricsProviderTest, OnlyNegative) { + AddTracker(-123); + TestProvider(0); +} + +TEST_F(DeviceCountMetricsProviderTest, VeryLarge) { + AddTracker(123456789); + TestProvider(100); +} + +} // namespace + +} // namespace sync_driver
diff --git a/components/sync_driver/device_info_service.cc b/components/sync_driver/device_info_service.cc index 5f1efcc7..8702864 100644 --- a/components/sync_driver/device_info_service.cc +++ b/components/sync_driver/device_info_service.cc
@@ -196,6 +196,11 @@ observers_.RemoveObserver(observer); } +int DeviceInfoService::CountActiveDevices() const { + // TODO(skym): crbug.com/590006: Implementation. + return 0; +} + void DeviceInfoService::NotifyObservers() { FOR_EACH_OBSERVER(Observer, observers_, OnDeviceInfoChange()); }
diff --git a/components/sync_driver/device_info_service.h b/components/sync_driver/device_info_service.h index 8cc1136..4ffc466 100644 --- a/components/sync_driver/device_info_service.h +++ b/components/sync_driver/device_info_service.h
@@ -69,6 +69,7 @@ ScopedVector<sync_driver::DeviceInfo> GetAllDeviceInfo() const override; void AddObserver(Observer* observer) override; void RemoveObserver(Observer* observer) override; + int CountActiveDevices() const override; private: friend class DeviceInfoServiceTest;
diff --git a/components/sync_driver/device_info_sync_service.cc b/components/sync_driver/device_info_sync_service.cc index 009f6aa..31ec504 100644 --- a/components/sync_driver/device_info_sync_service.cc +++ b/components/sync_driver/device_info_sync_service.cc
@@ -5,10 +5,13 @@ #include "components/sync_driver/device_info_sync_service.h" #include <stddef.h> + +#include <algorithm> #include <utility> #include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" +#include "base/time/time.h" #include "components/sync_driver/local_device_info_provider.h" #include "sync/api/sync_change.h" #include "sync/protocol/sync.pb.h" @@ -16,6 +19,8 @@ namespace sync_driver { +using base::Time; +using base::TimeDelta; using syncer::ModelType; using syncer::SyncChange; using syncer::SyncChangeList; @@ -25,6 +30,9 @@ using syncer::SyncErrorFactory; using syncer::SyncMergeResult; +const TimeDelta kDeviceInfoPulseInterval = TimeDelta::FromDays(1); +const TimeDelta kStaleDeviceInfoThreshold = TimeDelta::FromDays(14); + namespace { // TODO(pavely): Remove histogram once device_id mismatch is understood @@ -91,6 +99,7 @@ // UPDATE to INVALID down below if the initial data contains // data matching the local device ID. SyncChange::SyncChangeType change_type = SyncChange::ACTION_ADD; + TimeDelta pulse_delay; size_t num_items_new = 0; size_t num_items_updated = 0; @@ -116,11 +125,13 @@ local_device_info->signin_scoped_device_id()); } + pulse_delay = CalculatePulseDelay(*iter, Time::Now()); // Store the synced device info for the local device only if // it is the same as the local info. Otherwise store the local // device info and issue a change further below after finishing // processing the |initial_sync_data|. - if (synced_local_device_info->Equals(*local_device_info)) { + if (synced_local_device_info->Equals(*local_device_info) && + !pulse_delay.is_zero()) { change_type = SyncChange::ACTION_INVALID; } else { num_items_updated++; @@ -137,16 +148,17 @@ syncer::SyncMergeResult result(type); - // Add SyncData for the local device if it is new or different than - // the synced one, and also add it to the |change_list|. - if (change_type != SyncChange::ACTION_INVALID) { - SyncData local_data = CreateLocalData(local_device_info); - StoreSyncData(local_device_info->guid(), local_data); - - SyncChangeList change_list; - change_list.push_back(SyncChange(FROM_HERE, change_type, local_data)); - result.set_error( - sync_processor_->ProcessSyncChanges(FROM_HERE, change_list)); + // If the SyncData for the local device is new or different then send it + // immediately, otherwise wait until the pulse interval has elapsed from the + // previous update. Regardless of the branch here we setup a timer loop with + // SendLocalData such that we continue pulsing every interval. + if (change_type == SyncChange::ACTION_INVALID) { + pulse_timer_.Start( + FROM_HERE, pulse_delay, + base::Bind(&DeviceInfoSyncService::SendLocalData, + base::Unretained(this), SyncChange::ACTION_UPDATE)); + } else { + SendLocalData(change_type); } result.set_num_items_before_association(1); @@ -264,6 +276,10 @@ observers_.RemoveObserver(observer); } +int DeviceInfoSyncService::CountActiveDevices() const { + return CountActiveDevices(Time::Now()); +} + void DeviceInfoSyncService::NotifyObservers() { FOR_EACH_OBSERVER(Observer, observers_, OnDeviceInfoChange()); } @@ -278,6 +294,7 @@ specifics.set_sync_user_agent(info->sync_user_agent()); specifics.set_device_type(info->device_type()); specifics.set_signin_scoped_device_id(info->signin_scoped_device_id()); + specifics.set_last_updated_timestamp(syncer::TimeToProtoTime(Time::Now())); return CreateLocalData(entity); } @@ -324,4 +341,66 @@ } } +// static +Time DeviceInfoSyncService::GetLastUpdateTime(const SyncData& device_info) { + if (device_info.GetSpecifics().device_info().has_last_updated_timestamp()) { + return syncer::ProtoTimeToTime( + device_info.GetSpecifics().device_info().last_updated_timestamp()); + } else if (!device_info.IsLocal()) { + // If there is no |last_updated_timestamp| present, fallback to mod time. + return syncer::SyncDataRemote(device_info).GetModifiedTime(); + } else { + // We shouldn't reach this point for remote data, so this means we're likely + // looking at the local device info. Using a long ago time is perfect, since + // the desired behavior is to update/pulse our data as soon as possible. + return Time(); + } +} + +// static +TimeDelta DeviceInfoSyncService::GetLastUpdateAge(const SyncData& device_info, + const Time now) { + // Don't allow negative ages for data modified in the future, use age of 0. + return std::max(TimeDelta(), now - GetLastUpdateTime(device_info)); +} + +// static +TimeDelta DeviceInfoSyncService::CalculatePulseDelay( + const SyncData& device_info, + const Time now) { + // Don't allow negative delays for very stale data, use delay of 0. + return std::max(TimeDelta(), kDeviceInfoPulseInterval - + GetLastUpdateAge(device_info, now)); +} + +void DeviceInfoSyncService::SendLocalData( + const SyncChange::SyncChangeType change_type) { + DCHECK_NE(change_type, SyncChange::ACTION_INVALID); + + const DeviceInfo* device_info = + local_device_info_provider_->GetLocalDeviceInfo(); + const SyncData& data = CreateLocalData(device_info); + StoreSyncData(device_info->guid(), data); + + SyncChangeList change_list; + change_list.push_back(SyncChange(FROM_HERE, change_type, data)); + sync_processor_->ProcessSyncChanges(FROM_HERE, change_list); + + pulse_timer_.Start( + FROM_HERE, kDeviceInfoPulseInterval, + base::Bind(&DeviceInfoSyncService::SendLocalData, base::Unretained(this), + SyncChange::ACTION_UPDATE)); +} + +int DeviceInfoSyncService::CountActiveDevices(const Time now) const { + int count = 0; + for (const auto& pair : all_data_) { + const TimeDelta age = GetLastUpdateAge(pair.second, now); + if (age < kStaleDeviceInfoThreshold) { + count++; + } + } + return count; +} + } // namespace sync_driver
diff --git a/components/sync_driver/device_info_sync_service.h b/components/sync_driver/device_info_sync_service.h index 6c82a12..fd75beab 100644 --- a/components/sync_driver/device_info_sync_service.h +++ b/components/sync_driver/device_info_sync_service.h
@@ -14,7 +14,10 @@ #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/observer_list.h" +#include "base/time/time.h" +#include "base/timer/timer.h" #include "components/sync_driver/device_info_tracker.h" +#include "sync/api/sync_change.h" #include "sync/api/sync_change_processor.h" #include "sync/api/sync_data.h" #include "sync/api/sync_error_factory.h" @@ -24,6 +27,13 @@ class LocalDeviceInfoProvider; +// The delay between periodic updates to the entry corresponding to this device. +extern const base::TimeDelta kDeviceInfoPulseInterval; + +// The amount of time a device can go without an updates before we consider it +// stale/inactive, and start ignoring it for active device counts. +extern const base::TimeDelta kStaleDeviceInfoThreshold; + // SyncableService implementation for DEVICE_INFO model type. class DeviceInfoSyncService : public syncer::SyncableService, public DeviceInfoTracker { @@ -51,8 +61,11 @@ ScopedVector<DeviceInfo> GetAllDeviceInfo() const override; void AddObserver(Observer* observer) override; void RemoveObserver(Observer* observer) override; + int CountActiveDevices() const override; private: + friend class DeviceInfoSyncServiceTest; + // Create SyncData from local DeviceInfo. syncer::SyncData CreateLocalData(const DeviceInfo* info); // Create SyncData from EntitySpecifics. @@ -69,6 +82,33 @@ // Notify all registered observers. void NotifyObservers(); + // Find the timestamp for the last time this |device_info| was edited. + static base::Time GetLastUpdateTime(const syncer::SyncData& device_info); + + // Finds the amount of time since this |device_info| was last edited. If this + // |device_info| claims to have been edited in the future, the smallest age + // this returns will be an age of zero and never negative. + static base::TimeDelta GetLastUpdateAge(const syncer::SyncData& device_info, + const base::Time now); + + // Determines the amount of time before we should pulse and update the entity + // that corresponds to this device. This value is calculated by looking at + // time |now|, the last updated timestamp in |device_info|, and using the + // pulse interval. The smallest delay this will ever return will be the + // instant delay and never negative. + static base::TimeDelta CalculatePulseDelay( + const syncer::SyncData& device_info, + const base::Time now); + + // Sends a copy of the current device's state to the processor/sync. + void SendLocalData(const syncer::SyncChange::SyncChangeType change_type); + + // Counts the number of active devices relative to |now|. The activeness of a + // device depends on the amount of time since it was updated, which means + // comparing it against the current time. |now| is passed into this method to + // allow unit tests to control expected results. + int CountActiveDevices(const base::Time now) const; + // |local_device_info_provider_| isn't owned. const LocalDeviceInfoProvider* const local_device_info_provider_; @@ -84,6 +124,9 @@ // Registered observers, not owned. base::ObserverList<Observer, true> observers_; + // Used to update our local device info once every pulse interval. + base::OneShotTimer pulse_timer_; + DISALLOW_COPY_AND_ASSIGN(DeviceInfoSyncService); };
diff --git a/components/sync_driver/device_info_sync_service_unittest.cc b/components/sync_driver/device_info_sync_service_unittest.cc index 2dffcbe..02b76232 100644 --- a/components/sync_driver/device_info_sync_service_unittest.cc +++ b/components/sync_driver/device_info_sync_service_unittest.cc
@@ -9,6 +9,7 @@ #include <string> +#include "base/message_loop/message_loop.h" #include "components/sync_driver/local_device_info_provider_mock.h" #include "sync/api/sync_change.h" #include "sync/api/sync_change_processor.h" @@ -18,6 +19,8 @@ #include "sync/util/time.h" #include "testing/gtest/include/gtest/gtest.h" +using base::Time; +using base::TimeDelta; using syncer::AttachmentIdList; using syncer::AttachmentServiceProxyForTest; using syncer::ModelType; @@ -78,6 +81,8 @@ SyncChangeList change_list_; }; +} // namespace + class DeviceInfoSyncServiceTest : public testing::Test, public DeviceInfoTracker::Observer { public: @@ -111,9 +116,10 @@ return scoped_ptr<SyncErrorFactory>(new SyncErrorFactoryMock()); } + // Default |last_updated_timestamp| to now to avoid pulse update on merge. SyncData CreateRemoteData(const std::string& client_id, const std::string& client_name, - int64_t backup_timestamp = 0) { + Time last_updated_timestamp = Time::Now()) { sync_pb::EntitySpecifics entity; sync_pb::DeviceInfoSpecifics& specifics = *entity.mutable_device_info(); @@ -123,11 +129,10 @@ specifics.set_sync_user_agent("Chrome 10k"); specifics.set_device_type(sync_pb::SyncEnums_DeviceType_TYPE_LINUX); specifics.set_signin_scoped_device_id("device_id"); + specifics.set_last_updated_timestamp( + syncer::TimeToProtoTime(last_updated_timestamp)); - return SyncData::CreateRemoteData(1, - entity, - base::Time(), - AttachmentIdList(), + return SyncData::CreateRemoteData(1, entity, Time(), AttachmentIdList(), AttachmentServiceProxyForTest::Create()); } @@ -148,12 +153,29 @@ } protected: + // Private method wrappers through friend class. + TimeDelta CalculatePulseDelay(const syncer::SyncData& data, const Time now) { + return sync_service_->CalculatePulseDelay(data, now); + } + int CountActiveDevices(const Time now) { + return sync_service_->CountActiveDevices(now); + } + void StoreSyncData(const std::string& client_id, + const syncer::SyncData& sync_data) { + sync_service_->StoreSyncData(client_id, sync_data); + } + + // Needs to be created for OneShotTimer to grab the current task runner. + base::MessageLoop message_loop_; + int num_device_info_changed_callbacks_; scoped_ptr<LocalDeviceInfoProviderMock> local_device_; scoped_ptr<DeviceInfoSyncService> sync_service_; scoped_ptr<TestChangeProcessor> sync_processor_; }; +namespace { + // Sync with empty initial data. TEST_F(DeviceInfoSyncServiceTest, StartSyncEmptyInitialData) { EXPECT_FALSE(sync_service_->IsSyncing()); @@ -414,6 +436,165 @@ EXPECT_EQ(0, num_device_info_changed_callbacks_); } +// While the initial data will match the current device, the last modified time +// should be greater than the threshold and cause an update anyways. +TEST_F(DeviceInfoSyncServiceTest, StartSyncMatchingButStale) { + SyncDataList sync_data; + sync_data.push_back(CreateRemoteData("guid_1", "foo_1", Time())); + SyncMergeResult merge_result = sync_service_->MergeDataAndStartSyncing( + syncer::DEVICE_INFO, sync_data, PassProcessor(), + CreateAndPassSyncErrorFactory()); + + EXPECT_EQ(1U, sync_processor_->change_list_size()); + EXPECT_EQ(SyncChange::ACTION_UPDATE, sync_processor_->change_type_at(0)); + EXPECT_EQ("guid_1", sync_processor_->cache_guid_at(0)); + EXPECT_EQ("client_1", sync_processor_->client_name_at(0)); +} + +// Verifies when the device info has not been update for exactly the pulse +// interval, it should be updated right now. +TEST_F(DeviceInfoSyncServiceTest, CalculatePulseDelayExactlyStale) { + const SyncData data = CreateRemoteData("guid_1", "foo_1", Time()); + const TimeDelta actual = + CalculatePulseDelay(data, Time() + kStaleDeviceInfoThreshold); + EXPECT_EQ(TimeDelta(), actual); +} + +// Verifies when the device info has not been updated for longer than the pulse +// interval, it should be updated right now. +TEST_F(DeviceInfoSyncServiceTest, CalculatePulseDelayVeryStale) { + const SyncData data = CreateRemoteData("guid_1", "foo_1", Time()); + const TimeDelta actual = CalculatePulseDelay( + data, Time() + kDeviceInfoPulseInterval + TimeDelta::FromDays(1)); + EXPECT_EQ(TimeDelta(), actual); +} + +// Verifies when the device info has not been updated for shorter than the pulse +// interval, it should be updated in the future. +TEST_F(DeviceInfoSyncServiceTest, CalculatePulseDelayMiddle) { + // This is only going to work while kStaleDeviceInfoThreshold is even. + const TimeDelta half = kDeviceInfoPulseInterval / 2; + const SyncData data = CreateRemoteData("guid_1", "foo_1", Time()); + const TimeDelta actual = CalculatePulseDelay(data, Time() + half); + EXPECT_EQ(half, actual); +} + +// Verifies when the device info was last updated right now, it should be +// updated in exactly one pulse interval. +TEST_F(DeviceInfoSyncServiceTest, CalculatePulseDelayCurrent) { + const SyncData data = CreateRemoteData("guid_1", "foo_1", Time()); + EXPECT_EQ(kDeviceInfoPulseInterval, CalculatePulseDelay(data, Time())); +} + +// Verifies when the device info claims to have been updated in the future, it +// should be updated in exactly one pulse interval. +TEST_F(DeviceInfoSyncServiceTest, CalculatePulseDelayFuture) { + const SyncData data = + CreateRemoteData("guid_1", "foo_1", Time() + kDeviceInfoPulseInterval); + const TimeDelta actual = CalculatePulseDelay(data, Time()); + EXPECT_EQ(kDeviceInfoPulseInterval, actual); +} + +// Verifies the number of active devices is 0 when there is no data. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesNone) { + EXPECT_EQ(0, CountActiveDevices(Time())); +} + +// Verifies the number of active devices when we have one active device info. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesOneActive) { + StoreSyncData("active", CreateRemoteData("active", "active", Time())); + EXPECT_EQ(1, CountActiveDevices(Time() + (kStaleDeviceInfoThreshold / 2))); +} + +// Verifies the number of active devices when we have one stale that hasn't been +// updated for exactly the threshold is considered stale. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesExactlyStale) { + StoreSyncData("stale", CreateRemoteData("stale", "stale", Time())); + EXPECT_EQ(0, CountActiveDevices(Time() + kStaleDeviceInfoThreshold)); +} + +// Verifies the number of active devices when we have a mix of active and stale +// device infos. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesManyMix) { + StoreSyncData("stale", CreateRemoteData("stale", "stale", Time())); + StoreSyncData("active1", + CreateRemoteData("active1", "active1", + Time() + kStaleDeviceInfoThreshold / 2)); + StoreSyncData("active2", + CreateRemoteData("active2", "active2", + Time() + kStaleDeviceInfoThreshold)); + EXPECT_EQ(2, CountActiveDevices(Time() + kStaleDeviceInfoThreshold)); +} + +// Verifies the number of active devices when we have many that are stale. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesManyStale) { + StoreSyncData("stale1", CreateRemoteData("stale1", "stale1", Time())); + StoreSyncData("stale2", CreateRemoteData("stale2", "stale2", + Time() + kStaleDeviceInfoThreshold)); + StoreSyncData("stale3", + CreateRemoteData("stale3", "stale3", + Time() + (kStaleDeviceInfoThreshold * 2))); + EXPECT_EQ(0, CountActiveDevices(Time() + (kStaleDeviceInfoThreshold * 3))); +} + +// Verifies the number of active devices when we have devices that claim to have +// been updated in the future. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesFuture) { + StoreSyncData("now", CreateRemoteData("now", "now", + Time() + kStaleDeviceInfoThreshold)); + StoreSyncData("future", + CreateRemoteData("future", "future", + Time() + (kStaleDeviceInfoThreshold * 10))); + EXPECT_EQ(2, CountActiveDevices(Time() + kStaleDeviceInfoThreshold)); +} + +// Verifies the number of active devices when they don't have an updated time +// set, and fallback to checking the SyncData's last modified time. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesModifiedTime) { + sync_pb::EntitySpecifics stale_entity; + sync_pb::DeviceInfoSpecifics& stale_specifics = + *stale_entity.mutable_device_info(); + stale_specifics.set_cache_guid("stale"); + StoreSyncData("stale", SyncData::CreateRemoteData( + 1, stale_entity, Time(), AttachmentIdList(), + AttachmentServiceProxyForTest::Create())); + + sync_pb::EntitySpecifics active_entity; + sync_pb::DeviceInfoSpecifics& active_specifics = + *active_entity.mutable_device_info(); + active_specifics.set_cache_guid("active"); + StoreSyncData( + "active", + SyncData::CreateRemoteData( + 1, active_entity, Time() + (kStaleDeviceInfoThreshold / 2), + AttachmentIdList(), AttachmentServiceProxyForTest::Create())); + + EXPECT_EQ(1, CountActiveDevices(Time() + kStaleDeviceInfoThreshold)); +} + +// Verifies the number of active devices when they don't have an updated time +// and they're not remote, which means we cannot use SyncData's last modified +// time. If now is close to uninitialized time, should still be active. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesLocalActive) { + sync_pb::EntitySpecifics entity; + sync_pb::DeviceInfoSpecifics& specifics = *entity.mutable_device_info(); + specifics.set_cache_guid("active"); + StoreSyncData("active", + SyncData::CreateLocalData("active", "active", entity)); + EXPECT_EQ(1, CountActiveDevices(Time() + (kStaleDeviceInfoThreshold / 2))); +} + +// Verifies the number of active devices when they don't have an updated time +// and they're not remote, which means we cannot use SyncData's last modified +// time. If now is far from uninitialized time, should be stale. +TEST_F(DeviceInfoSyncServiceTest, CountActiveDevicesLocalStale) { + sync_pb::EntitySpecifics entity; + sync_pb::DeviceInfoSpecifics& specifics = *entity.mutable_device_info(); + specifics.set_cache_guid("stale"); + StoreSyncData("stale", SyncData::CreateLocalData("stale", "stale", entity)); + EXPECT_EQ(0, CountActiveDevices(Time() + kStaleDeviceInfoThreshold)); +} + } // namespace } // namespace sync_driver
diff --git a/components/sync_driver/device_info_tracker.h b/components/sync_driver/device_info_tracker.h index b15e738..f506330 100644 --- a/components/sync_driver/device_info_tracker.h +++ b/components/sync_driver/device_info_tracker.h
@@ -37,6 +37,8 @@ virtual void AddObserver(Observer* observer) = 0; // Unregisters an observer. virtual void RemoveObserver(Observer* observer) = 0; + // Returns the count of active devices. + virtual int CountActiveDevices() const = 0; }; } // namespace sync_driver
diff --git a/components/sync_sessions/sessions_sync_manager.h b/components/sync_sessions/sessions_sync_manager.h index 2c990e04..ba48b24b 100644 --- a/components/sync_sessions/sessions_sync_manager.h +++ b/components/sync_sessions/sessions_sync_manager.h
@@ -113,9 +113,8 @@ FaviconCache* GetFaviconCache(); // Triggers garbage collection of stale sessions (as defined by - // |stale_session_threshold_days_|). This is called automatically every - // time we start up (via AssociateModels) and when new sessions data is - // downloaded (sync cycles complete). + // |stale_session_threshold_days_|). This is called every time we see new + // sessions data downloaded (sync cycles complete). void DoGarbageCollection(); private:
diff --git a/components/test_runner/layout_dump.cc b/components/test_runner/layout_dump.cc index 02a90ee..3c4c84d 100644 --- a/components/test_runner/layout_dump.cc +++ b/components/test_runner/layout_dump.cc
@@ -78,11 +78,6 @@ WebFrameContentDumper::LayoutAsTextNormal; if (flags.is_printing) layout_text_behavior |= WebFrameContentDumper::LayoutAsTextPrinting; - if (flags.debug_render_tree) - layout_text_behavior |= WebFrameContentDumper::LayoutAsTextDebug; - if (flags.dump_line_box_trees) - layout_text_behavior |= - WebFrameContentDumper::LayoutAsTextWithLineTrees; result = WebFrameContentDumper::dumpLayoutTreeAsText(frame, layout_text_behavior) .utf8();
diff --git a/components/test_runner/layout_dump_flags.h b/components/test_runner/layout_dump_flags.h index 188c1be3..06855ee 100644 --- a/components/test_runner/layout_dump_flags.h +++ b/components/test_runner/layout_dump_flags.h
@@ -13,17 +13,13 @@ bool dump_as_markup, bool dump_child_frames_as_markup, bool dump_child_frame_scroll_positions, - bool is_printing, - bool dump_line_box_trees, - bool debug_render_tree) + bool is_printing) : dump_as_text(dump_as_text), dump_child_frames_as_text(dump_child_frames_as_text), dump_as_markup(dump_as_text), dump_child_frames_as_markup(dump_child_frames_as_markup), dump_child_frame_scroll_positions(dump_child_frame_scroll_positions), - is_printing(is_printing), - dump_line_box_trees(dump_line_box_trees), - debug_render_tree(debug_render_tree) {} + is_printing(is_printing) {} // Default constructor needed for IPC. // @@ -64,10 +60,6 @@ // If true, layout is to target printed pages. bool is_printing; - - // Extra flags for debugging layout tests. - bool dump_line_box_trees; - bool debug_render_tree; }; } // namespace test_runner
diff --git a/components/test_runner/mock_web_speech_recognizer.cc b/components/test_runner/mock_web_speech_recognizer.cc index 9504fea..e80958f 100644 --- a/components/test_runner/mock_web_speech_recognizer.cc +++ b/components/test_runner/mock_web_speech_recognizer.cc
@@ -111,22 +111,18 @@ // Task for tidying up after recognition task has ended. class EndedTask : public MockWebSpeechRecognizer::Task { public: - EndedTask(MockWebSpeechRecognizer* mock, - blink::WebSpeechRecognitionHandle handle) - : MockWebSpeechRecognizer::Task(mock), handle_(handle) {} + EndedTask(MockWebSpeechRecognizer* mock) + : MockWebSpeechRecognizer::Task(mock) {} ~EndedTask() override {} void run() override { - // Reset recognizer's handle if it hasn't been replaced. - if (recognizer_->Handle() == handle_) - recognizer_->Handle().reset(); - handle_.reset(); + blink::WebSpeechRecognitionHandle handle = recognizer_->Handle(); + recognizer_->Handle().reset(); + recognizer_->Client()->didEnd(handle); } private: - blink::WebSpeechRecognitionHandle handle_; - DISALLOW_COPY_AND_ASSIGN(EndedTask); }; @@ -175,9 +171,7 @@ new ClientCallTask(this, &blink::WebSpeechRecognizerClient::didEndSound)); task_queue_.push_back( new ClientCallTask(this, &blink::WebSpeechRecognizerClient::didEndAudio)); - task_queue_.push_back( - new ClientCallTask(this, &blink::WebSpeechRecognizerClient::didEnd)); - task_queue_.push_back(new EndedTask(this, handle_)); + task_queue_.push_back(new EndedTask(this)); StartTaskQueue(); } @@ -200,9 +194,7 @@ ClearTaskQueue(); was_aborted_ = true; - task_queue_.push_back( - new ClientCallTask(this, &blink::WebSpeechRecognizerClient::didEnd)); - task_queue_.push_back(new EndedTask(this, handle_)); + task_queue_.push_back(new EndedTask(this)); StartTaskQueue(); } @@ -239,9 +231,7 @@ ClearTaskQueue(); task_queue_.push_back(new ErrorTask(this, code, message)); - task_queue_.push_back( - new ClientCallTask(this, &blink::WebSpeechRecognizerClient::didEnd)); - task_queue_.push_back(new EndedTask(this, handle_)); + task_queue_.push_back(new EndedTask(this)); StartTaskQueue(); }
diff --git a/components/test_runner/test_runner.cc b/components/test_runner/test_runner.cc index 836924e..b85bc61 100644 --- a/components/test_runner/test_runner.cc +++ b/components/test_runner/test_runner.cc
@@ -1663,9 +1663,7 @@ false, // dump_as_markup false, // dump_child_frames_as_markup false, // dump_child_frame_scroll_positions - false, // is_printing - false, // dump_line_box_trees - false), // debug_render_tree + false), // is_printing test_interfaces_(interfaces), delegate_(nullptr), web_view_(nullptr),
diff --git a/components/user_manager/known_user.cc b/components/user_manager/known_user.cc index 973e12b..8be385c 100644 --- a/components/user_manager/known_user.cc +++ b/components/user_manager/known_user.cc
@@ -46,11 +46,10 @@ const char kGaiaIdMigration[] = "gaia_id_migration"; PrefService* GetLocalState() { - UserManager* user_manager = UserManager::Get(); - if (user_manager) - return user_manager->GetLocalState(); + if (!UserManager::IsInitialized()) + return nullptr; - return nullptr; + return UserManager::Get()->GetLocalState(); } // Checks if values in |dict| correspond with |account_id| identity. @@ -72,7 +71,11 @@ // Fills relevant |dict| values based on |account_id|. void UpdateIdentity(const AccountId& account_id, base::DictionaryValue& dict) { - dict.SetString(kCanonicalEmail, account_id.GetUserEmail()); + if (!account_id.GetUserEmail().empty()) + dict.SetString(kCanonicalEmail, account_id.GetUserEmail()); + + if (!account_id.GetGaiaId().empty()) + dict.SetString(kGAIAIdKey, account_id.GetGaiaId()); } } // namespace @@ -86,9 +89,8 @@ return false; // UserManager is usually NULL in unit tests. - UserManager* user_manager = UserManager::Get(); - if (user_manager && - user_manager->IsUserNonCryptohomeDataEphemeral(account_id)) + if (UserManager::IsInitialized() && + UserManager::Get()->IsUserNonCryptohomeDataEphemeral(account_id)) return false; const base::ListValue* known_users = local_state->GetList(kKnownUsers); @@ -114,9 +116,8 @@ return; // UserManager is usually NULL in unit tests. - UserManager* user_manager = UserManager::Get(); - if (user_manager && - user_manager->IsUserNonCryptohomeDataEphemeral(account_id)) + if (UserManager::IsInitialized() && + UserManager::Get()->IsUserNonCryptohomeDataEphemeral(account_id)) return; ListPrefUpdate update(local_state, kKnownUsers); @@ -219,9 +220,10 @@ return EmptyAccountId(); AccountId result(EmptyAccountId()); - UserManager* user_manager = UserManager::Get(); - if (user_manager && - user_manager->GetPlatformKnownUserId(user_email, gaia_id, &result)) { + // UserManager is usually NULL in unit tests. + if (UserManager::IsInitialized() && + UserManager::Get()->GetPlatformKnownUserId(user_email, gaia_id, + &result)) { return result; } @@ -256,6 +258,29 @@ : AccountId::FromUserEmailGaiaId(user_email, gaia_id)); } +std::vector<AccountId> GetKnownAccountIds() { + std::vector<AccountId> result; + PrefService* local_state = GetLocalState(); + + // Local State may not be initialized in tests. + if (!local_state) + return result; + + const base::ListValue* known_users = local_state->GetList(kKnownUsers); + for (size_t i = 0; i < known_users->GetSize(); ++i) { + const base::DictionaryValue* element = nullptr; + if (known_users->GetDictionary(i, &element)) { + std::string email; + std::string gaia_id; + const bool has_email = element->GetString(kCanonicalEmail, &email); + const bool has_gaia_id = element->GetString(kGAIAIdKey, &gaia_id); + if (has_email || has_gaia_id) + result.push_back(AccountId::FromUserEmailGaiaId(email, gaia_id)); + } + } + return result; +} + bool GetGaiaIdMigrationStatus(const AccountId& account_id, const std::string& subsystem) { bool migrated = false;
diff --git a/components/user_manager/known_user.h b/components/user_manager/known_user.h index aa02b2f..8a16cbe 100644 --- a/components/user_manager/known_user.h +++ b/components/user_manager/known_user.h
@@ -6,6 +6,7 @@ #define COMPONENTS_USER_MANAGER_KNOWN_USER_H_ #include <string> +#include <vector> #include "components/user_manager/user_manager_export.h" @@ -68,6 +69,9 @@ const std::string& path, const int in_value); +// Returns the list of known AccountIds. +std::vector<AccountId> USER_MANAGER_EXPORT GetKnownAccountIds(); + // This call forms full account id of a known user by email and (optionally) // gaia_id. // This is a temporary call while migrating to AccountId.
diff --git a/components/webcrypto/BUILD.gn b/components/webcrypto/BUILD.gn index 0db4ccc..d824d54 100644 --- a/components/webcrypto/BUILD.gn +++ b/components/webcrypto/BUILD.gn
@@ -121,7 +121,7 @@ } # Tests the import of PKCS8 formatted EC keys. -fuzzer_test("ec_import_key_pkcs8_fuzzer") { +fuzzer_test("webcrypto_ec_import_key_pkcs8_fuzzer") { sources = [ "ec_import_key_pkcs8_fuzzer.cc", ] @@ -133,7 +133,7 @@ } # Tests the import of SPKI formatted EC keys. -fuzzer_test("ec_import_key_spki_fuzzer") { +fuzzer_test("webcrypto_ec_import_key_spki_fuzzer") { sources = [ "ec_import_key_spki_fuzzer.cc", ] @@ -145,7 +145,7 @@ } # Tests the import of PKCS8 formatted RSA keys. -fuzzer_test("rsa_import_key_pkcs8_fuzzer") { +fuzzer_test("webcrypto_rsa_import_key_pkcs8_fuzzer") { sources = [ "rsa_import_key_pkcs8_fuzzer.cc", ] @@ -157,7 +157,7 @@ } # Tests the import of SPKI formatted RSA keys. -fuzzer_test("rsa_import_key_spki_fuzzer") { +fuzzer_test("webcrypto_rsa_import_key_spki_fuzzer") { sources = [ "rsa_import_key_pkcs8_fuzzer.cc", ]
diff --git a/content/browser/browser_context.cc b/content/browser/browser_context.cc index 21817d6..10db382 100644 --- a/content/browser/browser_context.cc +++ b/content/browser/browser_context.cc
@@ -10,6 +10,7 @@ #include <limits> #include <utility> +#include "base/guid.h" #include "base/lazy_instance.h" #include "base/rand_util.h" #include "build/build_config.h" @@ -44,9 +45,9 @@ #if !defined(OS_IOS) namespace { -base::LazyInstance<std::set<uint32_t>> g_used_user_ids = +base::LazyInstance<std::set<std::string>> g_used_user_ids = LAZY_INSTANCE_INITIALIZER; -base::LazyInstance<std::vector<std::pair<BrowserContext*, uint32_t>>> +base::LazyInstance<std::vector<std::pair<BrowserContext*, std::string>>> g_context_to_user_id = LAZY_INSTANCE_INITIALIZER; // Key names on BrowserContext. @@ -336,13 +337,10 @@ void BrowserContext::Initialize( BrowserContext* browser_context, const base::FilePath& path) { - // Associate a random unsigned 32 bit number with |browser_context|. This - // becomes the mojo user id for this BrowserContext. - uint32_t new_id = static_cast<uint32_t>(base::RandGenerator(UINT32_MAX)); - while ((new_id == 0) || - (g_used_user_ids.Get().find(new_id) != g_used_user_ids.Get().end())) { - new_id = static_cast<uint32_t>(base::RandGenerator(UINT32_MAX)); - } + // Generate a GUID for |browser_context| to use as the Mojo user id. + std::string new_id = base::GenerateGUID(); + while (g_used_user_ids.Get().find(new_id) != g_used_user_ids.Get().end()) + new_id = base::GenerateGUID(); g_used_user_ids.Get().insert(new_id); g_context_to_user_id.Get().push_back(std::make_pair(browser_context, new_id)); @@ -352,7 +350,8 @@ new base::SupportsUserData::Data); } -uint32_t BrowserContext::GetMojoUserIdFor(BrowserContext* browser_context) { +const std::string& BrowserContext::GetMojoUserIdFor( + BrowserContext* browser_context) { CHECK(browser_context->GetUserData(kMojoWasInitialized)) << "Attempting to get the mojo user id for a BrowserContext that was " << "never Initialize()ed."; @@ -360,7 +359,7 @@ auto it = std::find_if( g_context_to_user_id.Get().begin(), g_context_to_user_id.Get().end(), - [&browser_context](const std::pair<BrowserContext*, uint32_t>& p) { + [&browser_context](const std::pair<BrowserContext*, std::string>& p) { return p.first == browser_context; }); CHECK(it != g_context_to_user_id.Get().end()); return it->second;
diff --git a/content/browser/cache_storage/cache_storage.cc b/content/browser/cache_storage/cache_storage.cc index 1a1f0517..c14a923 100644 --- a/content/browser/cache_storage/cache_storage.cc +++ b/content/browser/cache_storage/cache_storage.cc
@@ -67,16 +67,15 @@ // Handles the loading and clean up of CacheStorageCache objects. class CacheStorage::CacheLoader { public: - typedef base::Callback<void(const scoped_refptr<CacheStorageCache>&)> - CacheCallback; + typedef base::Callback<void(scoped_refptr<CacheStorageCache>)> CacheCallback; typedef base::Callback<void(bool)> BoolCallback; typedef base::Callback<void(scoped_ptr<std::vector<std::string>>)> StringVectorCallback; CacheLoader( base::SequencedTaskRunner* cache_task_runner, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + storage::QuotaManagerProxy* quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context, const GURL& origin) : cache_task_runner_(cache_task_runner), @@ -114,7 +113,10 @@ protected: scoped_refptr<base::SequencedTaskRunner> cache_task_runner_; scoped_refptr<net::URLRequestContextGetter> request_context_getter_; - scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_; + + // Owned by CacheStorage which owns this. + storage::QuotaManagerProxy* quota_manager_proxy_; + base::WeakPtr<storage::BlobStorageContext> blob_context_; GURL origin_; }; @@ -125,12 +127,11 @@ // cache is deleted. class CacheStorage::MemoryLoader : public CacheStorage::CacheLoader { public: - MemoryLoader( - base::SequencedTaskRunner* cache_task_runner, - const scoped_refptr<net::URLRequestContextGetter>& request_context, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, - base::WeakPtr<storage::BlobStorageContext> blob_context, - const GURL& origin) + MemoryLoader(base::SequencedTaskRunner* cache_task_runner, + scoped_refptr<net::URLRequestContextGetter> request_context, + storage::QuotaManagerProxy* quota_manager_proxy, + base::WeakPtr<storage::BlobStorageContext> blob_context, + const GURL& origin) : CacheLoader(cache_task_runner, request_context, quota_manager_proxy, @@ -147,7 +148,7 @@ const CacheCallback& callback) override { scoped_refptr<CacheStorageCache> cache = CreateCache(cache_name); cache_refs_.insert(std::make_pair(cache_name, cache)); - callback.Run(cache); + callback.Run(std::move(cache)); } void CleanUpDeletedCache(const std::string& cache_name, @@ -180,13 +181,12 @@ class CacheStorage::SimpleCacheLoader : public CacheStorage::CacheLoader { public: - SimpleCacheLoader( - const base::FilePath& origin_path, - base::SequencedTaskRunner* cache_task_runner, - const scoped_refptr<net::URLRequestContextGetter>& request_context, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, - base::WeakPtr<storage::BlobStorageContext> blob_context, - const GURL& origin) + SimpleCacheLoader(const base::FilePath& origin_path, + base::SequencedTaskRunner* cache_task_runner, + scoped_refptr<net::URLRequestContextGetter> request_context, + storage::QuotaManagerProxy* quota_manager_proxy, + base::WeakPtr<storage::BlobStorageContext> blob_context, + const GURL& origin) : CacheLoader(cache_task_runner, request_context, quota_manager_proxy, @@ -262,7 +262,7 @@ static void CleanUpDeleteCacheDirInPool( const base::FilePath& cache_path, const BoolCallback& callback, - const scoped_refptr<base::SingleThreadTaskRunner>& original_task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> original_task_runner) { bool rv = base::DeleteFile(cache_path, true); original_task_runner->PostTask(FROM_HERE, base::Bind(callback, rv)); } @@ -304,7 +304,7 @@ const base::FilePath& index_path, const std::string& data, const BoolCallback& callback, - const scoped_refptr<base::SingleThreadTaskRunner>& original_task_runner) { + scoped_refptr<base::SingleThreadTaskRunner> original_task_runner) { int bytes_written = base::WriteFile(tmp_path, data.c_str(), data.size()); if (bytes_written != base::checked_cast<int>(data.size())) { base::DeleteFile(tmp_path, /* recursive */ false); @@ -451,8 +451,8 @@ const base::FilePath& path, bool memory_only, base::SequencedTaskRunner* cache_task_runner, - const scoped_refptr<net::URLRequestContextGetter>& request_context, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context, const GURL& origin) : initialized_(false), @@ -465,13 +465,13 @@ origin_(origin), weak_factory_(this) { if (memory_only) - cache_loader_.reset(new MemoryLoader(cache_task_runner_.get(), - request_context, quota_manager_proxy, - blob_context, origin)); + cache_loader_.reset( + new MemoryLoader(cache_task_runner_.get(), std::move(request_context), + quota_manager_proxy.get(), blob_context, origin)); else cache_loader_.reset(new SimpleCacheLoader( - origin_path_, cache_task_runner_.get(), request_context, - quota_manager_proxy, blob_context, origin)); + origin_path_, cache_task_runner_.get(), std::move(request_context), + quota_manager_proxy.get(), blob_context, origin)); } CacheStorage::~CacheStorage() { @@ -657,7 +657,7 @@ const CacheAndErrorCallback& callback) { scoped_refptr<CacheStorageCache> cache = GetLoadedCache(cache_name); if (cache.get()) { - callback.Run(cache, CACHE_STORAGE_OK); + callback.Run(std::move(cache), CACHE_STORAGE_OK); return; } @@ -669,7 +669,7 @@ void CacheStorage::CreateCacheDidCreateCache( const std::string& cache_name, const CacheAndErrorCallback& callback, - const scoped_refptr<CacheStorageCache>& cache) { + scoped_refptr<CacheStorageCache> cache) { DCHECK_CURRENTLY_ON(BrowserThread::IO); UMA_HISTOGRAM_BOOLEAN("ServiceWorkerCache.CreateCacheStorageResult", @@ -689,19 +689,19 @@ cache_loader_->WriteIndex( ordered_cache_names_, base::Bind(&CacheStorage::CreateCacheDidWriteIndex, - weak_factory_.GetWeakPtr(), callback, cache)); + weak_factory_.GetWeakPtr(), callback, std::move(cache))); } void CacheStorage::CreateCacheDidWriteIndex( const CacheAndErrorCallback& callback, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, bool success) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(cache.get()); // TODO(jkarlin): Handle !success. - callback.Run(cache, CACHE_STORAGE_OK); + callback.Run(std::move(cache), CACHE_STORAGE_OK); } void CacheStorage::HasCacheImpl(const std::string& cache_name, @@ -733,12 +733,11 @@ callback, ordered_cache_names_, cache)); } -void CacheStorage::DeleteCacheDidClose( - const std::string& cache_name, - const BoolAndErrorCallback& callback, - const StringVector& ordered_cache_names, - const scoped_refptr<CacheStorageCache>& cache, - int64_t cache_size) { +void CacheStorage::DeleteCacheDidClose(const std::string& cache_name, + const BoolAndErrorCallback& callback, + const StringVector& ordered_cache_names, + scoped_refptr<CacheStorageCache> cache, + int64_t cache_size) { cache_loader_->WriteIndex( ordered_cache_names, base::Bind(&CacheStorage::DeleteCacheDidWriteIndex, @@ -794,7 +793,7 @@ } void CacheStorage::MatchCacheDidMatch( - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, const CacheStorageCache::ResponseCallback& callback, CacheStorageError error, scoped_ptr<ServiceWorkerResponse> response, @@ -876,7 +875,7 @@ } void CacheStorage::TemporarilyPreserveCache( - const scoped_refptr<CacheStorageCache>& cache) { + scoped_refptr<CacheStorageCache> cache) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!ContainsKey(preserved_caches_, cache.get())); @@ -961,11 +960,11 @@ void CacheStorage::PendingCacheAndErrorCallback( const CacheAndErrorCallback& callback, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error) { base::WeakPtr<CacheStorage> cache_storage = weak_factory_.GetWeakPtr(); - callback.Run(cache, error); + callback.Run(std::move(cache), error); if (cache_storage) scheduler_->CompleteOperationAndRunNext(); }
diff --git a/content/browser/cache_storage/cache_storage.h b/content/browser/cache_storage/cache_storage.h index e5aac76..aed53b64 100644 --- a/content/browser/cache_storage/cache_storage.h +++ b/content/browser/cache_storage/cache_storage.h
@@ -41,8 +41,9 @@ public: typedef std::vector<std::string> StringVector; typedef base::Callback<void(bool, CacheStorageError)> BoolAndErrorCallback; - typedef base::Callback<void(const scoped_refptr<CacheStorageCache>&, - CacheStorageError)> CacheAndErrorCallback; + typedef base::Callback<void(scoped_refptr<CacheStorageCache>, + CacheStorageError)> + CacheAndErrorCallback; typedef base::Callback<void(const StringVector&, CacheStorageError)> StringsAndErrorCallback; using SizeCallback = base::Callback<void(int64_t)>; @@ -53,8 +54,8 @@ const base::FilePath& origin_path, bool memory_only, base::SequencedTaskRunner* cache_task_runner, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context, const GURL& origin); @@ -120,7 +121,7 @@ const std::string& cache_name); // Holds a reference to a cache for thirty seconds. - void TemporarilyPreserveCache(const scoped_refptr<CacheStorageCache>& cache); + void TemporarilyPreserveCache(scoped_refptr<CacheStorageCache> cache); virtual void SchedulePreservedCacheRemoval( const base::Closure& callback); // Virtual for testing. void RemovePreservedCache(const CacheStorageCache* cache); @@ -136,9 +137,9 @@ const CacheAndErrorCallback& callback); void CreateCacheDidCreateCache(const std::string& cache_name, const CacheAndErrorCallback& callback, - const scoped_refptr<CacheStorageCache>& cache); + scoped_refptr<CacheStorageCache> cache); void CreateCacheDidWriteIndex(const CacheAndErrorCallback& callback, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, bool success); // The HasCache callbacks are below. @@ -152,7 +153,7 @@ void DeleteCacheDidClose(const std::string& cache_name, const BoolAndErrorCallback& callback, const StringVector& ordered_cache_names, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, int64_t cache_size); void DeleteCacheDidWriteIndex(const std::string& cache_name, const BoolAndErrorCallback& callback, @@ -168,7 +169,7 @@ void MatchCacheImpl(const std::string& cache_name, scoped_ptr<ServiceWorkerFetchRequest> request, const CacheStorageCache::ResponseCallback& callback); - void MatchCacheDidMatch(const scoped_refptr<CacheStorageCache>& cache, + void MatchCacheDidMatch(scoped_refptr<CacheStorageCache> cache, const CacheStorageCache::ResponseCallback& callback, CacheStorageError error, scoped_ptr<ServiceWorkerResponse> response, @@ -194,10 +195,9 @@ void PendingBoolAndErrorCallback(const BoolAndErrorCallback& callback, bool found, CacheStorageError error); - void PendingCacheAndErrorCallback( - const CacheAndErrorCallback& callback, - const scoped_refptr<CacheStorageCache>& cache, - CacheStorageError error); + void PendingCacheAndErrorCallback(const CacheAndErrorCallback& callback, + scoped_refptr<CacheStorageCache> cache, + CacheStorageError error); void PendingStringsAndErrorCallback(const StringsAndErrorCallback& callback, const StringVector& strings, CacheStorageError error);
diff --git a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc index 08dffc32..bc58008 100644 --- a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc +++ b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.cc
@@ -32,13 +32,14 @@ void CacheStorageBlobToDiskCache::StreamBlobToCache( disk_cache::ScopedEntryPtr entry, int disk_cache_body_index, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, + net::URLRequestContextGetter* request_context_getter, scoped_ptr<storage::BlobDataHandle> blob_data_handle, const EntryAndBoolCallback& callback) { DCHECK(entry); DCHECK_LE(0, disk_cache_body_index); DCHECK(blob_data_handle); DCHECK(!blob_request_); + DCHECK(request_context_getter); if (!request_context_getter->GetURLRequestContext()) { callback.Run(std::move(entry), false /* success */);
diff --git a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h index 18e6fd97..3f73f25 100644 --- a/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h +++ b/content/browser/cache_storage/cache_storage_blob_to_disk_cache.h
@@ -43,12 +43,11 @@ // Writes the body of |blob_data_handle| to |entry| with index // |disk_cache_body_index|. |entry| is passed to the callback once complete. // Only call this once per instantiation of CacheStorageBlobToDiskCache. - void StreamBlobToCache( - disk_cache::ScopedEntryPtr entry, - int disk_cache_body_index, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - scoped_ptr<storage::BlobDataHandle> blob_data_handle, - const EntryAndBoolCallback& callback); + void StreamBlobToCache(disk_cache::ScopedEntryPtr entry, + int disk_cache_body_index, + net::URLRequestContextGetter* request_context_getter, + scoped_ptr<storage::BlobDataHandle> blob_data_handle, + const EntryAndBoolCallback& callback); // net::URLRequest::Delegate overrides for reading blobs. void OnResponseStarted(net::URLRequest* request) override; @@ -80,7 +79,10 @@ int cache_entry_offset_; disk_cache::ScopedEntryPtr entry_; - scoped_refptr<net::URLRequestContextGetter> request_context_getter_; + + // Owned by CacheStorageCache which owns this. + net::URLRequestContextGetter* request_context_getter_; + int disk_cache_body_index_; scoped_ptr<net::URLRequest> blob_request_; EntryAndBoolCallback callback_;
diff --git a/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc b/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc index 28e6c0c..5734e0d 100644 --- a/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc +++ b/content/browser/cache_storage/cache_storage_blob_to_disk_cache_unittest.cc
@@ -172,7 +172,7 @@ cache_storage_blob_to_disk_cache_->StreamBlobToCache( std::move(disk_cache_entry_), kCacheEntryIndex, - url_request_context_getter_, std::move(new_data_handle), + url_request_context_getter_.get(), std::move(new_data_handle), base::Bind(&CacheStorageBlobToDiskCacheTest::StreamCallback, base::Unretained(this)));
diff --git a/content/browser/cache_storage/cache_storage_cache.cc b/content/browser/cache_storage/cache_storage_cache.cc index 1e114d9d..1e83b43 100644 --- a/content/browser/cache_storage/cache_storage_cache.cc +++ b/content/browser/cache_storage/cache_storage_cache.cc
@@ -42,7 +42,7 @@ class CacheStorageCacheDataHandle : public storage::BlobDataBuilder::DataHandle { public: - CacheStorageCacheDataHandle(const scoped_refptr<CacheStorageCache>& cache, + CacheStorageCacheDataHandle(scoped_refptr<CacheStorageCache> cache, disk_cache::ScopedEntryPtr entry) : cache_(cache), entry_(std::move(entry)) {} @@ -106,11 +106,10 @@ // Copy headers out of a cache entry and into a protobuf. The callback is // guaranteed to be run. void ReadMetadata(disk_cache::Entry* entry, const MetadataCallback& callback); -void ReadMetadataDidReadMetadata( - disk_cache::Entry* entry, - const MetadataCallback& callback, - const scoped_refptr<net::IOBufferWithSize>& buffer, - int rv); +void ReadMetadataDidReadMetadata(disk_cache::Entry* entry, + const MetadataCallback& callback, + scoped_refptr<net::IOBufferWithSize> buffer, + int rv); bool VaryMatches(const ServiceWorkerHeaderMap& request, const ServiceWorkerHeaderMap& cached_request, @@ -166,11 +165,10 @@ read_header_callback.Run(read_rv); } -void ReadMetadataDidReadMetadata( - disk_cache::Entry* entry, - const MetadataCallback& callback, - const scoped_refptr<net::IOBufferWithSize>& buffer, - int rv) { +void ReadMetadataDidReadMetadata(disk_cache::Entry* entry, + const MetadataCallback& callback, + scoped_refptr<net::IOBufferWithSize> buffer, + int rv) { if (rv != buffer->size()) { callback.Run(scoped_ptr<CacheMetadata>()); return; @@ -286,23 +284,24 @@ // static scoped_refptr<CacheStorageCache> CacheStorageCache::CreateMemoryCache( const GURL& origin, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context) { - return make_scoped_refptr( - new CacheStorageCache(origin, base::FilePath(), request_context_getter, - quota_manager_proxy, blob_context)); + return make_scoped_refptr(new CacheStorageCache( + origin, base::FilePath(), std::move(request_context_getter), + std::move(quota_manager_proxy), blob_context)); } // static scoped_refptr<CacheStorageCache> CacheStorageCache::CreatePersistentCache( const GURL& origin, const base::FilePath& path, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context) { - return make_scoped_refptr(new CacheStorageCache( - origin, path, request_context_getter, quota_manager_proxy, blob_context)); + return make_scoped_refptr( + new CacheStorageCache(origin, path, std::move(request_context_getter), + std::move(quota_manager_proxy), blob_context)); } CacheStorageCache::~CacheStorageCache() { @@ -480,18 +479,17 @@ CacheStorageCache::CacheStorageCache( const GURL& origin, const base::FilePath& path, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context) : origin_(origin), path_(path), - request_context_getter_(request_context_getter), - quota_manager_proxy_(quota_manager_proxy), + request_context_getter_(std::move(request_context_getter)), + quota_manager_proxy_(std::move(quota_manager_proxy)), blob_storage_context_(blob_context), scheduler_(new CacheStorageScheduler()), memory_only_(path.empty()), - weak_ptr_factory_(this) { -} + weak_ptr_factory_(this) {} bool CacheStorageCache::LazyInitialize() { switch (backend_state_) { @@ -972,7 +970,7 @@ std::move(put_context->blob_data_handle); blob_to_cache->StreamBlobToCache( - std::move(entry), INDEX_RESPONSE_BODY, request_context_getter_, + std::move(entry), INDEX_RESPONSE_BODY, request_context_getter_.get(), std::move(blob_data_handle), base::Bind(&CacheStorageCache::PutDidWriteBlobToCache, weak_ptr_factory_.GetWeakPtr(),
diff --git a/content/browser/cache_storage/cache_storage_cache.h b/content/browser/cache_storage/cache_storage_cache.h index 72e1c9a..c4f904f3 100644 --- a/content/browser/cache_storage/cache_storage_cache.h +++ b/content/browser/cache_storage/cache_storage_cache.h
@@ -62,14 +62,14 @@ static scoped_refptr<CacheStorageCache> CreateMemoryCache( const GURL& origin, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context); static scoped_refptr<CacheStorageCache> CreatePersistentCache( const GURL& origin, const base::FilePath& path, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context); // Returns ERROR_TYPE_NOT_FOUND if not found. @@ -150,8 +150,8 @@ CacheStorageCache( const GURL& origin, const base::FilePath& path, - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy, base::WeakPtr<storage::BlobStorageContext> blob_context); // Async operations in progress will cancel and not run their callbacks.
diff --git a/content/browser/cache_storage/cache_storage_context_impl.cc b/content/browser/cache_storage/cache_storage_context_impl.cc index 83aa12d6..e58d790 100644 --- a/content/browser/cache_storage/cache_storage_context_impl.cc +++ b/content/browser/cache_storage/cache_storage_context_impl.cc
@@ -28,8 +28,7 @@ void CacheStorageContextImpl::Init( const base::FilePath& user_data_directory, - storage::QuotaManagerProxy* quota_manager_proxy, - storage::SpecialStoragePolicy* special_storage_policy) { + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy) { DCHECK_CURRENTLY_ON(BrowserThread::UI); is_incognito_ = user_data_directory.empty(); @@ -45,7 +44,7 @@ // TODO: Fix the tests to let the quota manager initialize normally. if (BrowserThread::CurrentlyOn(BrowserThread::IO)) { CreateCacheStorageManager(user_data_directory, cache_task_runner, - quota_manager_proxy, special_storage_policy); + std::move(quota_manager_proxy)); return; } @@ -53,8 +52,7 @@ BrowserThread::IO, FROM_HERE, base::Bind(&CacheStorageContextImpl::CreateCacheStorageManager, this, user_data_directory, cache_task_runner, - make_scoped_refptr(quota_manager_proxy), - make_scoped_refptr(special_storage_policy))); + std::move(quota_manager_proxy))); } void CacheStorageContextImpl::Shutdown() { @@ -103,15 +101,13 @@ void CacheStorageContextImpl::CreateCacheStorageManager( const base::FilePath& user_data_directory, - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner, - storage::QuotaManagerProxy* quota_manager_proxy, - storage::SpecialStoragePolicy* special_storage_policy) { + scoped_refptr<base::SequencedTaskRunner> cache_task_runner, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(!cache_manager_); - cache_manager_ = - CacheStorageManager::Create(user_data_directory, cache_task_runner.get(), - make_scoped_refptr(quota_manager_proxy)); + cache_manager_ = CacheStorageManager::Create( + user_data_directory, cache_task_runner, std::move(quota_manager_proxy)); } void CacheStorageContextImpl::ShutdownOnIO() {
diff --git a/content/browser/cache_storage/cache_storage_context_impl.h b/content/browser/cache_storage/cache_storage_context_impl.h index d72babf..f404fa8 100644 --- a/content/browser/cache_storage/cache_storage_context_impl.h +++ b/content/browser/cache_storage/cache_storage_context_impl.h
@@ -44,8 +44,7 @@ // Init and Shutdown are for use on the UI thread when the profile, // storagepartition is being setup and torn down. void Init(const base::FilePath& user_data_directory, - storage::QuotaManagerProxy* quota_manager_proxy, - storage::SpecialStoragePolicy* special_storage_policy); + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy); void Shutdown(); // Only callable on the IO thread. @@ -73,9 +72,8 @@ private: void CreateCacheStorageManager( const base::FilePath& user_data_directory, - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner, - storage::QuotaManagerProxy* quota_manager_proxy, - storage::SpecialStoragePolicy* special_storage_policy); + scoped_refptr<base::SequencedTaskRunner> cache_task_runner, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy); void ShutdownOnIO();
diff --git a/content/browser/cache_storage/cache_storage_dispatcher_host.cc b/content/browser/cache_storage/cache_storage_dispatcher_host.cc index af73b78..05e3568 100644 --- a/content/browser/cache_storage/cache_storage_dispatcher_host.cc +++ b/content/browser/cache_storage/cache_storage_dispatcher_host.cc
@@ -334,14 +334,14 @@ void CacheStorageDispatcherHost::OnCacheStorageOpenCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error) { if (error != CACHE_STORAGE_OK) { Send(new CacheStorageMsg_CacheStorageOpenError( thread_id, request_id, ToWebServiceWorkerCacheError(error))); return; } - CacheID cache_id = StoreCacheReference(cache); + CacheID cache_id = StoreCacheReference(std::move(cache)); Send(new CacheStorageMsg_CacheStorageOpenSuccess(thread_id, request_id, cache_id)); } @@ -400,7 +400,7 @@ void CacheStorageDispatcherHost::OnCacheMatchCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<ServiceWorkerResponse> response, scoped_ptr<storage::BlobDataHandle> blob_data_handle) { @@ -419,7 +419,7 @@ void CacheStorageDispatcherHost::OnCacheMatchAllCallbackAdapter( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<ServiceWorkerResponse> response, scoped_ptr<storage::BlobDataHandle> blob_data_handle) { @@ -433,14 +433,14 @@ if (blob_data_handle) blob_data_handles->push_back(*blob_data_handle); } - OnCacheMatchAllCallback(thread_id, request_id, cache, error, + OnCacheMatchAllCallback(thread_id, request_id, std::move(cache), error, std::move(responses), std::move(blob_data_handles)); } void CacheStorageDispatcherHost::OnCacheMatchAllCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<CacheStorageCache::Responses> responses, scoped_ptr<CacheStorageCache::BlobDataHandles> blob_data_handles) { @@ -460,7 +460,7 @@ void CacheStorageDispatcherHost::OnCacheKeysCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<CacheStorageCache::Requests> requests) { if (error != CACHE_STORAGE_OK) { @@ -484,7 +484,7 @@ void CacheStorageDispatcherHost::OnCacheBatchCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error) { if (error != CACHE_STORAGE_OK) { Send(new CacheStorageMsg_CacheBatchError( @@ -497,9 +497,9 @@ CacheStorageDispatcherHost::CacheID CacheStorageDispatcherHost::StoreCacheReference( - const scoped_refptr<CacheStorageCache>& cache) { + scoped_refptr<CacheStorageCache> cache) { int cache_id = next_cache_id_++; - id_to_cache_map_[cache_id] = cache; + id_to_cache_map_[cache_id] = std::move(cache); return cache_id; }
diff --git a/content/browser/cache_storage/cache_storage_dispatcher_host.h b/content/browser/cache_storage/cache_storage_dispatcher_host.h index 7743509..3ae680b 100644 --- a/content/browser/cache_storage/cache_storage_dispatcher_host.h +++ b/content/browser/cache_storage/cache_storage_dispatcher_host.h
@@ -91,7 +91,7 @@ CacheStorageError error); void OnCacheStorageOpenCallback(int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error); void OnCacheStorageDeleteCallback(int thread_id, int request_id, @@ -112,21 +112,21 @@ void OnCacheMatchCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<ServiceWorkerResponse> response, scoped_ptr<storage::BlobDataHandle> blob_data_handle); void OnCacheMatchAllCallbackAdapter( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<ServiceWorkerResponse> response, scoped_ptr<storage::BlobDataHandle> blob_data_handle); void OnCacheMatchAllCallback( int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<std::vector<ServiceWorkerResponse>> responses, scoped_ptr<CacheStorageCache::BlobDataHandles> blob_data_handles); @@ -137,18 +137,18 @@ const CacheStorageCacheQueryParams& match_params); void OnCacheKeysCallback(int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error, scoped_ptr<CacheStorageCache::Requests> requests); void OnCacheBatchCallback(int thread_id, int request_id, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error); // Hangs onto a scoped_refptr for the cache if it isn't already doing so. // Returns a unique cache_id. Call DropCacheReference when the client is done // with this cache. - CacheID StoreCacheReference(const scoped_refptr<CacheStorageCache>& cache); + CacheID StoreCacheReference(scoped_refptr<CacheStorageCache> cache); void DropCacheReference(CacheID cache_id); // Stores blob handles while waiting for acknowledgement of receipt from the
diff --git a/content/browser/cache_storage/cache_storage_manager.cc b/content/browser/cache_storage/cache_storage_manager.cc index 781df64..be2c6d7c 100644 --- a/content/browser/cache_storage/cache_storage_manager.cc +++ b/content/browser/cache_storage/cache_storage_manager.cc
@@ -123,16 +123,16 @@ // static scoped_ptr<CacheStorageManager> CacheStorageManager::Create( const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy) { + scoped_refptr<base::SequencedTaskRunner> cache_task_runner, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy) { base::FilePath root_path = path; if (!path.empty()) { root_path = path.Append(ServiceWorkerContextCore::kServiceWorkerDirectory) .AppendASCII("CacheStorage"); } - return make_scoped_ptr(new CacheStorageManager(root_path, cache_task_runner, - quota_manager_proxy)); + return make_scoped_ptr(new CacheStorageManager( + root_path, std::move(cache_task_runner), std::move(quota_manager_proxy))); } // static @@ -211,14 +211,14 @@ } void CacheStorageManager::SetBlobParametersForCache( - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, base::WeakPtr<storage::BlobStorageContext> blob_storage_context) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(cache_storage_map_.empty()); DCHECK(!request_context_getter_ || request_context_getter_.get() == request_context_getter.get()); DCHECK(!blob_context_ || blob_context_.get() == blob_storage_context.get()); - request_context_getter_ = request_context_getter; + request_context_getter_ = std::move(request_context_getter); blob_context_ = blob_storage_context; } @@ -380,11 +380,11 @@ CacheStorageManager::CacheStorageManager( const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy) + scoped_refptr<base::SequencedTaskRunner> cache_task_runner, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy) : root_path_(path), - cache_task_runner_(cache_task_runner), - quota_manager_proxy_(quota_manager_proxy), + cache_task_runner_(std::move(cache_task_runner)), + quota_manager_proxy_(std::move(quota_manager_proxy)), weak_ptr_factory_(this) { if (quota_manager_proxy_.get()) { quota_manager_proxy_->RegisterClient(
diff --git a/content/browser/cache_storage/cache_storage_manager.h b/content/browser/cache_storage/cache_storage_manager.h index 3ae3da80..ded3703 100644 --- a/content/browser/cache_storage/cache_storage_manager.h +++ b/content/browser/cache_storage/cache_storage_manager.h
@@ -40,8 +40,8 @@ public: static scoped_ptr<CacheStorageManager> Create( const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy); + scoped_refptr<base::SequencedTaskRunner> cache_task_runner, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy); static scoped_ptr<CacheStorageManager> Create( CacheStorageManager* old_manager); @@ -76,7 +76,7 @@ // This must be called before creating any of the public *Cache functions // above. void SetBlobParametersForCache( - const scoped_refptr<net::URLRequestContextGetter>& request_context_getter, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, base::WeakPtr<storage::BlobStorageContext> blob_storage_context); base::WeakPtr<CacheStorageManager> AsWeakPtr() { @@ -95,8 +95,8 @@ CacheStorageManager( const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner, - const scoped_refptr<storage::QuotaManagerProxy>& quota_manager_proxy); + scoped_refptr<base::SequencedTaskRunner> cache_task_runner, + scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy); // The returned CacheStorage* is owned by this manager. CacheStorage* FindOrCreateCacheStorage(const GURL& origin); @@ -132,7 +132,7 @@ return blob_context_; } - const scoped_refptr<base::SequencedTaskRunner>& cache_task_runner() const { + scoped_refptr<base::SequencedTaskRunner> cache_task_runner() const { return cache_task_runner_; }
diff --git a/content/browser/cache_storage/cache_storage_manager_unittest.cc b/content/browser/cache_storage/cache_storage_manager_unittest.cc index 5ed18f1..1f6411a 100644 --- a/content/browser/cache_storage/cache_storage_manager_unittest.cc +++ b/content/browser/cache_storage/cache_storage_manager_unittest.cc
@@ -117,9 +117,9 @@ } void CacheAndErrorCallback(base::RunLoop* run_loop, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error) { - callback_cache_ = cache; + callback_cache_ = std::move(cache); callback_error_ = error; run_loop->Quit(); } @@ -226,8 +226,7 @@ return callback_error_ == CACHE_STORAGE_OK; } - bool CachePut(const scoped_refptr<CacheStorageCache>& cache, - const GURL& url) { + bool CachePut(CacheStorageCache* cache, const GURL& url) { ServiceWorkerFetchRequest request; request.url = url; @@ -257,8 +256,7 @@ return callback_error_ == CACHE_STORAGE_OK; } - bool CacheMatch(const scoped_refptr<CacheStorageCache>& cache, - const GURL& url) { + bool CacheMatch(CacheStorageCache* cache, const GURL& url) { scoped_ptr<ServiceWorkerFetchRequest> request( new ServiceWorkerFetchRequest()); request->url = url; @@ -416,7 +414,7 @@ TEST_P(CacheStorageManagerTestP, DeleteCacheReducesOriginSize) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); // The quota manager gets updated after the put operation runs its callback so // run the event loop. base::RunLoop().RunUntilIdle(); @@ -458,33 +456,33 @@ TEST_P(CacheStorageManagerTestP, StorageMatchEntryExists) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_TRUE(StorageMatch(origin1_, "foo", GURL("http://example.com/foo"))); } TEST_P(CacheStorageManagerTestP, StorageMatchNoEntry) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_FALSE(StorageMatch(origin1_, "foo", GURL("http://example.com/bar"))); EXPECT_EQ(CACHE_STORAGE_ERROR_NOT_FOUND, callback_error_); } TEST_P(CacheStorageManagerTestP, StorageMatchNoCache) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_FALSE(StorageMatch(origin1_, "bar", GURL("http://example.com/foo"))); EXPECT_EQ(CACHE_STORAGE_ERROR_CACHE_NAME_NOT_FOUND, callback_error_); } TEST_P(CacheStorageManagerTestP, StorageMatchAllEntryExists) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_TRUE(StorageMatchAll(origin1_, GURL("http://example.com/foo"))); } TEST_P(CacheStorageManagerTestP, StorageMatchAllNoEntry) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_FALSE(StorageMatchAll(origin1_, GURL("http://example.com/bar"))); EXPECT_EQ(CACHE_STORAGE_ERROR_NOT_FOUND, callback_error_); } @@ -499,8 +497,8 @@ // with the same URL should work. (see crbug.com/542668) const GURL kTestURL = GURL("http://example.com/foo"); EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, kTestURL)); - EXPECT_TRUE(CacheMatch(callback_cache_, kTestURL)); + EXPECT_TRUE(CachePut(callback_cache_.get(), kTestURL)); + EXPECT_TRUE(CacheMatch(callback_cache_.get(), kTestURL)); scoped_ptr<storage::BlobDataHandle> data_handle = std::move(callback_data_handle_); @@ -508,14 +506,14 @@ // The cache is deleted but the handle to one of its entries is still // open. Creating a new cache in the same directory would fail on Windows. EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, kTestURL)); + EXPECT_TRUE(CachePut(callback_cache_.get(), kTestURL)); } TEST_P(CacheStorageManagerTestP, StorageMatchAllEntryExistsTwice) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_TRUE(Open(origin1_, "bar")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_TRUE(StorageMatchAll(origin1_, GURL("http://example.com/foo"))); } @@ -523,7 +521,7 @@ TEST_P(CacheStorageManagerTestP, StorageMatchInOneOfMany) { EXPECT_TRUE(Open(origin1_, "foo")); EXPECT_TRUE(Open(origin1_, "bar")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_TRUE(Open(origin1_, "baz")); EXPECT_TRUE(StorageMatchAll(origin1_, GURL("http://example.com/foo"))); @@ -627,14 +625,14 @@ EXPECT_EQ(0, GetOriginUsage(origin1_)); EXPECT_TRUE(Open(origin1_, "foo")); EXPECT_EQ(0, GetOriginUsage(origin1_)); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); int64_t foo_size = GetOriginUsage(origin1_); EXPECT_LT(0, GetOriginUsage(origin1_)); EXPECT_EQ(0, GetOriginUsage(origin2_)); // Add the same entry into a second cache, the size should double. EXPECT_TRUE(Open(origin1_, "bar")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_EQ(2 * foo_size, GetOriginUsage(origin1_)); } @@ -642,12 +640,12 @@ EXPECT_EQ(0ULL, GetAllOriginsUsage().size()); // Put one entry in a cache on origin 1. EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); // Put two entries (of identical size) in a cache on origin 2. EXPECT_TRUE(Open(origin2_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/bar"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/bar"))); std::vector<CacheStorageUsageInfo> usage = GetAllOriginsUsage(); EXPECT_EQ(2ULL, usage.size()); @@ -671,22 +669,22 @@ TEST_P(CacheStorageManagerTestP, GetSizeThenCloseAllCaches) { EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo2"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo2"))); EXPECT_TRUE(Open(origin1_, "bar")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/bar"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/bar"))); int64_t origin_size = GetOriginUsage(origin1_); EXPECT_LT(0, origin_size); EXPECT_EQ(origin_size, GetSizeThenCloseAllCaches(origin1_)); - EXPECT_FALSE(CachePut(callback_cache_, GURL("http://example.com/baz"))); + EXPECT_FALSE(CachePut(callback_cache_.get(), GURL("http://example.com/baz"))); } TEST_F(CacheStorageManagerTest, DeleteUnreferencedCacheDirectories) { // Create a referenced cache. EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); // Create an unreferenced directory next to the referenced one. base::FilePath origin_path = CacheStorageManager::ConstructOriginPath( @@ -702,7 +700,8 @@ // Verify that the referenced cache still works. EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CacheMatch(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE( + CacheMatch(callback_cache_.get(), GURL("http://example.com/foo"))); // Verify that the unreferenced cache is gone. EXPECT_FALSE(base::DirectoryExists(unreferenced_path)); @@ -816,7 +815,7 @@ // Populate a legacy cache. ASSERT_TRUE(Open(origin1_, legacy_cache_name_)); - EXPECT_TRUE(CachePut(callback_cache_, stored_url_)); + EXPECT_TRUE(CachePut(callback_cache_.get(), stored_url_)); base::FilePath new_path = callback_cache_->path(); // Close the cache's backend so that the files can be moved. @@ -869,27 +868,29 @@ ASSERT_FALSE(base::DirectoryExists(legacy_path_)); // Verify that the existing entry still works. - EXPECT_TRUE(CacheMatch(callback_cache_, stored_url_)); + EXPECT_TRUE(CacheMatch(callback_cache_.get(), stored_url_)); // Verify that adding new entries works. - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo2"))); - EXPECT_TRUE(CacheMatch(callback_cache_, GURL("http://example.com/foo2"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo2"))); + EXPECT_TRUE( + CacheMatch(callback_cache_.get(), GURL("http://example.com/foo2"))); } TEST_F(MigratedLegacyCacheDirectoryNameTest, RandomDirectoryCacheSideBySideWithLegacy) { EXPECT_TRUE(Open(origin1_, legacy_cache_name_)); EXPECT_TRUE(Open(origin1_, "bar")); - EXPECT_TRUE(CachePut(callback_cache_, stored_url_)); - EXPECT_TRUE(CacheMatch(callback_cache_, stored_url_)); + EXPECT_TRUE(CachePut(callback_cache_.get(), stored_url_)); + EXPECT_TRUE(CacheMatch(callback_cache_.get(), stored_url_)); } TEST_F(MigratedLegacyCacheDirectoryNameTest, DeleteLegacyCacheAndRecreateNew) { EXPECT_TRUE(Delete(origin1_, legacy_cache_name_)); EXPECT_TRUE(Open(origin1_, legacy_cache_name_)); - EXPECT_FALSE(CacheMatch(callback_cache_, stored_url_)); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo2"))); - EXPECT_TRUE(CacheMatch(callback_cache_, GURL("http://example.com/foo2"))); + EXPECT_FALSE(CacheMatch(callback_cache_.get(), stored_url_)); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo2"))); + EXPECT_TRUE( + CacheMatch(callback_cache_.get(), GURL("http://example.com/foo2"))); } class CacheStorageQuotaClientTest : public CacheStorageManagerTest { @@ -988,7 +989,7 @@ TEST_P(CacheStorageQuotaClientTestP, QuotaGetOriginUsage) { EXPECT_EQ(0, QuotaGetOriginUsage(origin1_)); EXPECT_TRUE(Open(origin1_, "foo")); - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_LT(0, QuotaGetOriginUsage(origin1_)); } @@ -1017,7 +1018,7 @@ EXPECT_EQ(0, QuotaGetOriginUsage(origin1_)); EXPECT_TRUE(Open(origin1_, "foo")); // Call put to test that initialized caches are properly deleted too. - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); EXPECT_TRUE(Open(origin1_, "bar")); EXPECT_TRUE(Open(origin2_, "baz")); @@ -1041,7 +1042,7 @@ TEST_F(CacheStorageQuotaClientDiskOnlyTest, QuotaDeleteUnloadedOriginData) { EXPECT_TRUE(Open(origin1_, "foo")); // Call put to test that initialized caches are properly deleted too. - EXPECT_TRUE(CachePut(callback_cache_, GURL("http://example.com/foo"))); + EXPECT_TRUE(CachePut(callback_cache_.get(), GURL("http://example.com/foo"))); // Close the cache backend so that it writes out its index to disk. base::RunLoop run_loop;
diff --git a/content/browser/cache_storage/cache_storage_unittest.cc b/content/browser/cache_storage/cache_storage_unittest.cc index faf0eb10..f2d1e9a 100644 --- a/content/browser/cache_storage/cache_storage_unittest.cc +++ b/content/browser/cache_storage/cache_storage_unittest.cc
@@ -81,7 +81,7 @@ } void OpenCacheCallback(bool* callback_called, - const scoped_refptr<CacheStorageCache>& cache, + scoped_refptr<CacheStorageCache> cache, CacheStorageError error) { *callback_called = true; callback_cache_ = cache;
diff --git a/content/browser/compositor/delegated_frame_host.cc b/content/browser/compositor/delegated_frame_host.cc index 5ffef426..7686744d 100644 --- a/content/browser/compositor/delegated_frame_host.cc +++ b/content/browser/compositor/delegated_frame_host.cc
@@ -456,7 +456,7 @@ if (!compositor_ || skip_frame) { SendDelegatedFrameAck(output_surface_id); } else { - AddOnCommitCallbackAndDisableLocks(base::Closure()); + can_lock_compositor_ = NO_PENDING_COMMIT; } if (!surface_id_.is_null()) delegated_frame_evictor_->SwappedFrame( @@ -699,7 +699,6 @@ if (resize_lock_.get() && resize_lock_->GrabDeferredLock()) can_lock_compositor_ = YES_DID_LOCK; } - RunOnCommitCallbacks(); if (resize_lock_ && resize_lock_->expected_size() == current_frame_size_in_dip_) { resize_lock_.reset(); @@ -771,24 +770,6 @@ DCHECK(!vsync_manager_.get()); } -void DelegatedFrameHost::RunOnCommitCallbacks() { - for (std::vector<base::Closure>::const_iterator - it = on_compositing_did_commit_callbacks_.begin(); - it != on_compositing_did_commit_callbacks_.end(); ++it) { - it->Run(); - } - on_compositing_did_commit_callbacks_.clear(); -} - -void DelegatedFrameHost::AddOnCommitCallbackAndDisableLocks( - const base::Closure& callback) { - DCHECK(compositor_); - - can_lock_compositor_ = NO_PENDING_COMMIT; - if (!callback.is_null()) - on_compositing_did_commit_callbacks_.push_back(callback); -} - void DelegatedFrameHost::SetCompositor(ui::Compositor* compositor) { DCHECK(!compositor_); if (!compositor) @@ -803,7 +784,6 @@ void DelegatedFrameHost::ResetCompositor() { if (!compositor_) return; - RunOnCommitCallbacks(); if (resize_lock_) { resize_lock_.reset(); client_->DelegatedFrameHostResizeLockWasReleased();
diff --git a/content/browser/compositor/delegated_frame_host.h b/content/browser/compositor/delegated_frame_host.h index 558d178b..e0ac4c0 100644 --- a/content/browser/compositor/delegated_frame_host.h +++ b/content/browser/compositor/delegated_frame_host.h
@@ -203,12 +203,6 @@ // Checks if the resize lock can be released because we received an new frame. void CheckResizeLock(); - // Run all on compositing commit callbacks. - void RunOnCommitCallbacks(); - - // Add on compositing commit callback. - void AddOnCommitCallbackAndDisableLocks(const base::Closure& callback); - // Called after async thumbnailer task completes. Scales and crops the result // of the copy. static void CopyFromCompositingSurfaceHasResultForVideo( @@ -239,8 +233,6 @@ DelegatedFrameHostClient* const client_; ui::Compositor* compositor_; - std::vector<base::Closure> on_compositing_did_commit_callbacks_; - // The vsync manager we are observing for changes, if any. scoped_refptr<ui::CompositorVSyncManager> vsync_manager_;
diff --git a/content/browser/compositor/gpu_process_transport_factory.cc b/content/browser/compositor/gpu_process_transport_factory.cc index 1aa6dd70..0a8867049 100644 --- a/content/browser/compositor/gpu_process_transport_factory.cc +++ b/content/browser/compositor/gpu_process_transport_factory.cc
@@ -62,6 +62,7 @@ #if defined(OS_WIN) #include "content/browser/compositor/software_output_device_win.h" +#include "ui/gfx/win/rendering_window_manager.h" #elif defined(USE_OZONE) #include "content/browser/compositor/browser_compositor_overlay_candidate_validator_ozone.h" #include "content/browser/compositor/software_output_device_ozone.h" @@ -218,6 +219,11 @@ data->surface = nullptr; } +#if defined(OS_WIN) + gfx::RenderingWindowManager::GetInstance()->UnregisterParent( + compositor->widget()); +#endif + bool create_gpu_output_surface = ShouldCreateGpuOutputSurface(compositor.get()); if (create_gpu_output_surface) { @@ -256,6 +262,11 @@ create_gpu_output_surface = false; } +#if defined(OS_WIN) + gfx::RenderingWindowManager::GetInstance()->RegisterParent( + compositor->widget()); +#endif + scoped_refptr<ContextProviderCommandBuffer> context_provider; if (create_gpu_output_surface) { // Try to reuse existing worker context provider. @@ -355,6 +366,11 @@ if (data->reflector) data->reflector->OnSourceSurfaceReady(data->surface); +#if defined(OS_WIN) + gfx::RenderingWindowManager::GetInstance()->DoSetParentOnChild( + compositor->widget()); +#endif + // This gets a bit confusing. Here we have a ContextProvider in the |surface| // configured to render directly to this widget. We need to make an // OnscreenDisplayClient associated with that context, then return a @@ -431,6 +447,10 @@ DCHECK(!gl_helper_) << "Destroying the GLHelper should not cause a new " "GLHelper to be created."; } +#if defined(OS_WIN) + gfx::RenderingWindowManager::GetInstance()->UnregisterParent( + compositor->widget()); +#endif } bool GpuProcessTransportFactory::DoesCreateTestContexts() { return false; }
diff --git a/content/browser/frame_host/frame_mojo_shell.cc b/content/browser/frame_host/frame_mojo_shell.cc index 752cb78f..8b54af6 100644 --- a/content/browser/frame_host/frame_mojo_shell.cc +++ b/content/browser/frame_host/frame_mojo_shell.cc
@@ -49,7 +49,7 @@ // future we may need to support both. void FrameMojoShell::Connect( const mojo::String& application_name, - uint32_t user_id, + const mojo::String& user_id, mojo::shell::mojom::InterfaceProviderRequest services, mojo::shell::mojom::InterfaceProviderPtr /* exposed_services */, const mojo::shell::mojom::Connector::ConnectCallback& callback) {
diff --git a/content/browser/frame_host/frame_mojo_shell.h b/content/browser/frame_host/frame_mojo_shell.h index 5e5f85b..c243345 100644 --- a/content/browser/frame_host/frame_mojo_shell.h +++ b/content/browser/frame_host/frame_mojo_shell.h
@@ -9,7 +9,7 @@ #include "base/memory/scoped_ptr.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/public/cpp/bindings/interface_request.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace content { @@ -30,7 +30,7 @@ // mojo::Connector: void Connect( const mojo::String& application_name, - uint32_t user_id, + const mojo::String& user_id, mojo::shell::mojom::InterfaceProviderRequest services, mojo::shell::mojom::InterfaceProviderPtr exposed_services, const mojo::shell::mojom::Connector::ConnectCallback& callback) override;
diff --git a/content/browser/frame_host/render_frame_host_manager.cc b/content/browser/frame_host/render_frame_host_manager.cc index 11894a7..d9901894 100644 --- a/content/browser/frame_host/render_frame_host_manager.cc +++ b/content/browser/frame_host/render_frame_host_manager.cc
@@ -2514,4 +2514,36 @@ ->GetRoutingIdForSiteInstance(instance); } +void RenderFrameHostManager::SendPageMessage(IPC::Message* msg) { + DCHECK(IPC_MESSAGE_CLASS(*msg) == PageMsgStart); + + // We should always deliver page messages through the main frame. + DCHECK(!frame_tree_node_->parent()); + + if ((IPC_MESSAGE_CLASS(*msg) != PageMsgStart) || frame_tree_node_->parent()) { + delete msg; + return; + } + + auto send_msg = [](IPC::Sender* sender, int routing_id, IPC::Message* msg) { + IPC::Message* copy = new IPC::Message(*msg); + copy->set_routing_id(routing_id); + sender->Send(copy); + }; + + for (const auto& pair : proxy_hosts_) + send_msg(pair.second.get(), pair.second->GetRoutingID(), msg); + + if (speculative_render_frame_host_) { + send_msg(speculative_render_frame_host_.get(), + speculative_render_frame_host_->GetRoutingID(), msg); + } else if (pending_render_frame_host_) { + send_msg(pending_render_frame_host_.get(), + pending_render_frame_host_->GetRoutingID(), msg); + } + + msg->set_routing_id(render_frame_host_->GetRoutingID()); + render_frame_host_->Send(msg); +} + } // namespace content
diff --git a/content/browser/frame_host/render_frame_host_manager.h b/content/browser/frame_host/render_frame_host_manager.h index 1b4afcb..5eba090 100644 --- a/content/browser/frame_host/render_frame_host_manager.h +++ b/content/browser/frame_host/render_frame_host_manager.h
@@ -487,6 +487,10 @@ // Returns the number of RenderFrameProxyHosts for this frame. int GetProxyCount(); + // Sends an IPC message to every process in the FrameTree. This should only be + // called in the top-level RenderFrameHostManager. + void SendPageMessage(IPC::Message* msg); + // Returns a const reference to the map of proxy hosts. The keys are // SiteInstance IDs, the values are RenderFrameProxyHosts. const std::unordered_map<int32_t, scoped_ptr<RenderFrameProxyHost>>&
diff --git a/content/browser/frame_host/render_widget_host_view_child_frame.cc b/content/browser/frame_host/render_widget_host_view_child_frame.cc index 35749e9..7c60d9c 100644 --- a/content/browser/frame_host/render_widget_host_view_child_frame.cc +++ b/content/browser/frame_host/render_widget_host_view_child_frame.cc
@@ -426,6 +426,12 @@ host_->ForwardTouchEventWithLatencyInfo(event, latency); } +void RenderWidgetHostViewChildFrame::ProcessGestureEvent( + const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) { + host_->ForwardGestureEventWithLatencyInfo(event, latency); +} + gfx::Point RenderWidgetHostViewChildFrame::TransformPointToRootCoordSpace( const gfx::Point& point) { if (!frame_connector_)
diff --git a/content/browser/frame_host/render_widget_host_view_child_frame.h b/content/browser/frame_host/render_widget_host_view_child_frame.h index 615028f..f6cba54 100644 --- a/content/browser/frame_host/render_widget_host_view_child_frame.h +++ b/content/browser/frame_host/render_widget_host_view_child_frame.h
@@ -141,6 +141,8 @@ void ProcessMouseWheelEvent(const blink::WebMouseWheelEvent& event) override; void ProcessTouchEvent(const blink::WebTouchEvent& event, const ui::LatencyInfo& latency) override; + void ProcessGestureEvent(const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) override; gfx::Point TransformPointToRootCoordSpace(const gfx::Point& point) override; #if defined(OS_MACOSX)
diff --git a/content/browser/geolocation/fake_access_token_store.cc b/content/browser/geolocation/fake_access_token_store.cc index d7da9ad..176513d 100644 --- a/content/browser/geolocation/fake_access_token_store.cc +++ b/content/browser/geolocation/fake_access_token_store.cc
@@ -14,7 +14,7 @@ namespace content { -FakeAccessTokenStore::FakeAccessTokenStore() : originating_task_runner_(NULL) { +FakeAccessTokenStore::FakeAccessTokenStore() { ON_CALL(*this, LoadAccessTokens(_)) .WillByDefault(Invoke(this, &FakeAccessTokenStore::DefaultLoadAccessTokens)); @@ -38,7 +38,7 @@ void FakeAccessTokenStore::DefaultLoadAccessTokens( const LoadAccessTokensCallback& callback) { - originating_task_runner_ = base::ThreadTaskRunnerHandle::Get().get(); + originating_task_runner_ = base::ThreadTaskRunnerHandle::Get(); callback_ = callback; }
diff --git a/content/browser/geolocation/fake_access_token_store.h b/content/browser/geolocation/fake_access_token_store.h index 49ce4cd..276f5c5 100644 --- a/content/browser/geolocation/fake_access_token_store.h +++ b/content/browser/geolocation/fake_access_token_store.h
@@ -6,6 +6,7 @@ #define CONTENT_BROWSER_GEOLOCATION_FAKE_ACCESS_TOKEN_STORE_H_ #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" #include "content/public/browser/access_token_store.h" #include "testing/gmock/include/gmock/gmock.h" @@ -43,7 +44,7 @@ // In some tests, NotifyDelegateTokensLoaded() is called on a thread // other than the originating thread, in which case we must post // back to it. - base::SingleThreadTaskRunner* originating_task_runner_; + scoped_refptr<base::SingleThreadTaskRunner> originating_task_runner_; DISALLOW_COPY_AND_ASSIGN(FakeAccessTokenStore); };
diff --git a/content/browser/geolocation/geolocation_provider_impl.cc b/content/browser/geolocation/geolocation_provider_impl.cc index 915a27816..c490907 100644 --- a/content/browser/geolocation/geolocation_provider_impl.cc +++ b/content/browser/geolocation/geolocation_provider_impl.cc
@@ -75,8 +75,7 @@ GeolocationProviderImpl::GeolocationProviderImpl() : base::Thread("Geolocation"), user_did_opt_into_location_services_(false), - ignore_location_updates_(false), - arbitrator_(NULL) { + ignore_location_updates_(false) { DCHECK_CURRENTLY_ON(BrowserThread::UI); high_accuracy_callbacks_.set_removal_callback( base::Bind(&GeolocationProviderImpl::OnClientsChanged, @@ -167,14 +166,13 @@ void GeolocationProviderImpl::CleanUp() { DCHECK(OnGeolocationThread()); - delete arbitrator_; - arbitrator_ = NULL; + arbitrator_.reset(); } -LocationArbitrator* GeolocationProviderImpl::CreateArbitrator() { +scoped_ptr<LocationArbitrator> GeolocationProviderImpl::CreateArbitrator() { LocationArbitratorImpl::LocationUpdateCallback callback = base::Bind( &GeolocationProviderImpl::OnLocationUpdate, base::Unretained(this)); - return new LocationArbitratorImpl(callback); + return make_scoped_ptr(new LocationArbitratorImpl(callback)); } } // namespace content
diff --git a/content/browser/geolocation/geolocation_provider_impl.h b/content/browser/geolocation/geolocation_provider_impl.h index 04e5de7..92129c5 100644 --- a/content/browser/geolocation/geolocation_provider_impl.h +++ b/content/browser/geolocation/geolocation_provider_impl.h
@@ -11,6 +11,7 @@ #include "base/callback_forward.h" #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/threading/thread.h" #include "content/common/content_export.h" #include "content/public/browser/geolocation_provider.h" @@ -53,7 +54,8 @@ ~GeolocationProviderImpl() override; // Useful for injecting mock geolocation arbitrator in tests. - virtual LocationArbitrator* CreateArbitrator(); + // TODO(mvanouwerkerk): Use something like SetArbitratorForTesting instead. + virtual scoped_ptr<LocationArbitrator> CreateArbitrator(); private: bool OnGeolocationThread() const; @@ -90,7 +92,7 @@ bool ignore_location_updates_; // Only to be used on the geolocation thread. - LocationArbitrator* arbitrator_; + scoped_ptr<LocationArbitrator> arbitrator_; DISALLOW_COPY_AND_ASSIGN(GeolocationProviderImpl); };
diff --git a/content/browser/geolocation/geolocation_provider_impl_unittest.cc b/content/browser/geolocation/geolocation_provider_impl_unittest.cc index 0b354fd..f1c7323 100644 --- a/content/browser/geolocation/geolocation_provider_impl_unittest.cc +++ b/content/browser/geolocation/geolocation_provider_impl_unittest.cc
@@ -38,16 +38,18 @@ protected: // GeolocationProviderImpl implementation: - LocationArbitrator* CreateArbitrator() override; + scoped_ptr<LocationArbitrator> CreateArbitrator() override; private: + // An alias to the arbitrator stored in the super class, where it is owned. MockLocationArbitrator* mock_arbitrator_; }; -LocationArbitrator* LocationProviderForTestArbitrator::CreateArbitrator() { +scoped_ptr<LocationArbitrator> +LocationProviderForTestArbitrator::CreateArbitrator() { DCHECK(mock_arbitrator_ == NULL); mock_arbitrator_ = new MockLocationArbitrator; - return mock_arbitrator_; + return make_scoped_ptr(mock_arbitrator_); } class GeolocationObserver {
diff --git a/content/browser/geolocation/location_api_adapter_android.cc b/content/browser/geolocation/location_api_adapter_android.cc index 4037ab6e..e1472ea 100644 --- a/content/browser/geolocation/location_api_adapter_android.cc +++ b/content/browser/geolocation/location_api_adapter_android.cc
@@ -151,7 +151,7 @@ } void AndroidLocationApiAdapter::CreateJavaObject(JNIEnv* env) { - // Create the Java AndroidLocationProvider object. + // Create the Java LocationProviderAdapter object. java_location_provider_android_object_.Reset( Java_LocationProviderAdapter_create(env, base::android::GetApplicationContext()));
diff --git a/content/browser/geolocation/location_api_adapter_android.h b/content/browser/geolocation/location_api_adapter_android.h index c58e26d6..6e48109 100644 --- a/content/browser/geolocation/location_api_adapter_android.h +++ b/content/browser/geolocation/location_api_adapter_android.h
@@ -19,18 +19,18 @@ class LocationProviderAndroid; struct Geoposition; -// Interacts with JNI and reports back to AndroidLocationProvider. -// This class creates a LocationProvider java object and listens for -// updates. +// Interacts with JNI and reports back to LocationProviderAndroid. This class +// creates a LocationProvider java object and listens for updates. // The simplified flow is: -// GeolocationProvider runs in a Geolocation Thread and fetches geolocation data -// from a LocationProvider. -// AndroidLocationProvider access a singleton AndroidLocationApiAdapter -// AndroidLocationApiAdapter calls via JNI and uses the main thread Looper -// in the java side to listen for location updates. We then bounce these updates -// to the Geolocation thread. +// - GeolocationProvider runs in a Geolocation Thread and fetches geolocation +// data from a LocationProvider. +// - LocationProviderAndroid accesses a singleton AndroidLocationApiAdapter. +// - AndroidLocationApiAdapter calls via JNI and uses the main thread Looper +// in the java side to listen for location updates. We then bounce these +// updates to the Geolocation thread. +// // Note that AndroidLocationApiAdapter is a singleton and there's at most only -// one AndroidLocationProvider that has called Start(). +// one LocationProviderAndroid that has called Start(). class AndroidLocationApiAdapter { public: // Starts the underlying location provider, returns true if successful. @@ -71,7 +71,8 @@ base::android::ScopedJavaGlobalRef<jobject> java_location_provider_android_object_; - LocationProviderAndroid* location_provider_; + // TODO(mvanouwerkerk): Use a callback instead of holding a pointer. + LocationProviderAndroid* location_provider_; // Owned by the arbitrator. // Guards against the following member which is accessed on Geolocation // thread and the JNI main thread looper.
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index dabd491..3433b55 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -62,6 +62,7 @@ #include "content/common/sandbox_win.h" #include "sandbox/win/src/sandbox_policy.h" #include "ui/gfx/switches.h" +#include "ui/gfx/win/rendering_window_manager.h" #endif #if defined(USE_OZONE) @@ -662,7 +663,11 @@ } } - ::SetParent(window_handle, parent_handle); + if (!gfx::RenderingWindowManager::GetInstance()->RegisterChild( + parent_handle, window_handle)) { + process_->TerminateOnBadMessageReceived( + GpuHostMsg_AcceleratedSurfaceCreatedChildWindow::ID); + } } #endif
diff --git a/content/browser/loader/async_revalidation_manager_browsertest.cc b/content/browser/loader/async_revalidation_manager_browsertest.cc index 33826ca5..9be15a4 100644 --- a/content/browser/loader/async_revalidation_manager_browsertest.cc +++ b/content/browser/loader/async_revalidation_manager_browsertest.cc
@@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/command_line.h" +#include "base/feature_list.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/run_loop.h" @@ -43,6 +43,12 @@ ~AsyncRevalidationManagerBrowserTest() override {} void SetUp() override { + base::FeatureList::ClearInstanceForTesting(); + scoped_ptr<base::FeatureList> feature_list(new base::FeatureList); + feature_list->InitializeFromCommandLine( + "StaleWhileRevalidate2", std::string()); + base::FeatureList::SetInstance(std::move(feature_list)); + ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); ContentBrowserTest::SetUp(); } @@ -51,10 +57,6 @@ embedded_test_server()->StartAcceptingConnections(); } - void SetUpCommandLine(base::CommandLine* command_line) override { - command_line->AppendSwitch("enable-stale-while-revalidate"); - } - base::RunLoop* run_loop() { return &run_loop_; } int requests_counted() const { return requests_counted_; }
diff --git a/content/browser/loader/mime_type_resource_handler.cc b/content/browser/loader/mime_type_resource_handler.cc index c9a9bb8..3dc8dce 100644 --- a/content/browser/loader/mime_type_resource_handler.cc +++ b/content/browser/loader/mime_type_resource_handler.cc
@@ -10,7 +10,7 @@ #include "base/bind.h" #include "base/location.h" #include "base/logging.h" -#include "base/metrics/histogram.h" +#include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" #include "base/thread_task_runner_handle.h" @@ -40,31 +40,6 @@ namespace { -void RecordSnifferMetrics(bool sniffing_blocked, - bool we_would_like_to_sniff, - const std::string& mime_type) { - static base::HistogramBase* nosniff_usage(NULL); - if (!nosniff_usage) - nosniff_usage = base::BooleanHistogram::FactoryGet( - "nosniff.usage", base::HistogramBase::kUmaTargetedHistogramFlag); - nosniff_usage->AddBoolean(sniffing_blocked); - - if (sniffing_blocked) { - static base::HistogramBase* nosniff_otherwise(NULL); - if (!nosniff_otherwise) - nosniff_otherwise = base::BooleanHistogram::FactoryGet( - "nosniff.otherwise", base::HistogramBase::kUmaTargetedHistogramFlag); - nosniff_otherwise->AddBoolean(we_would_like_to_sniff); - - static base::HistogramBase* nosniff_empty_mime_type(NULL); - if (!nosniff_empty_mime_type) - nosniff_empty_mime_type = base::BooleanHistogram::FactoryGet( - "nosniff.empty_mime_type", - base::HistogramBase::kUmaTargetedHistogramFlag); - nosniff_empty_mime_type->AddBoolean(mime_type.empty()); - } -} - // Used to write into an existing IOBuffer at a given offset. class DependentIOBuffer : public net::WrappedIOBuffer { public: @@ -260,8 +235,6 @@ bool we_would_like_to_sniff = net::ShouldSniffMimeType(request()->url(), mime_type); - RecordSnifferMetrics(sniffing_blocked, we_would_like_to_sniff, mime_type); - if (!sniffing_blocked && we_would_like_to_sniff) { // We're going to look at the data before deciding what the content type // is. That means we need to delay sending the ResponseStarted message
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index ce9d802..7b160b9d 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -17,6 +17,7 @@ #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/debug/alias.h" +#include "base/feature_list.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/scoped_ptr.h" @@ -87,6 +88,7 @@ #include "content/public/browser/stream_info.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/browser_side_navigation_policy.h" +#include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "ipc/ipc_message_macros.h" @@ -564,11 +566,6 @@ update_load_states_timer_.reset(new base::RepeatingTimer()); - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - // This needs to be called to mark the trial as active, even if the result - // isn't used. - std::string stale_while_revalidate_trial_group = - base::FieldTrialList::FindFullName("StaleWhileRevalidate"); // stale-while-revalidate currently doesn't work with browser-side navigation. // Only enable stale-while-revalidate if browser navigation is not enabled. // @@ -576,9 +573,7 @@ // together. Or disable stale-while-revalidate completely before browser-side // navigation becomes the default. crbug.com/561610 if (!IsBrowserSideNavigationEnabled() && - (base::StartsWith(stale_while_revalidate_trial_group, "Enabled", - base::CompareCase::SENSITIVE) || - command_line->HasSwitch(switches::kEnableStaleWhileRevalidate))) { + base::FeatureList::IsEnabled(features::kStaleWhileRevalidate)) { async_revalidation_manager_.reset(new AsyncRevalidationManager); } }
diff --git a/content/browser/media/capture/cursor_renderer_aura_unittest.cc b/content/browser/media/capture/cursor_renderer_aura_unittest.cc index bb210b9..e521236 100644 --- a/content/browser/media/capture/cursor_renderer_aura_unittest.cc +++ b/content/browser/media/capture/cursor_renderer_aura_unittest.cc
@@ -200,4 +200,20 @@ EXPECT_TRUE(NonZeroPixelsInRegion(frame, gfx::Rect(50, 50, 70, 70))); } +TEST_F(CursorRendererAuraTest, CursorRenderedOnRootWindow) { + cursor_renderer_.reset(new CursorRendererAura(root_window())); + EXPECT_FALSE(CursorDisplayed()); + + // Cursor displayed after mouse movement. + MoveMouseCursorWithinWindow(); + EXPECT_TRUE(CursorDisplayed()); + + // Cursor being displayed even if another window is activated. + scoped_ptr<aura::Window> window2(aura::test::CreateTestWindowWithBounds( + gfx::Rect(0, 0, 800, 600), root_window())); + wm::ActivateWindow(window2.get()); + SnapshotCursorState(gfx::Rect(0, 0, 800, 600)); + EXPECT_TRUE(CursorDisplayed()); +} + } // namespace content
diff --git a/content/browser/mojo/mojo_app_connection_impl.cc b/content/browser/mojo/mojo_app_connection_impl.cc index 1cf2148..5182971 100644 --- a/content/browser/mojo/mojo_app_connection_impl.cc +++ b/content/browser/mojo/mojo_app_connection_impl.cc
@@ -15,7 +15,8 @@ const char kBrowserMojoAppUrl[] = "system:content_browser"; namespace { -void OnGotInstanceID(uint32_t remote_id, uint32_t user_id) {} +void OnGotInstanceID(mojo::shell::mojom::ConnectResult result, + const std::string& user_id, uint32_t remote_id) {} } // namespace // static
diff --git a/content/browser/mojo/mojo_shell_client_host.cc b/content/browser/mojo/mojo_shell_client_host.cc index 0bdd217..69f1cc5c 100644 --- a/content/browser/mojo/mojo_shell_client_host.cc +++ b/content/browser/mojo/mojo_shell_client_host.cc
@@ -20,7 +20,7 @@ #include "mojo/edk/embedder/embedder.h" #include "mojo/public/cpp/system/message_pipe.h" #include "mojo/shell/public/cpp/connector.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/shell.mojom.h" namespace content { namespace { @@ -81,6 +81,8 @@ DISALLOW_COPY_AND_ASSIGN(PIDSender); }; +void OnConnectionComplete(mojo::shell::mojom::ConnectResult result) {} + } // namespace std::string RegisterChildWithExternalShell( @@ -99,9 +101,9 @@ if (!MojoShellConnection::Get()) return pipe_token; - mojo::shell::mojom::ApplicationManagerPtr application_manager; + mojo::shell::mojom::ShellPtr shell; MojoShellConnection::Get()->GetConnector()->ConnectToInterface( - "mojo:shell", &application_manager); + "mojo:shell", &shell); // The content of the URL/qualifier we pass is actually meaningless, it's only // important that they're unique per process. @@ -118,11 +120,14 @@ GetProxy(&pid_receiver); new PIDSender(render_process_host, std::move(pid_receiver)); - application_manager->CreateInstanceForHandle( - mojo::ScopedHandle(mojo::Handle(request_pipe.release().value())), - url, - CreateCapabilityFilterForRenderer(), - std::move(request)); + mojo::shell::mojom::ShellClientFactoryPtr factory; + factory.Bind(mojo::InterfacePtrInfo<mojo::shell::mojom::ShellClientFactory>( + std::move(request_pipe), 0u)); + + shell->CreateInstance(std::move(factory), url, + mojo::shell::mojom::kInheritUserID, + CreateCapabilityFilterForRenderer(), + std::move(request), base::Bind(&OnConnectionComplete)); // Store the URL on the RPH so client code can access it later via // GetMojoApplicationInstanceURL().
diff --git a/content/browser/mojo/mojo_shell_context.cc b/content/browser/mojo/mojo_shell_context.cc index e1a0a4e..134db56 100644 --- a/content/browser/mojo/mojo_shell_context.cc +++ b/content/browser/mojo/mojo_shell_context.cc
@@ -30,7 +30,7 @@ #include "mojo/shell/loader.h" #include "mojo/shell/native_runner.h" #include "mojo/shell/public/cpp/shell_client.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/runner/host/in_process_native_runner.h" namespace content { @@ -205,10 +205,10 @@ scoped_ptr<mojo::shell::NativeRunnerFactory> native_runner_factory( new mojo::shell::InProcessNativeRunnerFactory( BrowserThread::GetBlockingPool())); - application_manager_.reset(new mojo::shell::ApplicationManager( - std::move(native_runner_factory), file_task_runner.get(), nullptr)); + shell_.reset(new mojo::shell::Shell(std::move(native_runner_factory), + file_task_runner.get(), nullptr)); - application_manager_->set_default_loader( + shell_->set_default_loader( scoped_ptr<mojo::shell::Loader>(new DefaultLoader)); StaticApplicationMap apps; @@ -220,7 +220,7 @@ apps[entry.first] = entry.second; } for (const auto& entry : apps) { - application_manager_->SetLoaderForName( + shell_->SetLoaderForName( make_scoped_ptr(new StaticLoader(entry.second)), entry.first); } @@ -229,7 +229,7 @@ ->browser() ->RegisterOutOfProcessMojoApplications(&sandboxed_apps); for (const auto& app : sandboxed_apps) { - application_manager_->SetLoaderForName( + shell_->SetLoaderForName( make_scoped_ptr( new UtilityProcessLoader(app.second, true /* use_sandbox */)), app.first); @@ -240,25 +240,24 @@ ->browser() ->RegisterUnsandboxedOutOfProcessMojoApplications(&unsandboxed_apps); for (const auto& app : unsandboxed_apps) { - application_manager_->SetLoaderForName( + shell_->SetLoaderForName( make_scoped_ptr( new UtilityProcessLoader(app.second, false /* use_sandbox */)), app.first); } #if (ENABLE_MOJO_MEDIA_IN_GPU_PROCESS) - application_manager_->SetLoaderForName(make_scoped_ptr(new GpuProcessLoader), - "mojo:media"); + shell_->SetLoaderForName(make_scoped_ptr(new GpuProcessLoader), "mojo:media"); #endif base::Callback<scoped_ptr<mojo::ShellClient>()> profile_callback = base::Bind(&profile::CreateProfileApp); - application_manager_->SetLoaderForName( + shell_->SetLoaderForName( make_scoped_ptr(new StaticLoader(profile_callback)), "mojo:profile"); if (!IsRunningInMojoShell()) { MojoShellConnectionImpl::Create( - application_manager_->InitInstanceForEmbedder(kBrowserAppName)); + shell_->InitInstanceForEmbedder(kBrowserAppName)); } } @@ -285,20 +284,20 @@ mojo::shell::mojom::InterfaceProviderPtr exposed_services, const mojo::shell::mojom::Connector::ConnectCallback& callback) { scoped_ptr<mojo::shell::ConnectParams> params(new mojo::shell::ConnectParams); - // TODO(beng): kUserRoot is obviously wrong. + // TODO(beng): kRootUserID is obviously wrong. // TODO(beng): We need to set a permissive filter here temporarily because // content is known as a bogus system: name that the application // manager doesn't understand. mojo::shell::Identity source_id( - requestor_name, std::string(), mojo::shell::mojom::Connector::kUserRoot); + requestor_name, std::string(), mojo::shell::mojom::kRootUserID); source_id.set_filter(mojo::shell::GetPermissiveCapabilityFilter()); params->set_source(source_id); params->set_target(mojo::shell::Identity( - name, std::string(), mojo::shell::mojom::Connector::kUserRoot)); + name, std::string(), mojo::shell::mojom::kRootUserID)); params->set_remote_interfaces(std::move(request)); params->set_local_interfaces(std::move(exposed_services)); params->set_connect_callback(callback); - application_manager_->Connect(std::move(params)); + shell_->Connect(std::move(params)); } } // namespace content
diff --git a/content/browser/mojo/mojo_shell_context.h b/content/browser/mojo/mojo_shell_context.h index 2ed9cfcd3..90bda832 100644 --- a/content/browser/mojo/mojo_shell_context.h +++ b/content/browser/mojo/mojo_shell_context.h
@@ -13,8 +13,8 @@ #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "content/common/content_export.h" -#include "mojo/shell/application_manager.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" +#include "mojo/shell/shell.h" namespace mojo { class ShellClient; @@ -58,7 +58,7 @@ static base::LazyInstance<scoped_ptr<Proxy>> proxy_; - scoped_ptr<mojo::shell::ApplicationManager> application_manager_; + scoped_ptr<mojo::shell::Shell> shell_; DISALLOW_COPY_AND_ASSIGN(MojoShellContext); };
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 355a358..0343bd9 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -38,10 +38,24 @@ } } - if (view == current_touch_target_) { - current_touch_target_ = nullptr; + if (view == touch_target_) { + touch_target_ = nullptr; + touch_delta_ = gfx::Vector2d(); active_touches_ = 0; } + + // If the target that's being destroyed is in the gesture target queue, we + // replace it with nullptr so that we maintain the 1:1 correspondence between + // queue entries and the touch sequences that underly them. + for (size_t i = 0; i < gesture_target_queue_.size(); ++i) { + if (gesture_target_queue_[i].target == view) + gesture_target_queue_[i].target = nullptr; + } + + if (view == gesture_target_) { + gesture_target_ = nullptr; + gesture_delta_ = gfx::Vector2d(); + } } void RenderWidgetHostInputEventRouter::ClearAllObserverRegistrations() { @@ -74,7 +88,9 @@ } RenderWidgetHostInputEventRouter::RenderWidgetHostInputEventRouter() - : current_touch_target_(nullptr), active_touches_(0) {} + : touch_target_(nullptr), + gesture_target_(nullptr), + active_touches_(0) {} RenderWidgetHostInputEventRouter::~RenderWidgetHostInputEventRouter() { // We may be destroyed before some of the owners in the map, so we must @@ -144,6 +160,31 @@ target->ProcessMouseWheelEvent(*event); } +void RenderWidgetHostInputEventRouter::RouteGestureEvent( + RenderWidgetHostViewBase* root_view, + blink::WebGestureEvent* event, + const ui::LatencyInfo& latency) { + // We use GestureTapDown to detect the start of a gesture sequence since there + // is no WebGestureEvent equivalent for ET_GESTURE_BEGIN. Note that this + // means the GestureFlingCancel that always comes between ET_GESTURE_BEGIN and + // GestureTapDown is sent to the previous target, in case it is still in a + // fling. + if (event->type == blink::WebInputEvent::GestureTapDown) { + DCHECK(!gesture_target_queue_.empty()); + const GestureTargetData& data = gesture_target_queue_.front(); + gesture_target_ = data.target; + gesture_delta_ = data.delta; + gesture_target_queue_.pop_front(); + } + + if (!gesture_target_) + return; + + event->x += gesture_delta_.x(); + event->y += gesture_delta_.y(); + gesture_target_->ProcessGestureEvent(*event, latency); +} + void RenderWidgetHostInputEventRouter::RouteTouchEvent( RenderWidgetHostViewBase* root_view, blink::WebTouchEvent* event, @@ -153,46 +194,48 @@ if (!active_touches_) { // Since this is the first touch, it defines the target for the rest // of this sequence. - DCHECK(!current_touch_target_); + DCHECK(!touch_target_); gfx::Point transformed_point; gfx::Point original_point(event->touches[0].position.x, event->touches[0].position.y); - current_touch_target_ = + touch_target_ = FindEventTarget(root_view, original_point, &transformed_point); - if (!current_touch_target_) - return; // TODO(wjmaclean): Instead of just computing a delta, we should extract // the complete transform. We assume it doesn't change for the duration // of the touch sequence, though this could be wrong; a better approach - // might be to always transform each point to the current_touch_target_ + // might be to always transform each point to the touch_target_ // for the duration of the sequence. touch_delta_ = transformed_point - original_point; + gesture_target_queue_.emplace_back(touch_target_, touch_delta_); + + if (!touch_target_) + return; } ++active_touches_; - if (current_touch_target_) { + if (touch_target_) { TransformEventTouchPositions(event, touch_delta_); - current_touch_target_->ProcessTouchEvent(*event, latency); + touch_target_->ProcessTouchEvent(*event, latency); } break; } case blink::WebInputEvent::TouchMove: - if (current_touch_target_) { + if (touch_target_) { TransformEventTouchPositions(event, touch_delta_); - current_touch_target_->ProcessTouchEvent(*event, latency); + touch_target_->ProcessTouchEvent(*event, latency); } break; case blink::WebInputEvent::TouchEnd: case blink::WebInputEvent::TouchCancel: - if (!current_touch_target_) + if (!touch_target_) break; DCHECK(active_touches_); TransformEventTouchPositions(event, touch_delta_); - current_touch_target_->ProcessTouchEvent(*event, latency); + touch_target_->ProcessTouchEvent(*event, latency); --active_touches_; if (!active_touches_) { - current_touch_target_ = nullptr; + touch_target_ = nullptr; touch_delta_ = gfx::Vector2d(); } break;
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 5aba015..b4123539 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -6,9 +6,12 @@ #define CONTENT_BROWSER_RENDERER_HOST_RENDER_WIDGET_HOST_INPUT_EVENT_ROUTER_H_ #include <stdint.h> + +#include <deque> #include <unordered_map> #include "base/containers/hash_tables.h" +#include "base/gtest_prod_util.h" #include "base/macros.h" #include "cc/surfaces/surface_hittest_delegate.h" #include "cc/surfaces/surface_id.h" @@ -19,6 +22,7 @@ struct FrameHostMsg_HittestData_Params; namespace blink { +class WebGestureEvent; class WebMouseEvent; class WebMouseWheelEvent; class WebTouchEvent; @@ -55,6 +59,9 @@ blink::WebMouseEvent* event); void RouteMouseWheelEvent(RenderWidgetHostViewBase* root_view, blink::WebMouseWheelEvent* event); + void RouteGestureEvent(RenderWidgetHostViewBase* root_view, + blink::WebGestureEvent* event, + const ui::LatencyInfo& latency); void RouteTouchEvent(RenderWidgetHostViewBase* root_view, blink::WebTouchEvent *event, const ui::LatencyInfo& latency); @@ -89,6 +96,14 @@ using SurfaceIdNamespaceOwnerMap = base::hash_map<uint32_t, RenderWidgetHostViewBase*>; + struct GestureTargetData { + RenderWidgetHostViewBase* target; + const gfx::Vector2d delta; + + GestureTargetData(RenderWidgetHostViewBase* target, gfx::Vector2d delta) + : target(target), delta(delta) {} + }; + using GestureTargetQueue = std::deque<GestureTargetData>; void ClearAllObserverRegistrations(); @@ -97,13 +112,18 @@ gfx::Point* transformed_point); SurfaceIdNamespaceOwnerMap owner_map_; - RenderWidgetHostViewBase* current_touch_target_; + GestureTargetQueue gesture_target_queue_; + RenderWidgetHostViewBase* touch_target_; + RenderWidgetHostViewBase* gesture_target_; gfx::Vector2d touch_delta_; + gfx::Vector2d gesture_delta_; int active_touches_; std::unordered_map<cc::SurfaceId, HittestData, cc::SurfaceIdHash> hittest_data_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostInputEventRouter); + FRIEND_TEST_ALL_PREFIXES(SitePerProcessBrowserTest, + InputEventRouterGestureTargetQueueTest); }; } // namespace content
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 6963b213..3a46b4c 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -481,6 +481,7 @@ begin_frame_observer_proxy_(this), set_focus_on_mouse_down_or_key_event_(false), device_scale_factor_(0.0f), + disable_input_event_router_for_testing_(false), weak_ptr_factory_(this) { if (!is_guest_view_hack_) host_->SetView(this); @@ -869,7 +870,8 @@ // frame. TODO(wjmaclean): At present, this doesn't work for OOPIF, but // it should be a simple extension to modify RenderWidgetHostViewChildFrame // in a similar manner to RenderWidgetHostViewGuest. - bool result = host_->delegate() && host_->delegate()->GetInputEventRouter(); + bool result = host_->delegate() && host_->delegate()->GetInputEventRouter() && + !disable_input_event_router_for_testing_; if (event->IsMouseEvent()) result = result && SiteIsolationPolicy::AreCrossProcessFramesPossible(); return result; @@ -2260,6 +2262,12 @@ host_->ForwardTouchEventWithLatencyInfo(event, latency); } +void RenderWidgetHostViewAura::ProcessGestureEvent( + const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) { + host_->ForwardGestureEventWithLatencyInfo(event, latency); +} + void RenderWidgetHostViewAura::TransformPointToLocalCoordSpace( const gfx::Point& point, cc::SurfaceId original_surface, @@ -2368,11 +2376,21 @@ blink::WebGestureEvent fling_cancel = gesture; fling_cancel.type = blink::WebInputEvent::GestureFlingCancel; fling_cancel.sourceDevice = blink::WebGestureDeviceTouchscreen; - host_->ForwardGestureEvent(fling_cancel); + if (ShouldRouteEvent(event)) { + host_->delegate()->GetInputEventRouter()->RouteGestureEvent( + this, &fling_cancel, ui::LatencyInfo()); + } else { + host_->ForwardGestureEvent(fling_cancel); + } } if (gesture.type != blink::WebInputEvent::Undefined) { - host_->ForwardGestureEventWithLatencyInfo(gesture, *event->latency()); + if (ShouldRouteEvent(event)) { + host_->delegate()->GetInputEventRouter()->RouteGestureEvent( + this, &gesture, *event->latency()); + } else { + host_->ForwardGestureEventWithLatencyInfo(gesture, *event->latency()); + } if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN || event->type() == ui::ET_GESTURE_SCROLL_UPDATE || @@ -2738,6 +2756,7 @@ scoped_ptr<TouchSelectionControllerClientAura> client) { selection_controller_client_.swap(client); CreateSelectionController(); + disable_input_event_router_for_testing_ = true; } void RenderWidgetHostViewAura::InternalSetBounds(const gfx::Rect& rect) {
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h index 76e402f..7e9b2b37 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.h +++ b/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -202,6 +202,8 @@ void ProcessMouseWheelEvent(const blink::WebMouseWheelEvent& event) override; void ProcessTouchEvent(const blink::WebTouchEvent& event, const ui::LatencyInfo& latency) override; + void ProcessGestureEvent(const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) override; void TransformPointToLocalCoordSpace(const gfx::Point& point, cc::SurfaceId original_surface, gfx::Point* transformed_point) override; @@ -703,6 +705,11 @@ float device_scale_factor_; + // Allows tests to send gesture events for testing without first sending a + // corresponding touch sequence, as would be required by + // RenderWidgetHostInputEventRouter. + bool disable_input_event_router_for_testing_; + base::WeakPtrFactory<RenderWidgetHostViewAura> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAura);
diff --git a/content/browser/renderer_host/render_widget_host_view_base.h b/content/browser/renderer_host/render_widget_host_view_base.h index 94fbbb6..1cace30 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.h +++ b/content/browser/renderer_host/render_widget_host_view_base.h
@@ -221,7 +221,9 @@ virtual void ProcessMouseEvent(const blink::WebMouseEvent& event) {} virtual void ProcessMouseWheelEvent(const blink::WebMouseWheelEvent& event) {} virtual void ProcessTouchEvent(const blink::WebTouchEvent& event, - const ui::LatencyInfo& latency) {} + const ui::LatencyInfo& latency) {} + virtual void ProcessGestureEvent(const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) {} // Transform a point that is in the coordinate space of a Surface that is // embedded within the RenderWidgetHostViewBase's Surface to the
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.h b/content/browser/renderer_host/render_widget_host_view_mac.h index 46d18138..20579a59 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -362,6 +362,8 @@ void ProcessMouseWheelEvent(const blink::WebMouseWheelEvent& event) override; void ProcessTouchEvent(const blink::WebTouchEvent& event, const ui::LatencyInfo& latency) override; + void ProcessGestureEvent(const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) override; void TransformPointToLocalCoordSpace(const gfx::Point& point, cc::SurfaceId original_surface, gfx::Point* transformed_point) override;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index e1a196bd..62b0b38 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -1615,6 +1615,12 @@ render_widget_host_->ForwardTouchEventWithLatencyInfo(event, latency); } +void RenderWidgetHostViewMac::ProcessGestureEvent( + const blink::WebGestureEvent& event, + const ui::LatencyInfo& latency) { + render_widget_host_->ForwardGestureEventWithLatencyInfo(event, latency); +} + void RenderWidgetHostViewMac::TransformPointToLocalCoordSpace( const gfx::Point& point, cc::SurfaceId original_surface,
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 4031eec..debd06a6 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -26,10 +26,13 @@ #include "content/browser/frame_host/render_frame_proxy_host.h" #include "content/browser/frame_host/render_widget_host_view_child_frame.h" #include "content/browser/gpu/compositor_util.h" +#include "content/browser/renderer_host/input/synthetic_tap_gesture.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_input_event_router.h" +#include "content/browser/renderer_host/render_widget_host_view_aura.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/frame_messages.h" +#include "content/common/input/synthetic_tap_gesture_params.h" #include "content/common/view_messages.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_service.h" @@ -4576,6 +4579,239 @@ "window.domAutomationController.send(getLastTouchEvent());", &result)); EXPECT_EQ("touchstart", result); } + +namespace { + +// Declared here to be close to the SubframeGestureEventRouting test. +void OnSyntheticGestureCompleted(scoped_refptr<MessageLoopRunner> runner, + SyntheticGesture::Result result) { + EXPECT_EQ(SyntheticGesture::GESTURE_FINISHED, result); + runner->Quit(); +} + +} // namespace anonymous + +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, + SubframeGestureEventRouting) { + GURL main_url(embedded_test_server()->GetURL( + "/frame_tree/page_with_positioned_nested_frames.html")); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + WebContentsImpl* web_contents = + static_cast<WebContentsImpl*>(shell()->web_contents()); + FrameTreeNode* root = web_contents->GetFrameTree()->root(); + ASSERT_EQ(1U, root->child_count()); + + GURL frame_url( + embedded_test_server()->GetURL("b.com", "/page_with_click_handler.html")); + NavigateFrameToURL(root->child_at(0), frame_url); + auto child_frame_host = root->child_at(0)->current_frame_host(); + EXPECT_TRUE(WaitForRenderFrameReady(child_frame_host)); + + // Synchronize with the child and parent renderers to guarantee that the + // surface information required for event hit testing is ready. + RenderWidgetHostViewBase* child_rwhv = static_cast<RenderWidgetHostViewBase*>( + child_frame_host->GetView()); + SurfaceHitTestReadyNotifier notifier( + static_cast<RenderWidgetHostViewChildFrame*>(child_rwhv)); + notifier.WaitForSurfaceReady(); + + // There have been no GestureTaps sent yet. + { + std::string result; + EXPECT_TRUE(ExecuteScriptAndExtractString( + child_frame_host, + "window.domAutomationController.send(getClickStatus());", &result)); + EXPECT_EQ("0 clicks received", result); + } + + // Simulate touch sequence to send GestureTap to sub-frame. + SyntheticTapGestureParams params; + params.gesture_source_type = SyntheticGestureParams::TOUCH_INPUT; + gfx::Point center(150, 150); + params.position = gfx::PointF(center.x(), center.y()); + params.duration_ms = 100; + scoped_ptr<SyntheticTapGesture> gesture(new SyntheticTapGesture(params)); + + scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner(); + + RenderWidgetHostImpl* render_widget_host = + root->current_frame_host()->GetRenderWidgetHost(); + // TODO(wjmaclean): Convert the call to base::Bind() to a lambda someday. + render_widget_host->QueueSyntheticGesture( + std::move(gesture), base::Bind(OnSyntheticGestureCompleted, runner)); + + // We need to run the message loop while we wait for the synthetic gesture + // to be processed; the callback registered above will get us out of the + // message loop when that happens. + runner->Run(); + runner = nullptr; + + // Verify click handler in subframe was invoked + { + std::string result; + EXPECT_TRUE(ExecuteScriptAndExtractString( + child_frame_host, + "window.domAutomationController.send(getClickStatus());", &result)); + EXPECT_EQ("1 click received", result); + } +} + +namespace { + +// Defined here to be close to +// SitePerProcessBrowserTest.InputEventRouterGestureTargetQueueTest. +void SendTouchTapWithExpectedTarget( + RenderWidgetHostViewBase* root_view, + const gfx::Point& touch_point, + RenderWidgetHostViewBase*& router_touch_target, + const RenderWidgetHostViewBase* expected_target) { + auto root_view_aura = static_cast<RenderWidgetHostViewAura*>(root_view); + ui::TouchEvent touch_event_pressed(ui::ET_TOUCH_PRESSED, touch_point, 0, + 0, ui::EventTimeForNow(), 30.f, 30.f, 0.f, + 0.f); + root_view_aura->OnTouchEvent(&touch_event_pressed); + EXPECT_EQ(expected_target, router_touch_target); + ui::TouchEvent touch_event_released(ui::ET_TOUCH_RELEASED, touch_point, + 0, 0, ui::EventTimeForNow(), 30.f, 30.f, + 0.f, 0.f); + root_view_aura->OnTouchEvent(&touch_event_released); + EXPECT_EQ(nullptr, router_touch_target); +} + +void SendGestureTapSequenceWithExpectedTarget( + RenderWidgetHostViewBase* root_view, + gfx::Point gesture_point, + RenderWidgetHostViewBase*& router_gesture_target, + const RenderWidgetHostViewBase* old_expected_target, + const RenderWidgetHostViewBase* expected_target) { + auto root_view_aura = static_cast<RenderWidgetHostViewAura*>(root_view); + + ui::GestureEvent gesture_begin_event( + gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), + ui::GestureEventDetails(ui::ET_GESTURE_BEGIN)); + root_view_aura->OnGestureEvent(&gesture_begin_event); + // We expect to still have the old gesture target in place for the + // GestureFlingCancel that will be inserted before GestureTapDown. + // Note: the GestureFlingCancel is inserted by RenderWidgetHostViewAura:: + // OnGestureEvent() when it sees ui::ET_GESTURE_TAP_DOWN, so we don't + // explicitly add it here. + EXPECT_EQ(old_expected_target, router_gesture_target); + + ui::GestureEvent gesture_tap_down_event( + gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), + ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); + root_view_aura->OnGestureEvent(&gesture_tap_down_event); + EXPECT_EQ(expected_target, router_gesture_target); + + ui::GestureEvent gesture_show_press_event( + gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), + ui::GestureEventDetails(ui::ET_GESTURE_SHOW_PRESS)); + root_view_aura->OnGestureEvent(&gesture_show_press_event); + EXPECT_EQ(expected_target, router_gesture_target); + + ui::GestureEventDetails gesture_tap_details(ui::ET_GESTURE_TAP); + gesture_tap_details.set_tap_count(1); + ui::GestureEvent gesture_tap_event( + gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), + gesture_tap_details); + root_view_aura->OnGestureEvent(&gesture_tap_event); + EXPECT_EQ(expected_target, router_gesture_target); + + ui::GestureEvent gesture_end_event( + gesture_point.x(), gesture_point.y(), 0, ui::EventTimeForNow(), + ui::GestureEventDetails(ui::ET_GESTURE_END)); + root_view_aura->OnGestureEvent(&gesture_end_event); + EXPECT_EQ(expected_target, router_gesture_target); +} + +} // namespace anonymous + +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, + InputEventRouterGestureTargetQueueTest) { + GURL main_url(embedded_test_server()->GetURL( + "/frame_tree/page_with_positioned_nested_frames.html")); + EXPECT_TRUE(NavigateToURL(shell(), main_url)); + + WebContentsImpl* web_contents = + static_cast<WebContentsImpl*>(shell()->web_contents()); + FrameTreeNode* root = web_contents->GetFrameTree()->root(); + ASSERT_EQ(1U, root->child_count()); + + GURL frame_url( + embedded_test_server()->GetURL("b.com", "/page_with_click_handler.html")); + NavigateFrameToURL(root->child_at(0), frame_url); + auto child_frame_host = root->child_at(0)->current_frame_host(); + EXPECT_TRUE(WaitForRenderFrameReady(child_frame_host)); + + // Synchronize with the child and parent renderers to guarantee that the + // surface information required for event hit testing is ready. + auto rwhv_child = + static_cast<RenderWidgetHostViewBase*>(child_frame_host->GetView()); + SurfaceHitTestReadyNotifier notifier( + static_cast<RenderWidgetHostViewChildFrame*>(rwhv_child)); + notifier.WaitForSurfaceReady(); + + // All touches & gestures are sent to the main frame's view, and should be + // routed appropriately from there. + auto rwhv_parent = static_cast<RenderWidgetHostViewBase*>( + web_contents->GetRenderWidgetHostView()); + + RenderWidgetHostInputEventRouter* router = + web_contents->GetInputEventRouter(); + EXPECT_TRUE(router->gesture_target_queue_.empty()); + EXPECT_EQ(nullptr, router->gesture_target_); + + // Send touch sequence to main-frame. + gfx::Point main_frame_point(25, 25); + SendTouchTapWithExpectedTarget(rwhv_parent, main_frame_point, + router->touch_target_, rwhv_parent); + EXPECT_EQ(1LU, router->gesture_target_queue_.size()); + EXPECT_EQ(nullptr, router->gesture_target_); + + + // Send touch sequence to child. + gfx::Point child_center(150, 150); + SendTouchTapWithExpectedTarget(rwhv_parent, child_center, + router->touch_target_, rwhv_child); + EXPECT_EQ(2LU, router->gesture_target_queue_.size()); + EXPECT_EQ(nullptr, router->gesture_target_); + + // Send another touch sequence to main frame. + SendTouchTapWithExpectedTarget(rwhv_parent, main_frame_point, + router->touch_target_, rwhv_parent); + EXPECT_EQ(3LU, router->gesture_target_queue_.size()); + EXPECT_EQ(nullptr, router->gesture_target_); + + // Send Gestures to clear GestureTargetQueue. + + // The first touch sequence should generate a GestureTapDown, sent to the + // main frame. + SendGestureTapSequenceWithExpectedTarget(rwhv_parent, main_frame_point, + router->gesture_target_, nullptr, + rwhv_parent); + EXPECT_EQ(2LU, router->gesture_target_queue_.size()); + // Note: rwhv_parent is the target used for GestureFlingCancel sent by + // RenderWidgetHostViewAura::OnGestureEvent() at the start of the next gesture + // sequence; the sequence itself goes to rwhv_child. + EXPECT_EQ(rwhv_parent, router->gesture_target_); + + // The second touch sequence should generate a GestureTapDown, sent to the + // child frame. + SendGestureTapSequenceWithExpectedTarget(rwhv_parent, child_center, + router->gesture_target_, rwhv_parent, + rwhv_child); + EXPECT_EQ(1LU, router->gesture_target_queue_.size()); + EXPECT_EQ(rwhv_child, router->gesture_target_); + + // The third touch sequence should generate a GestureTapDown, sent to the + // main frame. + SendGestureTapSequenceWithExpectedTarget(rwhv_parent, main_frame_point, + router->gesture_target_, rwhv_child, + rwhv_parent); + EXPECT_EQ(0LU, router->gesture_target_queue_.size()); + EXPECT_EQ(rwhv_parent, router->gesture_target_); +} #endif // defined(USE_AURA) // Ensure that a cross-process subframe can receive keyboard events when in @@ -5584,8 +5820,7 @@ std::string frame_title; EXPECT_TRUE(ExecuteScriptAndExtractString( root->child_at(0)->current_frame_host(), - "domAutomationController.send(document.title)", - &frame_title)); + "domAutomationController.send(document.title)", &frame_title)); EXPECT_EQ("", frame_title); // Navigate the subframe to another cross-origin page and ensure that this @@ -5607,4 +5842,33 @@ } } +IN_PROC_BROWSER_TEST_F(SitePerProcessBrowserTest, ScreenCoordinates) { + GURL main_url(embedded_test_server()->GetURL( + "a.com", "/cross_site_iframe_factory.html?a(b)")); + NavigateToURL(shell(), main_url); + + FrameTreeNode* root = static_cast<WebContentsImpl*>(shell()->web_contents()) + ->GetFrameTree() + ->root(); + FrameTreeNode* child = root->child_at(0); + + const char* properties[] = {"screenX", "screenY", "outerWidth", + "outerHeight"}; + + for (const char* property : properties) { + std::string script = "window.domAutomationController.send(window."; + script += property; + script += ");"; + int root_value = 1; + int child_value = 2; + EXPECT_TRUE(ExecuteScriptAndExtractInt(root->current_frame_host(), + script.c_str(), &root_value)); + + EXPECT_TRUE(ExecuteScriptAndExtractInt(child->current_frame_host(), + script.c_str(), &child_value)); + + EXPECT_EQ(root_value, child_value); + } +} + } // namespace content
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index 571df268..52497c9 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -462,8 +462,7 @@ scoped_refptr<CacheStorageContextImpl> cache_storage_context = new CacheStorageContextImpl(context); - cache_storage_context->Init(path, quota_manager->proxy(), - context->GetSpecialStoragePolicy()); + cache_storage_context->Init(path, make_scoped_refptr(quota_manager->proxy())); scoped_refptr<ServiceWorkerContextWrapper> service_worker_context = new ServiceWorkerContextWrapper(context);
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 0578dfa..17e4875d 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -45,6 +45,7 @@ #include "content/browser/frame_host/navigation_handle_impl.h" #include "content/browser/frame_host/navigator_impl.h" #include "content/browser/frame_host/render_frame_host_impl.h" +#include "content/browser/frame_host/render_frame_proxy_host.h" #include "content/browser/frame_host/render_widget_host_view_child_frame.h" #include "content/browser/geolocation/geolocation_service_context.h" #include "content/browser/host_zoom_map_impl.h" @@ -72,6 +73,7 @@ #include "content/common/browser_plugin/browser_plugin_messages.h" #include "content/common/frame_messages.h" #include "content/common/input_messages.h" +#include "content/common/page_messages.h" #include "content/common/site_isolation_policy.h" #include "content/common/ssl_status_serialization.h" #include "content/common/view_messages.h" @@ -779,6 +781,10 @@ return number_of_messages; } +void WebContentsImpl::SendPageMessage(IPC::Message* msg) { + frame_tree_.root()->render_manager()->SendPageMessage(msg); +} + RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() const { return GetRenderManager()->current_host(); } @@ -2219,6 +2225,13 @@ RenderWidgetHostImpl::From(GetRenderViewHost()->GetWidget()) ->SendScreenRects(); + RenderWidgetHostViewBase* rwhv = + static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView()); + if (rwhv) { + SendPageMessage(new PageMsg_UpdateWindowScreenRect( + MSG_ROUTING_NONE, rwhv->GetBoundsInRootWindow())); + } + if (browser_plugin_embedder_) browser_plugin_embedder_->DidSendScreenRects(); } @@ -2934,9 +2947,28 @@ } bool WebContentsImpl::FocusLocationBarByDefault() { - NavigationEntry* entry = controller_.GetVisibleEntry(); - if (entry && entry->GetURL() == GURL(url::kAboutBlankURL)) + // When the browser is started with about:blank as the startup URL, focus + // the location bar (which will also select its contents) so people can + // simply begin typing to navigate elsewhere. + // + // We need to be careful not to trigger this for anything other than the + // startup navigation. In particular, if we allow an attacker to open a + // popup to about:blank, then navigate, focusing the Omnibox will cause the + // end of the new URL to be scrolled into view instead of the start, + // allowing the attacker to spoof other URLs. The conditions checked here + // are all aimed at ensuring no such attacker-controlled navigation can + // trigger this. + // + // Note that we check the pending entry instead of the visible one; for the + // startup URL case these are the same, but for the attacker-controlled + // navigation case the visible entry is the committed "about:blank" URL and + // the pending entry is the problematic navigation elsewhere. + NavigationEntryImpl* entry = controller_.GetPendingEntry(); + if (controller_.IsInitialNavigation() && entry && + !entry->is_renderer_initiated() && + entry->GetURL() == GURL(url::kAboutBlankURL)) { return true; + } return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this); }
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 503dd38..7e0da7d3 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -7,6 +7,7 @@ #include <stdint.h> +#include <functional> #include <map> #include <set> #include <string> @@ -980,6 +981,9 @@ // called once as this call also removes it from the internal map. WebContentsImpl* GetCreatedWindow(int route_id); + // Sends a Page message IPC. + void SendPageMessage(IPC::Message* msg); + // Tracking loading progress ------------------------------------------------- // Resets the tracking state of the current load progress.
diff --git a/content/browser/web_contents/web_contents_view_mac.mm b/content/browser/web_contents/web_contents_view_mac.mm index e569f018..5d079a5 100644 --- a/content/browser/web_contents/web_contents_view_mac.mm +++ b/content/browser/web_contents/web_contents_view_mac.mm
@@ -8,6 +8,7 @@ #include <string> +#include "base/command_line.h" #import "base/mac/mac_util.h" #import "base/mac/scoped_sending_event.h" #include "base/mac/sdk_forward_declarations.h" @@ -23,6 +24,7 @@ #include "content/common/view_messages.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_view_delegate.h" +#include "content/public/common/content_switches.h" #include "skia/ext/skia_utils_mac.h" #import "third_party/mozilla/NSPasteboard+Utils.h" #include "ui/base/clipboard/custom_data_helper.h" @@ -636,10 +638,12 @@ NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter]; - // Occlusion notification APIs are new in Mavericks. - bool supportsOcclusionAPIs = base::mac::IsOSMavericksOrLater(); + // Occlusion is highly undesirable for browser tests, since it will + // flakily change test behavior. + static bool isDisabled = base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kDisableBackgroundingOccludedWindowsForTesting); - if (supportsOcclusionAPIs) { + if (!isDisabled) { if (oldWindow) { [notificationCenter removeObserver:self
diff --git a/content/child/web_url_loader_impl.cc b/content/child/web_url_loader_impl.cc index 6b71bd2..88018f9b 100644 --- a/content/child/web_url_loader_impl.cc +++ b/content/child/web_url_loader_impl.cc
@@ -943,7 +943,7 @@ response->setWasCached(!info.load_timing.request_start_time.is_null() && info.response_time < info.load_timing.request_start_time); response->setRemoteIPAddress( - WebString::fromUTF8(info.socket_address.host())); + WebString::fromUTF8(info.socket_address.HostForURL())); response->setRemotePort(info.socket_address.port()); response->setConnectionID(info.load_timing.socket_log_id); response->setConnectionReused(info.load_timing.socket_reused);
diff --git a/content/child/web_url_loader_impl_unittest.cc b/content/child/web_url_loader_impl_unittest.cc index db13cdc..b8bc240 100644 --- a/content/child/web_url_loader_impl_unittest.cc +++ b/content/child/web_url_loader_impl_unittest.cc
@@ -26,6 +26,7 @@ #include "content/public/child/request_peer.h" #include "content/public/common/content_switches.h" #include "content/public/common/resource_response_info.h" +#include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" @@ -710,5 +711,32 @@ EXPECT_EQ(kTestData, client()->received_data()); } +TEST_F(WebURLLoaderImplTest, ResponseIPAddress) { + GURL url("http://example.test/"); + + struct TestCase { + const char* ip; + const char* expected; + } cases[] = { + {"127.0.0.1", "127.0.0.1"}, + {"123.123.123.123", "123.123.123.123"}, + {"::1", "[::1]"}, + {"2001:0db8:85a3:0000:0000:8a2e:0370:7334", + "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]"}, + {"2001:db8:85a3:0:0:8a2e:370:7334", "[2001:db8:85a3:0:0:8a2e:370:7334]"}, + {"2001:db8:85a3::8a2e:370:7334", "[2001:db8:85a3::8a2e:370:7334]"}, + {"::ffff:192.0.2.128", "[::ffff:192.0.2.128]"}}; + + for (const auto& test : cases) { + SCOPED_TRACE(test.ip); + content::ResourceResponseInfo info; + info.socket_address = net::HostPortPair(test.ip, 443); + blink::WebURLResponse response; + response.initialize(); + WebURLLoaderImpl::PopulateURLResponse(url, info, &response, true); + EXPECT_EQ(test.expected, response.remoteIPAddress().utf8()); + }; +} + } // namespace } // namespace content
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 63d416a..3dbb1306 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -188,7 +188,7 @@ "//gpu/command_buffer/client:gles2_cmd_helper", "//gpu/command_buffer/client:gles2_implementation", "//gpu/command_buffer/service", - "//gpu/ipc", + "//gpu/ipc/common", "//gpu/skia_bindings", "//media", "//media:shared_memory_support",
diff --git a/content/common/cc_messages.h b/content/common/cc_messages.h index 8870a1b..1dacc95 100644 --- a/content/common/cc_messages.h +++ b/content/common/cc_messages.h
@@ -28,7 +28,7 @@ #include "cc/surfaces/surface_id.h" #include "cc/surfaces/surface_sequence.h" #include "content/common/content_export.h" -#include "gpu/ipc/gpu_command_buffer_traits.h" +#include "gpu/ipc/common/gpu_command_buffer_traits.h" #include "ipc/ipc_message_macros.h" #include "ui/gfx/ipc/gfx_param_traits.h"
diff --git a/content/common/content_message_generator.h b/content/common/content_message_generator.h index 81c35ed4..13a5a27 100644 --- a/content/common/content_message_generator.h +++ b/content/common/content_message_generator.h
@@ -49,6 +49,7 @@ #include "content/common/message_port_messages.h" #include "content/common/mime_registry_messages.h" #include "content/common/mojo/mojo_messages.h" +#include "content/common/page_messages.h" #include "content/common/pepper_messages.h" #include "content/common/platform_notification_messages.h" #include "content/common/plugin_process_messages.h"
diff --git a/content/common/content_switches_internal.h b/content/common/content_switches_internal.h index 990070c..1a829ea 100644 --- a/content/common/content_switches_internal.h +++ b/content/common/content_switches_internal.h
@@ -6,6 +6,7 @@ #define CONTENT_COMMON_CONTENT_SWITCHES_INTERNAL_H_ #include "build/build_config.h" +#include "content/common/content_export.h" #include "content/public/common/web_preferences.h" namespace content { @@ -20,7 +21,7 @@ #endif V8CacheOptions GetV8CacheOptions(); -bool IsUseZoomForDSFEnabled(); +CONTENT_EXPORT bool IsUseZoomForDSFEnabled(); } // namespace content
diff --git a/content/common/gpu/client/command_buffer_proxy_impl.cc b/content/common/gpu/client/command_buffer_proxy_impl.cc index 14a3003..648ffa8 100644 --- a/content/common/gpu/client/command_buffer_proxy_impl.cc +++ b/content/common/gpu/client/command_buffer_proxy_impl.cc
@@ -11,6 +11,7 @@ #include "base/logging.h" #include "base/memory/shared_memory.h" #include "base/stl_util.h" +#include "base/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "content/common/gpu/client/gpu_channel_host.h" #include "content/common/gpu/client/gpu_video_decode_accelerator_host.h"
diff --git a/content/common/gpu/client/gpu_video_encode_accelerator_host.cc b/content/common/gpu/client/gpu_video_encode_accelerator_host.cc index 45c8a27..553fa209 100644 --- a/content/common/gpu/client/gpu_video_encode_accelerator_host.cc +++ b/content/common/gpu/client/gpu_video_encode_accelerator_host.cc
@@ -94,14 +94,14 @@ channel_->AddRoute(route_id, weak_this_factory_.GetWeakPtr()); CreateVideoEncoderParams params; - params.command_buffer_route_id = impl_->route_id(); params.input_format = input_format; params.input_visible_size = input_visible_size; params.output_profile = output_profile; params.initial_bitrate = initial_bitrate; params.encoder_route_id = route_id; bool succeeded = false; - Send(new GpuCommandBufferMsg_CreateVideoEncoder(params, &succeeded)); + Send(new GpuCommandBufferMsg_CreateVideoEncoder(impl_->route_id(), params, + &succeeded)); if (!succeeded) { DLOG(ERROR) << "Send(GpuCommandBufferMsg_CreateVideoEncoder()) failed"; channel_->RemoveRoute(route_id);
diff --git a/content/common/gpu/gpu_channel.cc b/content/common/gpu/gpu_channel.cc index bb53c4b..127b1a1f 100644 --- a/content/common/gpu/gpu_channel.cc +++ b/content/common/gpu/gpu_channel.cc
@@ -34,7 +34,6 @@ #include "content/common/gpu/gpu_channel_manager_delegate.h" #include "content/common/gpu/gpu_memory_buffer_factory.h" #include "content/common/gpu/gpu_messages.h" -#include "content/public/common/content_switches.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/value_state.h" #include "gpu/command_buffer/service/gpu_scheduler.h"
diff --git a/content/common/gpu/gpu_channel_manager.h b/content/common/gpu/gpu_channel_manager.h index 0d55e0d9..b8c3518 100644 --- a/content/common/gpu/gpu_channel_manager.h +++ b/content/common/gpu/gpu_channel_manager.h
@@ -19,7 +19,6 @@ #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "content/common/content_export.h" -#include "content/common/content_param_traits.h" #include "content/common/gpu/gpu_memory_manager.h" #include "gpu/command_buffer/common/constants.h" #include "ui/gfx/gpu_memory_buffer.h"
diff --git a/content/common/gpu/gpu_messages.h b/content/common/gpu/gpu_messages.h index 0248caa1..fcf885d8 100644 --- a/content/common/gpu/gpu_messages.h +++ b/content/common/gpu/gpu_messages.h
@@ -17,7 +17,6 @@ #include "content/common/gpu/gpu_memory_uma_stats.h" #include "content/common/gpu/gpu_process_launch_causes.h" #include "content/common/gpu/gpu_stream_constants.h" -#include "content/public/common/common_param_traits.h" #include "gpu/command_buffer/common/capabilities.h" #include "gpu/command_buffer/common/command_buffer.h" #include "gpu/command_buffer/common/constants.h" @@ -26,7 +25,7 @@ #include "gpu/command_buffer/common/sync_token.h" #include "gpu/command_buffer/common/value_state.h" #include "gpu/config/gpu_info.h" -#include "gpu/ipc/gpu_command_buffer_traits.h" +#include "gpu/ipc/common/gpu_command_buffer_traits.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_message_macros.h" #include "ui/events/latency_info.h" @@ -36,6 +35,7 @@ #include "ui/gfx/native_widget_types.h" #include "ui/gfx/swap_result.h" #include "ui/gl/gpu_preference.h" +#include "url/ipc/url_param_traits.h" #if defined(OS_ANDROID) #include "content/common/android/surface_texture_peer.h"
diff --git a/content/common/gpu/media/android_video_decode_accelerator.cc b/content/common/gpu/media/android_video_decode_accelerator.cc index 3942a80..d8da2982 100644 --- a/content/common/gpu/media/android_video_decode_accelerator.cc +++ b/content/common/gpu/media/android_video_decode_accelerator.cc
@@ -23,6 +23,7 @@ #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/command_buffer/service/mailbox_manager.h" +#include "media/base/android/media_codec_bridge.h" #include "media/base/android/media_codec_util.h" #include "media/base/bind_to_current_loop.h" #include "media/base/bitstream_buffer.h" @@ -592,10 +593,12 @@ DismissPictureBuffers(); } + if (media_codec_->GetOutputSize(&size_) != media::MEDIA_CODEC_OK) { + POST_ERROR(PLATFORM_FAILURE, "GetOutputSize failed."); + return false; + } + picturebuffers_requested_ = true; - int32_t width, height; - media_codec_->GetOutputFormat(&width, &height); - size_ = gfx::Size(width, height); base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&AndroidVideoDecodeAccelerator::RequestPictureBuffers,
diff --git a/content/common/gpu/media/android_video_encode_accelerator.cc b/content/common/gpu/media/android_video_encode_accelerator.cc index d84673d6..5b70bd3 100644 --- a/content/common/gpu/media/android_video_encode_accelerator.cc +++ b/content/common/gpu/media/android_video_encode_accelerator.cc
@@ -335,7 +335,9 @@ uint8_t* buffer = NULL; size_t capacity = 0; - media_codec_->GetInputBuffer(input_buf_index, &buffer, &capacity); + status = media_codec_->GetInputBuffer(input_buf_index, &buffer, &capacity); + RETURN_ON_FAILURE(status == media::MEDIA_CODEC_OK, "GetInputBuffer failed.", + kPlatformFailureError); size_t queued_size = VideoFrame::AllocationSize(media::PIXEL_FORMAT_I420, frame->coded_size()); @@ -429,7 +431,10 @@ << shm->mapped_size(), kPlatformFailureError); - media_codec_->CopyFromOutputBuffer(buf_index, offset, shm->memory(), size); + media::MediaCodecStatus status = media_codec_->CopyFromOutputBuffer( + buf_index, offset, shm->memory(), size); + RETURN_ON_FAILURE(status == media::MEDIA_CODEC_OK, + "CopyFromOutputBuffer failed", kPlatformFailureError); media_codec_->ReleaseOutputBuffer(buf_index, false); --num_buffers_at_codec_;
diff --git a/content/common/gpu/media/create_video_encoder_params.cc b/content/common/gpu/media/create_video_encoder_params.cc index ea42994..c7ed248 100644 --- a/content/common/gpu/media/create_video_encoder_params.cc +++ b/content/common/gpu/media/create_video_encoder_params.cc
@@ -9,8 +9,7 @@ namespace content { CreateVideoEncoderParams::CreateVideoEncoderParams() - : command_buffer_route_id(MSG_ROUTING_NONE), - input_format(media::PIXEL_FORMAT_UNKNOWN), + : input_format(media::PIXEL_FORMAT_UNKNOWN), output_profile(media::VIDEO_CODEC_PROFILE_UNKNOWN), initial_bitrate(0), encoder_route_id(MSG_ROUTING_NONE) {}
diff --git a/content/common/gpu/media/create_video_encoder_params.h b/content/common/gpu/media/create_video_encoder_params.h index 39ff841..408cc8a 100644 --- a/content/common/gpu/media/create_video_encoder_params.h +++ b/content/common/gpu/media/create_video_encoder_params.h
@@ -14,7 +14,6 @@ struct CreateVideoEncoderParams { CreateVideoEncoderParams(); ~CreateVideoEncoderParams(); - int32_t command_buffer_route_id; media::VideoPixelFormat input_format; gfx::Size input_visible_size; media::VideoCodecProfile output_profile;
diff --git a/content/common/gpu/media/media_channel.cc b/content/common/gpu/media/media_channel.cc index fd850b6e8..c2b6eff4 100644 --- a/content/common/gpu/media/media_channel.cc +++ b/content/common/gpu/media/media_channel.cc
@@ -30,6 +30,31 @@ } // namespace +class MediaChannelDispatchHelper { + public: + MediaChannelDispatchHelper(MediaChannel* channel, int32_t routing_id) + : channel_(channel), routing_id_(routing_id) {} + + bool Send(IPC::Message* msg) { return channel_->Send(msg); } + + void OnCreateVideoDecoder(const media::VideoDecodeAccelerator::Config& config, + int32_t decoder_route_id, + IPC::Message* reply_message) { + channel_->OnCreateVideoDecoder(routing_id_, config, decoder_route_id, + reply_message); + } + + void OnCreateVideoEncoder(const CreateVideoEncoderParams& params, + IPC::Message* reply_message) { + channel_->OnCreateVideoEncoder(routing_id_, params, reply_message); + } + + private: + MediaChannel* const channel_; + const int32_t routing_id_; + DISALLOW_COPY_AND_ASSIGN(MediaChannelDispatchHelper); +}; + MediaChannel::MediaChannel(GpuChannel* channel) : channel_(channel) {} MediaChannel::~MediaChannel() {} @@ -39,12 +64,15 @@ } bool MediaChannel::OnMessageReceived(const IPC::Message& message) { + MediaChannelDispatchHelper helper(this, message.routing_id()); bool handled = true; IPC_BEGIN_MESSAGE_MAP(MediaChannel, message) - IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoDecoder, - OnCreateVideoDecoder) - IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuCommandBufferMsg_CreateVideoEncoder, - OnCreateVideoEncoder) + IPC_MESSAGE_FORWARD_DELAY_REPLY( + GpuCommandBufferMsg_CreateVideoDecoder, &helper, + MediaChannelDispatchHelper::OnCreateVideoDecoder) + IPC_MESSAGE_FORWARD_DELAY_REPLY( + GpuCommandBufferMsg_CreateVideoEncoder, &helper, + MediaChannelDispatchHelper::OnCreateVideoEncoder) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateJpegDecoder, OnCreateJpegDecoder) IPC_MESSAGE_UNHANDLED(handled = false) @@ -73,8 +101,11 @@ TRACE_EVENT0("gpu", "MediaChannel::OnCreateVideoDecoder"); GpuCommandBufferStub* stub = channel_->LookupCommandBuffer(command_buffer_route_id); - if (!stub) + if (!stub) { + reply_message->set_reply_error(); + Send(reply_message); return; + } GpuVideoDecodeAccelerator* decoder = new GpuVideoDecodeAccelerator( decoder_route_id, stub, stub->channel()->io_task_runner()); bool succeeded = decoder->Initialize(config); @@ -86,13 +117,17 @@ // self-delete during destruction of this stub. } -void MediaChannel::OnCreateVideoEncoder(const CreateVideoEncoderParams& params, +void MediaChannel::OnCreateVideoEncoder(int32_t command_buffer_route_id, + const CreateVideoEncoderParams& params, IPC::Message* reply_message) { TRACE_EVENT0("gpu", "MediaChannel::OnCreateVideoEncoder"); GpuCommandBufferStub* stub = - channel_->LookupCommandBuffer(params.command_buffer_route_id); - if (!stub) + channel_->LookupCommandBuffer(command_buffer_route_id); + if (!stub) { + reply_message->set_reply_error(); + Send(reply_message); return; + } GpuVideoEncodeAccelerator* encoder = new GpuVideoEncodeAccelerator(params.encoder_route_id, stub); bool succeeded =
diff --git a/content/common/gpu/media/media_channel.h b/content/common/gpu/media/media_channel.h index f3725d7..b6a00b2 100644 --- a/content/common/gpu/media/media_channel.h +++ b/content/common/gpu/media/media_channel.h
@@ -14,6 +14,7 @@ class GpuChannel; class GpuCommandBufferStub; +class MediaChannelDispatchHelper; struct CreateVideoEncoderParams; class MediaChannel : public IPC::Listener, public IPC::Sender { @@ -25,6 +26,8 @@ bool Send(IPC::Message* msg) override; private: + friend class MediaChannelDispatchHelper; + // IPC::Listener implementation: bool OnMessageReceived(const IPC::Message& message) override; @@ -34,7 +37,8 @@ const media::VideoDecodeAccelerator::Config& config, int32_t route_id, IPC::Message* reply_message); - void OnCreateVideoEncoder(const CreateVideoEncoderParams& params, + void OnCreateVideoEncoder(int32_t command_buffer_route_id, + const CreateVideoEncoderParams& params, IPC::Message* reply_message); GpuChannel* const channel_;
diff --git a/content/common/gpu/media/media_messages.h b/content/common/gpu/media/media_messages.h index d9e2df4f..e351d941 100644 --- a/content/common/gpu/media/media_messages.h +++ b/content/common/gpu/media/media_messages.h
@@ -103,7 +103,6 @@ IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(content::CreateVideoEncoderParams) - IPC_STRUCT_TRAITS_MEMBER(command_buffer_route_id) IPC_STRUCT_TRAITS_MEMBER(input_format) IPC_STRUCT_TRAITS_MEMBER(input_visible_size) IPC_STRUCT_TRAITS_MEMBER(output_profile) @@ -118,11 +117,10 @@ // Create and initialize a hardware video decoder using the specified route_id. // Created decoders should be freed with AcceleratedVideoDecoderMsg_Destroy when // no longer needed. -IPC_SYNC_MESSAGE_CONTROL3_1(GpuCommandBufferMsg_CreateVideoDecoder, - int32_t /* command_buffer_route_id */, - media::VideoDecodeAccelerator::Config /* config */, - int32_t /* decoder_route_id */, - bool /* succeeded */) +IPC_SYNC_MESSAGE_ROUTED2_1(GpuCommandBufferMsg_CreateVideoDecoder, + media::VideoDecodeAccelerator::Config /* config */, + int32_t /* decoder_route_id */, + bool /* succeeded */) // Set a CDM on the decoder to handle encrypted buffers. IPC_MESSAGE_ROUTED1(AcceleratedVideoDecoderMsg_SetCdm, int32_t /* CDM ID */) @@ -198,9 +196,9 @@ // Create and initialize a hardware video encoder using the specified route_id. // Created encoders should be freed with AcceleratedVideoEncoderMsg_Destroy when // no longer needed. -IPC_SYNC_MESSAGE_CONTROL1_1(GpuCommandBufferMsg_CreateVideoEncoder, - content::CreateVideoEncoderParams, - bool /* succeeded */) +IPC_SYNC_MESSAGE_ROUTED1_1(GpuCommandBufferMsg_CreateVideoEncoder, + content::CreateVideoEncoderParams, + bool /* succeeded */) // Queue a video frame to the encoder to encode. |frame_id| will be returned // by AcceleratedVideoEncoderHostMsg_NotifyInputDone.
diff --git a/content/common/mojo/mojo_shell_connection_impl.cc b/content/common/mojo/mojo_shell_connection_impl.cc index f631540..eb11c96 100644 --- a/content/common/mojo/mojo_shell_connection_impl.cc +++ b/content/common/mojo/mojo_shell_connection_impl.cc
@@ -96,8 +96,8 @@ void MojoShellConnectionImpl::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { initialized_ = true; }
diff --git a/content/common/mojo/mojo_shell_connection_impl.h b/content/common/mojo/mojo_shell_connection_impl.h index 73ae507..c63b174 100644 --- a/content/common/mojo/mojo_shell_connection_impl.h +++ b/content/common/mojo/mojo_shell_connection_impl.h
@@ -57,7 +57,7 @@ // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // MojoShellConnection:
diff --git a/content/common/page_messages.h b/content/common/page_messages.h new file mode 100644 index 0000000..284c1345 --- /dev/null +++ b/content/common/page_messages.h
@@ -0,0 +1,25 @@ +// 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 "ipc/ipc_message_macros.h" + +// IPC messages for page-level actions. +// Multiply-included message file, hence no include guard. + +#undef IPC_MESSAGE_EXPORT +#define IPC_MESSAGE_EXPORT CONTENT_EXPORT + +#define IPC_MESSAGE_START PageMsgStart + +// Messages sent from the browser to the renderer. + +IPC_MESSAGE_ROUTED1(PageMsg_UpdateWindowScreenRect, + gfx::Rect /* window_screen_rect */) + +// ----------------------------------------------------------------------------- +// Messages sent from the renderer to the browser. + +// Adding a new message? Stick to the sort order above: first platform +// independent PageMsg, then ifdefs for platform specific PageMsg, then platform +// independent PageHostMsg, then ifdefs for platform specific PageHostMsg.
diff --git a/content/common/sandbox_mac.h b/content/common/sandbox_mac.h index bac23f0d..afda387 100644 --- a/content/common/sandbox_mac.h +++ b/content/common/sandbox_mac.h
@@ -50,9 +50,6 @@ bool CompileAndApplyProfile(std::string* error); private: - // Frees all of the system resources allocated for the sandbox. - void FreeSandboxResources(void* profile, void* params, char* error); - // Storage of the key/value pairs of strings that are used in the sandbox // profile. std::map<std::string, std::string> params_map_;
diff --git a/content/common/sandbox_mac.mm b/content/common/sandbox_mac.mm index ca915a7..75199b1 100644 --- a/content/common/sandbox_mac.mm +++ b/content/common/sandbox_mac.mm
@@ -47,14 +47,10 @@ void CGSSetDenyWindowServerConnections(bool); void CGSShutdownServerConnections(); -void* sandbox_create_params(); -int sandbox_set_param(void* params, const char* key, const char* value); -void* sandbox_compile_string(const char* profile_str, - void* params, - char** error); -int sandbox_apply(void* profile); -void sandbox_free_params(void* params); -void sandbox_free_profile(void* profile); +int sandbox_init_with_parameters(const char* profile, + uint64_t flags, + const char* const parameters[], + char** errorbuf); }; namespace content { @@ -68,14 +64,6 @@ int sandbox_profile_resource_id; }; -// This is the internal definition of the structure used by sandbox parameters -// on OS X 10.6. -struct SandboxParams { - void* buf; - size_t count; - size_t size; -}; - // Mapping from sandbox process types to resource IDs containing the sandbox // profile for all process types known to content. SandboxTypeToResourceIDMapping kDefaultSandboxTypeToResourceIDMapping[] = { @@ -153,58 +141,24 @@ return params_map_.insert(std::make_pair(key, value)).second; } -void SandboxCompiler::FreeSandboxResources(void* profile, - void* params, - char* error) { - if (error) - sandbox_free_error(error); - if (params) - sandbox_free_params(params); - if (profile) - sandbox_free_profile(profile); -} - bool SandboxCompiler::CompileAndApplyProfile(std::string* error) { char* error_internal = nullptr; - void* profile = nullptr; - void* params = nullptr; + std::vector<const char*> params; - if (!params_map_.empty()) { - if (base::mac::IsOSSnowLeopard()) { - // This is a workaround for 10.6, see crbug.com/509114. - // Check that there is no integer overflow. - base::CheckedNumeric<size_t> checked_size = params_map_.size(); - checked_size *= 2; - if (!checked_size.IsValid()) - return false; - - SandboxParams* internal_params = - static_cast<SandboxParams*>(malloc(sizeof(SandboxParams))); - internal_params->buf = calloc(checked_size.ValueOrDie(), sizeof(void*)); - internal_params->count = 0; - internal_params->size = checked_size.ValueOrDie(); - params = internal_params; - } else { - params = sandbox_create_params(); - if (!params) - return false; - } - - for (const auto& kv : params_map_) - sandbox_set_param(params, kv.first.c_str(), kv.second.c_str()); + for (const auto& kv : params_map_) { + params.push_back(kv.first.c_str()); + params.push_back(kv.second.c_str()); } + // The parameters array must be null terminated. + params.push_back(static_cast<const char*>(0)); - profile = - sandbox_compile_string(profile_str_.c_str(), params, &error_internal); - if (!profile) { + if (sandbox_init_with_parameters(profile_str_.c_str(), 0, params.data(), + &error_internal)) { error->assign(error_internal); - FreeSandboxResources(profile, params, error_internal); + sandbox_free_error(error_internal); return false; } - - int result = sandbox_apply(profile); - FreeSandboxResources(profile, params, error_internal); - return result == 0; + return true; } // static
diff --git a/content/public/browser/browser_context.h b/content/public/browser/browser_context.h index 26a208c..6f199bb 100644 --- a/content/public/browser/browser_context.h +++ b/content/public/browser/browser_context.h
@@ -133,9 +133,9 @@ static void Initialize(BrowserContext* browser_context, const base::FilePath& path); - // Returns a randomized user ID number associated with this - // BrowserContext. This ID is not persistent across runs. - static uint32_t GetMojoUserIdFor(BrowserContext* browser_context); + // Returns a Mojo User ID associated with this BrowserContext. This ID is not + // persistent across runs. See mojo/shell/public/interfaces/connector.mojom. + static const std::string& GetMojoUserIdFor(BrowserContext* browser_context); ~BrowserContext() override;
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index a8e364b..4ee7eff8 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -48,6 +48,12 @@ const base::Feature kScrollAnchoring{"ScrollAnchoring", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables implementation of the Cache-Control: stale-while-revalidate directive +// which permits servers to allow the use of stale resources while revalidation +// proceeds in the background. See http://crbug.com/348877 +const base::Feature kStaleWhileRevalidate{"StaleWhileRevalidate2", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Enables token binding // (https://www.ietf.org/id/draft-ietf-tokbind-protocol-04.txt). const base::Feature kTokenBinding{"token-binding",
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 6c6a1ca1..32ae2f3 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -24,6 +24,7 @@ CONTENT_EXPORT extern const base::Feature kOptimizeIPCForSmallResource; CONTENT_EXPORT extern const base::Feature kRenderingPipelineThrottling; CONTENT_EXPORT extern const base::Feature kScrollAnchoring; +CONTENT_EXPORT extern const base::Feature kStaleWhileRevalidate; CONTENT_EXPORT extern const base::Feature kTokenBinding; CONTENT_EXPORT extern const base::Feature kUpdateRendererPriorityOnStartup; CONTENT_EXPORT extern const base::Feature kWebFontsIntervention;
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index 1dac476d..92b7dc4 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -90,6 +90,11 @@ // users with many windows/tabs and lots of memory. const char kDisableBackingStoreLimit[] = "disable-backing-store-limit"; +// Disable backgrounding renders for occluded windows. Done for tests to avoid +// nondeterministic behavior. +extern const char kDisableBackgroundingOccludedWindowsForTesting[] = + "disable-backgrounding-occluded-windows"; + // Disable one or more Blink runtime-enabled features. // Use names from RuntimeEnabledFeatures.in, separated by commas. // Applied after kEnableBlinkFeatures, and after other flags that change these @@ -438,11 +443,6 @@ // Enable spatial navigation const char kEnableSpatialNavigation[] = "enable-spatial-navigation"; -// Enables implementation of the Cache-Control: stale-while-revalidate directive -// which permits servers to allow the use of stale resources while revalidation -// proceeds in the background. -const char kEnableStaleWhileRevalidate[] = "enable-stale-while-revalidate"; - // Enables StatsTable, logging statistics to a global named shared memory table. const char kEnableStatsTable[] = "enable-stats-table";
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index 51322c3d5..6143111b 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -35,6 +35,8 @@ CONTENT_EXPORT extern const char kDisableAcceleratedMjpegDecode[]; CONTENT_EXPORT extern const char kDisableAcceleratedVideoDecode[]; extern const char kDisableBackingStoreLimit[]; +CONTENT_EXPORT extern const char + kDisableBackgroundingOccludedWindowsForTesting[]; CONTENT_EXPORT extern const char kDisableBlinkFeatures[]; CONTENT_EXPORT extern const char kDisableDatabases[]; CONTENT_EXPORT extern const char kDisableDelayAgnosticAec[]; @@ -131,7 +133,6 @@ CONTENT_EXPORT extern const char kEnableSlimmingPaintV2[]; CONTENT_EXPORT extern const char kEnableSmoothScrolling[]; CONTENT_EXPORT extern const char kEnableSpatialNavigation[]; -CONTENT_EXPORT extern const char kEnableStaleWhileRevalidate[]; CONTENT_EXPORT extern const char kEnableStatsTable[]; CONTENT_EXPORT extern const char kEnableStrictMixedContentChecking[]; CONTENT_EXPORT extern const char kEnableStrictPowerfulFeatureRestrictions[];
diff --git a/content/public/test/browser_test_base.cc b/content/public/test/browser_test_base.cc index 2e6500a8..7b7513a 100644 --- a/content/public/test/browser_test_base.cc +++ b/content/public/test/browser_test_base.cc
@@ -200,6 +200,11 @@ if (use_software_compositing_) command_line->AppendSwitch(switches::kDisableGpu); + // The layout of windows on screen is unpredictable during tests, so disable + // occlusion when running browser tests. + base::CommandLine::ForCurrentProcess()->AppendSwitch( + switches::kDisableBackgroundingOccludedWindowsForTesting); + #if defined(USE_AURA) // Most tests do not need pixel output, so we don't produce any. The command // line can override this behaviour to allow for visual debugging.
diff --git a/content/renderer/devtools/render_widget_screen_metrics_emulator.cc b/content/renderer/devtools/render_widget_screen_metrics_emulator.cc index 1022c27c..bad6fa72 100644 --- a/content/renderer/devtools/render_widget_screen_metrics_emulator.cc +++ b/content/renderer/devtools/render_widget_screen_metrics_emulator.cc
@@ -22,7 +22,6 @@ original_resize_params_(resize_params), original_view_screen_rect_(view_screen_rect), original_window_screen_rect_(window_screen_rect) { - Apply(); } RenderWidgetScreenMetricsEmulator::~RenderWidgetScreenMetricsEmulator() { @@ -140,6 +139,14 @@ delegate_->Redraw(); } +void RenderWidgetScreenMetricsEmulator::OnUpdateWindowScreenRect( + const gfx::Rect& window_screen_rect) { + original_window_screen_rect_ = window_screen_rect; + if (emulation_params_.screenPosition == + blink::WebDeviceEmulationParams::Desktop) + Apply(); +} + void RenderWidgetScreenMetricsEmulator::OnUpdateScreenRects( const gfx::Rect& view_screen_rect, const gfx::Rect& window_screen_rect) {
diff --git a/content/renderer/devtools/render_widget_screen_metrics_emulator.h b/content/renderer/devtools/render_widget_screen_metrics_emulator.h index 8288dfa..5650d0a3 100644 --- a/content/renderer/devtools/render_widget_screen_metrics_emulator.h +++ b/content/renderer/devtools/render_widget_screen_metrics_emulator.h
@@ -54,15 +54,16 @@ // The following methods alter handlers' behavior for messages related to // widget size and position. void OnResize(const ResizeParams& params); + void OnUpdateWindowScreenRect(const gfx::Rect& window_screen_rect); void OnUpdateScreenRects(const gfx::Rect& view_screen_rect, const gfx::Rect& window_screen_rect); void OnShowContextMenu(ContextMenuParams* params); gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor); - private: - // Apply original_resize_params_ + // Apply parameters to the render widget. void Apply(); + private: RenderWidgetScreenMetricsEmulatorDelegate* const delegate_; // Parameters as passed by RenderWidget::EnableScreenMetricsEmulation.
diff --git a/content/renderer/gpu/render_widget_compositor.h b/content/renderer/gpu/render_widget_compositor.h index ab2c72d..aacbfac8 100644 --- a/content/renderer/gpu/render_widget_compositor.h +++ b/content/renderer/gpu/render_widget_compositor.h
@@ -192,6 +192,8 @@ }; protected: + friend class RenderViewImplScaleFactorTest; + RenderWidgetCompositor(RenderWidgetCompositorDelegate* delegate, CompositorDependencies* compositor_deps);
diff --git a/content/renderer/media/android/webmediaplayer_android.cc b/content/renderer/media/android/webmediaplayer_android.cc index 0b6a7ff7..32c68c82 100644 --- a/content/renderer/media/android/webmediaplayer_android.cc +++ b/content/renderer/media/android/webmediaplayer_android.cc
@@ -320,9 +320,8 @@ CORSMode cors_mode) { DCHECK(main_thread_checker_.CalledOnValidThread()); - media::ReportMetrics( - load_type, GURL(url), - blink::WebStringToGURL(frame_->document().securityOrigin().toString())); + media::ReportMetrics(load_type, GURL(url), + frame_->document().securityOrigin()); switch (load_type) { case LoadTypeURL:
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 6b7e1ea..82e5f3c7 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -53,6 +53,7 @@ #include "content/common/frame_replication_state.h" #include "content/common/input_messages.h" #include "content/common/navigation_params.h" +#include "content/common/page_messages.h" #include "content/common/savable_subframe.h" #include "content/common/service_worker/service_worker_types.h" #include "content/common/site_isolation_policy.h" @@ -624,7 +625,8 @@ RenderFrameImpl::CreateRenderFrameImplFunction g_create_render_frame_impl = nullptr; -void OnGotInstanceID(uint32_t instance_id, uint32_t user_id) {} +void OnGotInstanceID(mojo::shell::mojom::ConnectResult result, + const std::string& user_id, uint32_t instance_id) {} WebString ConvertRelativePathToHtmlAttribute(const base::FilePath& path) { DCHECK(!path.IsAbsolute()); @@ -1350,6 +1352,14 @@ #endif bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) { + // Forward Page IPCs to the RenderView. + if ((IPC_MESSAGE_CLASS(msg) == PageMsgStart)) { + if (render_view()) + return render_view()->OnMessageReceived(msg); + + return false; + } + // We may get here while detaching, when the WebFrame has been deleted. Do // not process any messages in this state. if (!frame_) @@ -2873,30 +2883,24 @@ } void RenderFrameImpl::willSubmitForm(const blink::WebFormElement& form) { - // With PlzNavigate-enabled, this will be called before a DataSource has been - // set-up. - // TODO(clamy): make sure the internal state is properly updated at some - // point in the navigation. - if (!IsBrowserSideNavigationEnabled()) { - DocumentState* document_state = - DocumentState::FromDataSource(frame_->provisionalDataSource()); - NavigationStateImpl* navigation_state = - static_cast<NavigationStateImpl*>(document_state->navigation_state()); - InternalDocumentStateData* internal_data = - InternalDocumentStateData::FromDocumentState(document_state); + DocumentState* document_state = + DocumentState::FromDataSource(frame_->provisionalDataSource()); + NavigationStateImpl* navigation_state = + static_cast<NavigationStateImpl*>(document_state->navigation_state()); + InternalDocumentStateData* internal_data = + InternalDocumentStateData::FromDocumentState(document_state); - if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(), - ui::PAGE_TRANSITION_LINK)) { - navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT); - } - - // Save these to be processed when the ensuing navigation is committed. - WebSearchableFormData web_searchable_form_data(form); - internal_data->set_searchable_form_url(web_searchable_form_data.url()); - internal_data->set_searchable_form_encoding( - web_searchable_form_data.encoding().utf8()); + if (ui::PageTransitionCoreTypeIs(navigation_state->GetTransitionType(), + ui::PAGE_TRANSITION_LINK)) { + navigation_state->set_transition_type(ui::PAGE_TRANSITION_FORM_SUBMIT); } + // Save these to be processed when the ensuing navigation is committed. + WebSearchableFormData web_searchable_form_data(form); + internal_data->set_searchable_form_url(web_searchable_form_data.url()); + internal_data->set_searchable_form_encoding( + web_searchable_form_data.encoding().utf8()); + FOR_EACH_OBSERVER(RenderFrameObserver, observers_, WillSubmitForm(form)); } @@ -6084,9 +6088,9 @@ if (!connector_) GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&connector_)); mojo::shell::mojom::InterfaceProviderPtr interface_provider; - connector_->Connect( - url.spec(), mojo::shell::mojom::Connector::kUserInherit, - GetProxy(&interface_provider), nullptr, base::Bind(&OnGotInstanceID)); + connector_->Connect(url.spec(), mojo::shell::mojom::kInheritUserID, + GetProxy(&interface_provider), nullptr, + base::Bind(&OnGotInstanceID)); return interface_provider; }
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index a458db6..f57b159 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -35,8 +35,8 @@ #include "ipc/ipc_platform_file.h" #include "media/blink/webmediaplayer_delegate.h" #include "media/blink/webmediaplayer_params.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" #include "third_party/WebKit/public/platform/WebFocusType.h" #include "third_party/WebKit/public/platform/WebMediaPlayer.h" #include "third_party/WebKit/public/platform/modules/app_banner/WebAppBannerClient.h"
diff --git a/content/renderer/render_frame_proxy.cc b/content/renderer/render_frame_proxy.cc index 6a1286e..d31dab2 100644 --- a/content/renderer/render_frame_proxy.cc +++ b/content/renderer/render_frame_proxy.cc
@@ -14,6 +14,7 @@ #include "content/common/frame_messages.h" #include "content/common/frame_replication_state.h" #include "content/common/input_messages.h" +#include "content/common/page_messages.h" #include "content/common/site_isolation_policy.h" #include "content/common/swapped_out_messages.h" #include "content/common/view_messages.h" @@ -22,6 +23,7 @@ #include "content/renderer/render_thread_impl.h" #include "content/renderer/render_view_impl.h" #include "content/renderer/render_widget.h" +#include "ipc/ipc_message_macros.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" @@ -251,6 +253,14 @@ } bool RenderFrameProxy::OnMessageReceived(const IPC::Message& msg) { + // Forward Page IPCs to the RenderView. + if ((IPC_MESSAGE_CLASS(msg) == PageMsgStart)) { + if (render_view()) + return render_view()->OnMessageReceived(msg); + + return false; + } + bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameProxy, msg) IPC_MESSAGE_HANDLER(FrameMsg_DeleteProxy, OnDeleteProxy)
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 387a644..78360857 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -17,8 +17,10 @@ #include "base/time/time.h" #include "base/win/windows_version.h" #include "build/build_config.h" +#include "cc/trees/layer_tree_host.h" #include "content/child/request_extra_data.h" #include "content/child/service_worker/service_worker_network_provider.h" +#include "content/common/content_switches_internal.h" #include "content/common/frame_messages.h" #include "content/common/frame_replication_state.h" #include "content/common/site_isolation_policy.h" @@ -42,6 +44,7 @@ #include "content/public/test/test_utils.h" #include "content/renderer/accessibility/renderer_accessibility.h" #include "content/renderer/devtools/devtools_agent.h" +#include "content/renderer/gpu/render_widget_compositor.h" #include "content/renderer/history_controller.h" #include "content/renderer/history_serialization.h" #include "content/renderer/navigation_state_impl.h" @@ -421,7 +424,7 @@ }; class RenderViewImplScaleFactorTest : public RenderViewImplBlinkSettingsTest { - public: + protected: void SetDeviceScaleFactor(float dsf) { ResizeParams params; params.screen_info.deviceScaleFactor = dsf; @@ -432,6 +435,33 @@ view()->OnResize(params); ASSERT_EQ(dsf, view()->device_scale_factor_); } + + void TestEmulatedSizeDprDsf(int width, int height, float dpr, + float compositor_dsf) { + static base::string16 get_width = + base::ASCIIToUTF16("Number(window.innerWidth)"); + static base::string16 get_height = + base::ASCIIToUTF16("Number(window.innerHeight)"); + static base::string16 get_dpr = + base::ASCIIToUTF16("Number(window.devicePixelRatio * 10)"); + + int emulated_width, emulated_height; + int emulated_dpr; + blink::WebDeviceEmulationParams params; + params.viewSize.width = width; + params.viewSize.height = height; + params.deviceScaleFactor = dpr; + view()->OnEnableDeviceEmulation(params); + EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &emulated_width)); + EXPECT_EQ(width, emulated_width); + EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, + &emulated_height)); + EXPECT_EQ(height, emulated_height); + EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_dpr, &emulated_dpr)); + EXPECT_EQ(static_cast<int>(dpr * 10), emulated_dpr); + EXPECT_EQ(compositor_dsf, + view()->compositor()->layer_tree_host()->device_scale_factor()); + } }; // Ensure that the main RenderFrame is deleted and cleared from the RenderView @@ -1447,385 +1477,6 @@ } } -// Test that we can receive correct DOM events when we send input events -// through the RenderWidget::OnHandleInputEvent() function. -TEST_F(RenderViewImplTest, OnHandleKeyboardEvent) { -#if !defined(OS_MACOSX) - // Load an HTML page consisting of one <input> element and three - // contentediable <div> elements. - // The <input> element is used for sending keyboard events, and the <div> - // elements are used for writing DOM events in the following format: - // "<keyCode>,<shiftKey>,<controlKey>,<altKey>". - // TODO(hbono): <http://crbug.com/2215> Our WebKit port set |ev.metaKey| to - // true when pressing an alt key, i.e. the |ev.metaKey| value is not - // trustworthy. We will check the |ev.metaKey| value when this issue is fixed. - view()->set_send_content_state_immediately(true); - LoadHTML("<html>" - "<head>" - "<title></title>" - "<script type='text/javascript' language='javascript'>" - "function OnKeyEvent(ev) {" - " var result = document.getElementById(ev.type);" - " result.innerText =" - " (ev.which || ev.keyCode) + ',' +" - " ev.shiftKey + ',' +" - " ev.ctrlKey + ',' +" - " ev.altKey;" - " return true;" - "}" - "</script>" - "</head>" - "<body>" - "<input id='test' type='text'" - " onkeydown='return OnKeyEvent(event);'" - " onkeypress='return OnKeyEvent(event);'" - " onkeyup='return OnKeyEvent(event);'>" - "</input>" - "<div id='keydown' contenteditable='true'>" - "</div>" - "<div id='keypress' contenteditable='true'>" - "</div>" - "<div id='keyup' contenteditable='true'>" - "</div>" - "</body>" - "</html>"); - ExecuteJavaScriptForTests("document.getElementById('test').focus();"); - render_thread_->sink().ClearMessages(); - - static const MockKeyboard::Layout kLayouts[] = { -#if defined(OS_WIN) - // Since we ignore the mock keyboard layout on Linux and instead just use - // the screen's keyboard layout, these trivially pass. They are commented - // out to avoid the illusion that they work. - MockKeyboard::LAYOUT_ARABIC, - MockKeyboard::LAYOUT_CANADIAN_FRENCH, - MockKeyboard::LAYOUT_FRENCH, - MockKeyboard::LAYOUT_HEBREW, - MockKeyboard::LAYOUT_RUSSIAN, -#endif - MockKeyboard::LAYOUT_UNITED_STATES, - }; - - for (size_t i = 0; i < arraysize(kLayouts); ++i) { - // For each key code, we send three keyboard events. - // * we press only the key; - // * we press the key and a left-shift key, and; - // * we press the key and a right-alt (AltGr) key. - // For each modifiers, we need a string used for formatting its expected - // result. (See the above comment for its format.) - static const struct { - MockKeyboard::Modifiers modifiers; - const char* expected_result; - } kModifierData[] = { - {MockKeyboard::NONE, "false,false,false"}, - {MockKeyboard::LEFT_SHIFT, "true,false,false"}, -#if defined(OS_WIN) - {MockKeyboard::RIGHT_ALT, "false,false,true"}, -#endif - }; - - MockKeyboard::Layout layout = kLayouts[i]; - for (size_t j = 0; j < arraysize(kModifierData); ++j) { - // Virtual key codes used for this test. - static const int kKeyCodes[] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', - 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', - 'W', 'X', 'Y', 'Z', - ui::VKEY_OEM_1, - ui::VKEY_OEM_PLUS, - ui::VKEY_OEM_COMMA, - ui::VKEY_OEM_MINUS, - ui::VKEY_OEM_PERIOD, - ui::VKEY_OEM_2, - ui::VKEY_OEM_3, - ui::VKEY_OEM_4, - ui::VKEY_OEM_5, - ui::VKEY_OEM_6, - ui::VKEY_OEM_7, -#if defined(OS_WIN) - // Not sure how to handle this key on Linux. - ui::VKEY_OEM_8, -#endif - }; - - MockKeyboard::Modifiers modifiers = kModifierData[j].modifiers; - for (size_t k = 0; k < arraysize(kKeyCodes); ++k) { - // Send a keyboard event to the RenderView object. - // We should test a keyboard event only when the given keyboard-layout - // driver is installed in a PC and the driver can assign a Unicode - // charcter for the given tuple (key-code and modifiers). - int key_code = kKeyCodes[k]; - base::string16 char_code; - if (SendKeyEvent(layout, key_code, modifiers, &char_code) < 0) - continue; - - // Create an expected result from the virtual-key code, the character - // code, and the modifier-key status. - // We format a string that emulates a DOM-event string produced hy - // our JavaScript function. (See the above comment for the format.) - static char expected_result[1024]; - expected_result[0] = 0; - base::snprintf(&expected_result[0], - sizeof(expected_result), - "\n" // texts in the <input> element - "%d,%s\n" // texts in the first <div> element - "%d,%s\n" // texts in the second <div> element - "%d,%s", // texts in the third <div> element - key_code, kModifierData[j].expected_result, - static_cast<int>(char_code[0]), - kModifierData[j].expected_result, - key_code, kModifierData[j].expected_result); - - // Retrieve the text in the test page and compare it with the expected - // text created from a virtual-key code, a character code, and the - // modifier-key status. - const int kMaxOutputCharacters = 1024; - view()->GetWebView()->updateAllLifecyclePhases(); - std::string output = base::UTF16ToUTF8( - base::StringPiece16(WebFrameContentDumper::dumpFrameTreeAsText( - GetMainFrame(), kMaxOutputCharacters))); - EXPECT_EQ(expected_result, output); - } - } - } -#else - NOTIMPLEMENTED(); -#endif -} - -// Test that our EditorClientImpl class can insert characters when we send -// keyboard events through the RenderWidget::OnHandleInputEvent() function. -// This test is for preventing regressions caused only when we use non-US -// keyboards, such as Issue 10846. -// see http://crbug.com/244562 -#if defined(OS_WIN) -#define MAYBE_InsertCharacters DISABLED_InsertCharacters -#else -#define MAYBE_InsertCharacters InsertCharacters -#endif -TEST_F(RenderViewImplTest, MAYBE_InsertCharacters) { -#if !defined(OS_MACOSX) - static const struct { - MockKeyboard::Layout layout; - const wchar_t* expected_result; - } kLayouts[] = { -#if 0 - // Disabled these keyboard layouts because buildbots do not have their - // keyboard-layout drivers installed. - {MockKeyboard::LAYOUT_ARABIC, - L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" - L"\x0038\x0039\x0634\x0624\x064a\x062b\x0628\x0644" - L"\x0627\x0647\x062a\x0646\x0645\x0629\x0649\x062e" - L"\x062d\x0636\x0642\x0633\x0641\x0639\x0631\x0635" - L"\x0621\x063a\x0626\x0643\x003d\x0648\x002d\x0632" - L"\x0638\x0630\x062c\x005c\x062f\x0637\x0028\x0021" - L"\x0040\x0023\x0024\x0025\x005e\x0026\x002a\x0029" - L"\x0650\x007d\x005d\x064f\x005b\x0623\x00f7\x0640" - L"\x060c\x002f\x2019\x0622\x00d7\x061b\x064e\x064c" - L"\x064d\x2018\x007b\x064b\x0652\x0625\x007e\x003a" - L"\x002b\x002c\x005f\x002e\x061f\x0651\x003c\x007c" - L"\x003e\x0022\x0030\x0031\x0032\x0033\x0034\x0035" - L"\x0036\x0037\x0038\x0039\x0634\x0624\x064a\x062b" - L"\x0628\x0644\x0627\x0647\x062a\x0646\x0645\x0629" - L"\x0649\x062e\x062d\x0636\x0642\x0633\x0641\x0639" - L"\x0631\x0635\x0621\x063a\x0626\x0643\x003d\x0648" - L"\x002d\x0632\x0638\x0630\x062c\x005c\x062f\x0637" - }, - {MockKeyboard::LAYOUT_HEBREW, - L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" - L"\x0038\x0039\x05e9\x05e0\x05d1\x05d2\x05e7\x05db" - L"\x05e2\x05d9\x05df\x05d7\x05dc\x05da\x05e6\x05de" - L"\x05dd\x05e4\x002f\x05e8\x05d3\x05d0\x05d5\x05d4" - L"\x0027\x05e1\x05d8\x05d6\x05e3\x003d\x05ea\x002d" - L"\x05e5\x002e\x003b\x005d\x005c\x005b\x002c\x0028" - L"\x0021\x0040\x0023\x0024\x0025\x005e\x0026\x002a" - L"\x0029\x0041\x0042\x0043\x0044\x0045\x0046\x0047" - L"\x0048\x0049\x004a\x004b\x004c\x004d\x004e\x004f" - L"\x0050\x0051\x0052\x0053\x0054\x0055\x0056\x0057" - L"\x0058\x0059\x005a\x003a\x002b\x003e\x005f\x003c" - L"\x003f\x007e\x007d\x007c\x007b\x0022\x0030\x0031" - L"\x0032\x0033\x0034\x0035\x0036\x0037\x0038\x0039" - L"\x05e9\x05e0\x05d1\x05d2\x05e7\x05db\x05e2\x05d9" - L"\x05df\x05d7\x05dc\x05da\x05e6\x05de\x05dd\x05e4" - L"\x002f\x05e8\x05d3\x05d0\x05d5\x05d4\x0027\x05e1" - L"\x05d8\x05d6\x05e3\x003d\x05ea\x002d\x05e5\x002e" - L"\x003b\x005d\x005c\x005b\x002c" - }, -#endif -#if defined(OS_WIN) - // On Linux, the only way to test alternate keyboard layouts is to change - // the keyboard layout of the whole screen. I'm worried about the side - // effects this may have on the buildbots. - {MockKeyboard::LAYOUT_CANADIAN_FRENCH, - L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" - L"\x0038\x0039\x0061\x0062\x0063\x0064\x0065\x0066" - L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" - L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" - L"\x0077\x0078\x0079\x007a\x003b\x003d\x002c\x002d" - L"\x002e\x00e9\x003c\x0029\x0021\x0022\x002f\x0024" - L"\x0025\x003f\x0026\x002a\x0028\x0041\x0042\x0043" - L"\x0044\x0045\x0046\x0047\x0048\x0049\x004a\x004b" - L"\x004c\x004d\x004e\x004f\x0050\x0051\x0052\x0053" - L"\x0054\x0055\x0056\x0057\x0058\x0059\x005a\x003a" - L"\x002b\x0027\x005f\x002e\x00c9\x003e\x0030\x0031" - L"\x0032\x0033\x0034\x0035\x0036\x0037\x0038\x0039" - L"\x0061\x0062\x0063\x0064\x0065\x0066\x0067\x0068" - L"\x0069\x006a\x006b\x006c\x006d\x006e\x006f\x0070" - L"\x0071\x0072\x0073\x0074\x0075\x0076\x0077\x0078" - L"\x0079\x007a\x003b\x003d\x002c\x002d\x002e\x00e9" - L"\x003c" - }, - {MockKeyboard::LAYOUT_FRENCH, - L"\x00e0\x0026\x00e9\x0022\x0027\x0028\x002d\x00e8" - L"\x005f\x00e7\x0061\x0062\x0063\x0064\x0065\x0066" - L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" - L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" - L"\x0077\x0078\x0079\x007a\x0024\x003d\x002c\x003b" - L"\x003a\x00f9\x0029\x002a\x0021\x0030\x0031\x0032" - L"\x0033\x0034\x0035\x0036\x0037\x0038\x0039\x0041" - L"\x0042\x0043\x0044\x0045\x0046\x0047\x0048\x0049" - L"\x004a\x004b\x004c\x004d\x004e\x004f\x0050\x0051" - L"\x0052\x0053\x0054\x0055\x0056\x0057\x0058\x0059" - L"\x005a\x00a3\x002b\x003f\x002e\x002f\x0025\x00b0" - L"\x00b5\x00e0\x0026\x00e9\x0022\x0027\x0028\x002d" - L"\x00e8\x005f\x00e7\x0061\x0062\x0063\x0064\x0065" - L"\x0066\x0067\x0068\x0069\x006a\x006b\x006c\x006d" - L"\x006e\x006f\x0070\x0071\x0072\x0073\x0074\x0075" - L"\x0076\x0077\x0078\x0079\x007a\x0024\x003d\x002c" - L"\x003b\x003a\x00f9\x0029\x002a\x0021" - }, - {MockKeyboard::LAYOUT_RUSSIAN, - L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" - L"\x0038\x0039\x0444\x0438\x0441\x0432\x0443\x0430" - L"\x043f\x0440\x0448\x043e\x043b\x0434\x044c\x0442" - L"\x0449\x0437\x0439\x043a\x044b\x0435\x0433\x043c" - L"\x0446\x0447\x043d\x044f\x0436\x003d\x0431\x002d" - L"\x044e\x002e\x0451\x0445\x005c\x044a\x044d\x0029" - L"\x0021\x0022\x2116\x003b\x0025\x003a\x003f\x002a" - L"\x0028\x0424\x0418\x0421\x0412\x0423\x0410\x041f" - L"\x0420\x0428\x041e\x041b\x0414\x042c\x0422\x0429" - L"\x0417\x0419\x041a\x042b\x0415\x0413\x041c\x0426" - L"\x0427\x041d\x042f\x0416\x002b\x0411\x005f\x042e" - L"\x002c\x0401\x0425\x002f\x042a\x042d\x0030\x0031" - L"\x0032\x0033\x0034\x0035\x0036\x0037\x0038\x0039" - L"\x0444\x0438\x0441\x0432\x0443\x0430\x043f\x0440" - L"\x0448\x043e\x043b\x0434\x044c\x0442\x0449\x0437" - L"\x0439\x043a\x044b\x0435\x0433\x043c\x0446\x0447" - L"\x043d\x044f\x0436\x003d\x0431\x002d\x044e\x002e" - L"\x0451\x0445\x005c\x044a\x044d" - }, -#endif // defined(OS_WIN) - {MockKeyboard::LAYOUT_UNITED_STATES, - L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" - L"\x0038\x0039\x0061\x0062\x0063\x0064\x0065\x0066" - L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" - L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" - L"\x0077\x0078\x0079\x007a\x003b\x003d\x002c\x002d" - L"\x002e\x002f\x0060\x005b\x005c\x005d\x0027\x0029" - L"\x0021\x0040\x0023\x0024\x0025\x005e\x0026\x002a" - L"\x0028\x0041\x0042\x0043\x0044\x0045\x0046\x0047" - L"\x0048\x0049\x004a\x004b\x004c\x004d\x004e\x004f" - L"\x0050\x0051\x0052\x0053\x0054\x0055\x0056\x0057" - L"\x0058\x0059\x005a\x003a\x002b\x003c\x005f\x003e" - L"\x003f\x007e\x007b\x007c\x007d\x0022" -#if defined(OS_WIN) - // This is ifdefed out for Linux to correspond to the fact that we don't - // test alt+keystroke for now. - L"\x0030\x0031\x0032\x0033\x0034\x0035\x0036\x0037" - L"\x0038\x0039\x0061\x0062\x0063\x0064\x0065\x0066" - L"\x0067\x0068\x0069\x006a\x006b\x006c\x006d\x006e" - L"\x006f\x0070\x0071\x0072\x0073\x0074\x0075\x0076" - L"\x0077\x0078\x0079\x007a\x003b\x003d\x002c\x002d" - L"\x002e\x002f\x0060\x005b\x005c\x005d\x0027" -#endif - }, - }; - - for (size_t i = 0; i < arraysize(kLayouts); ++i) { - // Load an HTML page consisting of one <div> element. - // This <div> element is used by the EditorClientImpl class to insert - // characters received through the RenderWidget::OnHandleInputEvent() - // function. - view()->set_send_content_state_immediately(true); - LoadHTML("<html>" - "<head>" - "<title></title>" - "</head>" - "<body>" - "<div id='test' contenteditable='true'>" - "</div>" - "</body>" - "</html>"); - ExecuteJavaScriptForTests("document.getElementById('test').focus();"); - render_thread_->sink().ClearMessages(); - - // For each key code, we send three keyboard events. - // * Pressing only the key; - // * Pressing the key and a left-shift key, and; - // * Pressing the key and a right-alt (AltGr) key. - static const MockKeyboard::Modifiers kModifiers[] = { - MockKeyboard::NONE, - MockKeyboard::LEFT_SHIFT, -#if defined(OS_WIN) - MockKeyboard::RIGHT_ALT, -#endif - }; - - MockKeyboard::Layout layout = kLayouts[i].layout; - for (size_t j = 0; j < arraysize(kModifiers); ++j) { - // Virtual key codes used for this test. - static const int kKeyCodes[] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', - 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', - 'W', 'X', 'Y', 'Z', - ui::VKEY_OEM_1, - ui::VKEY_OEM_PLUS, - ui::VKEY_OEM_COMMA, - ui::VKEY_OEM_MINUS, - ui::VKEY_OEM_PERIOD, - ui::VKEY_OEM_2, - ui::VKEY_OEM_3, - ui::VKEY_OEM_4, - ui::VKEY_OEM_5, - ui::VKEY_OEM_6, - ui::VKEY_OEM_7, -#if defined(OS_WIN) - // Unclear how to handle this on Linux. - ui::VKEY_OEM_8, -#endif - }; - - MockKeyboard::Modifiers modifiers = kModifiers[j]; - for (size_t k = 0; k < arraysize(kKeyCodes); ++k) { - // Send a keyboard event to the RenderView object. - // We should test a keyboard event only when the given keyboard-layout - // driver is installed in a PC and the driver can assign a Unicode - // charcter for the given tuple (layout, key-code, and modifiers). - int key_code = kKeyCodes[k]; - base::string16 char_code; - if (SendKeyEvent(layout, key_code, modifiers, &char_code) < 0) - continue; - } - } - - // Retrieve the text in the test page and compare it with the expected - // text created from a virtual-key code, a character code, and the - // modifier-key status. - const int kMaxOutputCharacters = 4096; - view()->GetWebView()->updateAllLifecyclePhases(); - base::string16 output = WebFrameContentDumper::dumpFrameTreeAsText( - GetMainFrame(), kMaxOutputCharacters); - EXPECT_EQ(base::WideToUTF16(kLayouts[i].expected_result), output); - } -#else - NOTIMPLEMENTED(); -#endif -} - // Crashy, http://crbug.com/53247. TEST_F(RenderViewImplTest, DISABLED_DidFailProvisionalLoadWithErrorForError) { GetMainFrame()->enableViewSourceMode(true); @@ -2464,36 +2115,6 @@ ASSERT_NE((RendererAccessibility*) NULL, frame()->renderer_accessibility()); } -TEST_F(RenderViewImplTest, ScreenMetricsEmulation) { - LoadHTML("<body style='min-height:1000px;'></body>"); - - blink::WebDeviceEmulationParams params; - base::string16 get_width = base::ASCIIToUTF16("Number(window.innerWidth)"); - base::string16 get_height = base::ASCIIToUTF16("Number(window.innerHeight)"); - int width, height; - - params.viewSize.width = 327; - params.viewSize.height = 415; - view()->OnEnableDeviceEmulation(params); - EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &width)); - EXPECT_EQ(params.viewSize.width, width); - EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, &height)); - EXPECT_EQ(params.viewSize.height, height); - - params.viewSize.width = 1005; - params.viewSize.height = 1102; - view()->OnEnableDeviceEmulation(params); - EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &width)); - EXPECT_EQ(params.viewSize.width, width); - EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, &height)); - EXPECT_EQ(params.viewSize.height, height); - - view()->OnDisableDeviceEmulation(); - - view()->OnEnableDeviceEmulation(params); - // Don't disable here to test that emulation is being shutdown properly. -} - // Sanity check for the Navigation Timing API |navigationStart| override. We // are asserting only most basic constraints, as TimeTicks (passed as the // override) are not comparable with the wall time (returned by the Blink API). @@ -2662,10 +2283,10 @@ EXPECT_TRUE(settings()->viewportEnabled()); } -#if !defined(OS_CHROMEOS) -// UseZoomForDSF is enabled on ChromeOS. TEST_F(RenderViewImplScaleFactorTest, ConverViewportToWindowWithoutZoomForDSF) { DoSetUp(); + if (IsUseZoomForDSFEnabled()) + return; SetDeviceScaleFactor(2.f); blink::WebRect rect(20, 10, 200, 100); view()->convertViewportToWindow(&rect); @@ -2674,7 +2295,66 @@ EXPECT_EQ(200, rect.width); EXPECT_EQ(100, rect.height); } -#endif + +TEST_F(RenderViewImplScaleFactorTest, ScreenMetricsEmulationWithOriginalDSF1) { + DoSetUp(); + SetDeviceScaleFactor(1.f); + + LoadHTML("<body style='min-height:1000px;'></body>"); + { + SCOPED_TRACE("327x415 1dpr"); + TestEmulatedSizeDprDsf(327, 415, 1.f, 1.f); + } + { + SCOPED_TRACE("327x415 1.5dpr"); + TestEmulatedSizeDprDsf(327, 415, 1.5f, 1.f); + } + { + SCOPED_TRACE("1005x1102 2dpr"); + TestEmulatedSizeDprDsf(1005, 1102, 2.f, 1.f); + } + { + SCOPED_TRACE("1005x1102 3dpr"); + TestEmulatedSizeDprDsf(1005, 1102, 3.f, 1.f); + } + + view()->OnDisableDeviceEmulation(); + + blink::WebDeviceEmulationParams params; + view()->OnEnableDeviceEmulation(params); + // Don't disable here to test that emulation is being shutdown properly. +} + +TEST_F(RenderViewImplScaleFactorTest, ScreenMetricsEmulationWithOriginalDSF2) { + DoSetUp(); + SetDeviceScaleFactor(2.f); + float compositor_dsf = + IsUseZoomForDSFEnabled() ? 1.f : 2.f; + + LoadHTML("<body style='min-height:1000px;'></body>"); + { + SCOPED_TRACE("327x415 1dpr"); + TestEmulatedSizeDprDsf(327, 415, 1.f, compositor_dsf); + } + { + SCOPED_TRACE("327x415 1.5dpr"); + TestEmulatedSizeDprDsf(327, 415, 1.5f, compositor_dsf); + } + { + SCOPED_TRACE("1005x1102 2dpr"); + TestEmulatedSizeDprDsf(1005, 1102, 2.f, compositor_dsf); + } + { + SCOPED_TRACE("1005x1102 3dpr"); + TestEmulatedSizeDprDsf(1005, 1102, 3.f, compositor_dsf); + } + + view()->OnDisableDeviceEmulation(); + + blink::WebDeviceEmulationParams params; + view()->OnEnableDeviceEmulation(params); + // Don't disable here to test that emulation is being shutdown properly. +} TEST_F(RenderViewImplScaleFactorTest, ConverViewportToWindowWithZoomForDSF) { base::CommandLine::ForCurrentProcess()->AppendSwitch(
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 5c4f976..cc773a8 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -50,6 +50,7 @@ #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/input/input_event_utils.h" #include "content/common/input_messages.h" +#include "content/common/page_messages.h" #include "content/common/pepper_messages.h" #include "content/common/site_isolation_policy.h" #include "content/common/ssl_status_serialization.h" @@ -1281,22 +1282,22 @@ // RenderWidgetInputHandlerDelegate ----------------------------------------- -void RenderViewImpl::FocusChangeComplete() { - RenderWidget::FocusChangeComplete(); +void RenderViewImpl::RenderWidgetFocusChangeComplete() { FOR_EACH_OBSERVER(RenderViewObserver, observers_, FocusChangeComplete()); } -bool RenderViewImpl::HasTouchEventHandlersAt(const gfx::Point& point) const { +bool RenderViewImpl::DoesRenderWidgetHaveTouchEventHandlersAt( + const gfx::Point& point) const { if (!webview()) return false; return webview()->hasTouchEventHandlersAt(point); } -void RenderViewImpl::OnDidHandleKeyEvent() { +void RenderViewImpl::RenderWidgetDidHandleKeyEvent() { ClearEditCommands(); } -bool RenderViewImpl::WillHandleGestureEvent( +bool RenderViewImpl::RenderWidgetWillHandleGestureEvent( const blink::WebGestureEvent& event) { possible_drag_event_info_.event_source = ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH; @@ -1305,7 +1306,8 @@ return false; } -bool RenderViewImpl::WillHandleMouseEvent(const blink::WebMouseEvent& event) { +bool RenderViewImpl::RenderWidgetWillHandleMouseEvent( + const blink::WebMouseEvent& event) { possible_drag_event_info_.event_source = ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE; possible_drag_event_info_.event_location = @@ -1404,6 +1406,8 @@ OnReleaseDisambiguationPopupBitmap) IPC_MESSAGE_HANDLER(ViewMsg_ForceRedraw, OnForceRedraw) IPC_MESSAGE_HANDLER(ViewMsg_SelectWordAroundCaret, OnSelectWordAroundCaret) + IPC_MESSAGE_HANDLER(PageMsg_UpdateWindowScreenRect, + OnUpdateWindowScreenRect) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(ViewMsg_UpdateTopControlsState, OnUpdateTopControlsState) @@ -1475,7 +1479,7 @@ const gfx::Rect& rect) { if (has_scrolled_focused_editable_node_into_rect_ && rect == rect_for_scrolled_focused_editable_node_) { - FocusChangeComplete(); + GetWidget()->FocusChangeComplete(); return; } @@ -1488,7 +1492,7 @@ } if (!will_animate) - FocusChangeComplete(); + GetWidget()->FocusChangeComplete(); } void RenderViewImpl::OnSetEditCommandsForNextKeyEvent( @@ -1511,6 +1515,10 @@ webview()->setInitialFocus(reverse); } +void RenderViewImpl::OnUpdateWindowScreenRect(gfx::Rect window_screen_rect) { + RenderWidget::OnUpdateWindowScreenRect(window_screen_rect); +} + #if defined(OS_MACOSX) void RenderViewImpl::OnSetInLiveResize(bool in_live_resize) { if (!webview()) @@ -3145,7 +3153,7 @@ } void RenderViewImpl::DidCompletePageScaleAnimation() { - FocusChangeComplete(); + GetWidget()->FocusChangeComplete(); } void RenderViewImpl::OnDeviceScaleFactorChanged() {
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index bdab8584..f03fc17 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -317,15 +317,6 @@ const gfx::Size& max_size); void DisableAutoResizeForTesting(const gfx::Size& new_size); - // RenderWidgetInputHandlerDelegate implementation --------------------------- - - // Most methods are handled by RenderWidget - void FocusChangeComplete() override; - bool HasTouchEventHandlersAt(const gfx::Point& point) const override; - void OnDidHandleKeyEvent() override; - bool WillHandleGestureEvent(const blink::WebGestureEvent& event) override; - bool WillHandleMouseEvent(const blink::WebMouseEvent& event) override; - // IPC::Listener implementation ---------------------------------------------- bool OnMessageReceived(const IPC::Message& msg) override; @@ -547,7 +538,10 @@ FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, GetCompositionCharacterBoundsTest); FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnNavigationHttpPost); - FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ScreenMetricsEmulation); + FRIEND_TEST_ALL_PREFIXES(RenderViewImplScaleFactorTest, + ScreenMetricsEmulationWithOriginalDSF1); + FRIEND_TEST_ALL_PREFIXES(RenderViewImplScaleFactorTest, + ScreenMetricsEmulationWithOriginalDSF2); FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, DecideNavigationPolicyHandlesAllTopLevel); #if defined(OS_MACOSX) @@ -582,6 +576,14 @@ void RenderWidgetDidSetColorProfile( const std::vector<char>& color_profile) override; + void RenderWidgetFocusChangeComplete() override; + bool DoesRenderWidgetHaveTouchEventHandlersAt( + const gfx::Point& point) const override; + void RenderWidgetDidHandleKeyEvent() override; + bool RenderWidgetWillHandleGestureEvent( + const blink::WebGestureEvent& event) override; + bool RenderWidgetWillHandleMouseEvent( + const blink::WebMouseEvent& event) override; // Old WebFrameClient implementations ---------------------------------------- @@ -694,6 +696,9 @@ const gfx::Rect& view_frame); #endif + // Page message handlers ----------------------------------------------------- + void OnUpdateWindowScreenRect(gfx::Rect window_screen_rect); + // Adding a new message handler? Please add it in alphabetical order above // and put it in the same position in the .cc file.
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 548d676..8220160 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -591,6 +591,7 @@ resize_params.display_mode = display_mode_; screen_metrics_emulator_.reset(new RenderWidgetScreenMetricsEmulator( this, params, resize_params, view_screen_rect_, window_screen_rect_)); + screen_metrics_emulator_->Apply(); } else { screen_metrics_emulator_->ChangeEmulationParams(params); } @@ -923,9 +924,15 @@ /////////////////////////////////////////////////////////////////////////////// // RenderWidgetInputHandlerDelegate -void RenderWidget::FocusChangeComplete() {} +void RenderWidget::FocusChangeComplete() { + if (owner_delegate_) + owner_delegate_->RenderWidgetFocusChangeComplete(); +} bool RenderWidget::HasTouchEventHandlersAt(const gfx::Point& point) const { + if (owner_delegate_) + return owner_delegate_->DoesRenderWidgetHaveTouchEventHandlersAt(point); + return true; } @@ -950,7 +957,10 @@ } } -void RenderWidget::OnDidHandleKeyEvent() {} +void RenderWidget::OnDidHandleKeyEvent() { + if (owner_delegate_) + owner_delegate_->RenderWidgetDidHandleKeyEvent(); +} void RenderWidget::OnDidOverscroll(const DidOverscrollParams& params) { Send(new InputHostMsg_DidOverscroll(routing_id_, params)); @@ -1044,10 +1054,16 @@ } bool RenderWidget::WillHandleGestureEvent(const blink::WebGestureEvent& event) { + if (owner_delegate_) + return owner_delegate_->RenderWidgetWillHandleGestureEvent(event); + return false; } bool RenderWidget::WillHandleMouseEvent(const blink::WebMouseEvent& event) { + if (owner_delegate_) + return owner_delegate_->RenderWidgetWillHandleMouseEvent(event); + return false; } @@ -1102,8 +1118,11 @@ top_controls_shrink_blink_size_); if (resized) { - gfx::Size new_widget_size = - IsUseZoomForDSFEnabled() ? physical_backing_size_ : size_; + gfx::Size new_widget_size = size_; + if (IsUseZoomForDSFEnabled()) { + new_widget_size = gfx::ScaleToCeiledSize(new_widget_size, + GetOriginalDeviceScaleFactor()); + } // When resizing, we want to wait to paint before ACK'ing the resize. This // ensures that we only resize as fast as we can paint. We only need to // send an ACK if we are resized to a non-empty rect. @@ -1112,8 +1131,9 @@ WebSize visual_viewport_size; if (IsUseZoomForDSFEnabled()) { - visual_viewport_size = gfx::ScaleToCeiledSize(params.visible_viewport_size, - device_scale_factor_); + visual_viewport_size = gfx::ScaleToCeiledSize( + params.visible_viewport_size, + GetOriginalDeviceScaleFactor()); } else { visual_viewport_size = visible_viewport_size_; } @@ -1480,9 +1500,8 @@ void RenderWidget::OnDeviceScaleFactorChanged() { if (!compositor_) return; - if (IsUseZoomForDSFEnabled()) - compositor_->SetPaintedDeviceScaleFactor(device_scale_factor_); + compositor_->SetPaintedDeviceScaleFactor(GetOriginalDeviceScaleFactor()); else compositor_->setDeviceScaleFactor(device_scale_factor_); } @@ -1527,6 +1546,15 @@ Send(new ViewHostMsg_UpdateScreenRects_ACK(routing_id())); } +void RenderWidget::OnUpdateWindowScreenRect( + const gfx::Rect& window_screen_rect) { + if (screen_metrics_emulator_) { + screen_metrics_emulator_->OnUpdateWindowScreenRect(window_screen_rect); + } else { + window_screen_rect_ = window_screen_rect; + } +} + void RenderWidget::OnSetSurfaceIdNamespace(uint32_t surface_id_namespace) { if (compositor_) compositor_->SetSurfaceIdNamespace(surface_id_namespace); @@ -1573,7 +1601,7 @@ void RenderWidget::convertViewportToWindow(blink::WebRect* rect) { if (IsUseZoomForDSFEnabled()) { - float reverse = 1 / device_scale_factor_; + float reverse = 1 / GetOriginalDeviceScaleFactor(); // TODO(oshima): We may need to allow pixel precision here as the the // anchor element can be placed at half pixel. gfx::Rect window_rect = @@ -1587,10 +1615,10 @@ void RenderWidget::convertWindowToViewport(blink::WebFloatRect* rect) { if (IsUseZoomForDSFEnabled()) { - rect->x *= device_scale_factor_; - rect->y *= device_scale_factor_; - rect->width *= device_scale_factor_; - rect->height *= device_scale_factor_; + rect->x *= GetOriginalDeviceScaleFactor(); + rect->y *= GetOriginalDeviceScaleFactor(); + rect->width *= GetOriginalDeviceScaleFactor(); + rect->height *= GetOriginalDeviceScaleFactor(); } } @@ -2130,4 +2158,11 @@ MESSAGE_DELIVERY_POLICY_WITH_VISUAL_STATE); } +float RenderWidget::GetOriginalDeviceScaleFactor() const { + return + screen_metrics_emulator_ ? + screen_metrics_emulator_->original_screen_info().deviceScaleFactor : + device_scale_factor_; +} + } // namespace content
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index 4830733..d189feb 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -468,6 +468,7 @@ void OnGetFPS(); void OnUpdateScreenRects(const gfx::Rect& view_screen_rect, const gfx::Rect& window_screen_rect); + void OnUpdateWindowScreenRect(const gfx::Rect& window_screen_rect); void OnShowImeIfNeeded(); void OnSetSurfaceIdNamespace(uint32_t surface_id_namespace); void OnHandleCompositorProto(const std::vector<uint8_t>& proto); @@ -780,6 +781,10 @@ scoped_ptr<scheduler::RenderWidgetSchedulingState> render_widget_scheduling_state_; + private: + // When emulated, this returns original device scale factor. + float GetOriginalDeviceScaleFactor() const; + DISALLOW_COPY_AND_ASSIGN(RenderWidget); };
diff --git a/content/renderer/render_widget_owner_delegate.h b/content/renderer/render_widget_owner_delegate.h index d7aa0838..309324ae 100644 --- a/content/renderer/render_widget_owner_delegate.h +++ b/content/renderer/render_widget_owner_delegate.h
@@ -7,6 +7,15 @@ #include "content/common/content_export.h" +namespace blink { +class WebGestureEvent; +class WebMouseEvent; +} + +namespace gfx { +class Point; +} + namespace content { // @@ -21,6 +30,16 @@ virtual void RenderWidgetDidSetColorProfile( const std::vector<char>& color_profile) = 0; + // As in RenderWidgetInputHandlerDelegate. + virtual void RenderWidgetFocusChangeComplete() = 0; + virtual bool DoesRenderWidgetHaveTouchEventHandlersAt( + const gfx::Point& point) const = 0; + virtual void RenderWidgetDidHandleKeyEvent() = 0; + virtual bool RenderWidgetWillHandleGestureEvent( + const blink::WebGestureEvent& event) = 0; + virtual bool RenderWidgetWillHandleMouseEvent( + const blink::WebMouseEvent& event) = 0; + protected: virtual ~RenderWidgetOwnerDelegate() {} };
diff --git a/content/renderer/usb/web_usb_device_impl.cc b/content/renderer/usb/web_usb_device_impl.cc index d5dcf2f..d0cedd51 100644 --- a/content/renderer/usb/web_usb_device_impl.cc +++ b/content/renderer/usb/web_usb_device_impl.cc
@@ -13,7 +13,7 @@ #include "content/child/scoped_web_callbacks.h" #include "content/renderer/usb/type_converters.h" #include "mojo/shell/public/cpp/connect.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/platform/modules/webusb/WebUSBDeviceInfo.h" #include "third_party/WebKit/public/platform/modules/webusb/WebUSBTransferInfo.h"
diff --git a/content/shell/browser/shell_content_browser_client.cc b/content/shell/browser/shell_content_browser_client.cc index 2731368..39eb87e 100644 --- a/content/shell/browser/shell_content_browser_client.cc +++ b/content/shell/browser/shell_content_browser_client.cc
@@ -234,10 +234,6 @@ base::CommandLine* command_line, int child_process_id) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDumpLineBoxTrees)) { - command_line->AppendSwitch(switches::kDumpLineBoxTrees); - } - if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableFontAntialiasing)) { command_line->AppendSwitch(switches::kEnableFontAntialiasing); }
diff --git a/content/shell/common/shell_messages.h b/content/shell/common/shell_messages.h index acbbfb01..7a0b1f93 100644 --- a/content/shell/common/shell_messages.h +++ b/content/shell/common/shell_messages.h
@@ -35,8 +35,6 @@ IPC_STRUCT_TRAITS_MEMBER(dump_child_frames_as_markup) IPC_STRUCT_TRAITS_MEMBER(dump_child_frame_scroll_positions) IPC_STRUCT_TRAITS_MEMBER(is_printing) - IPC_STRUCT_TRAITS_MEMBER(dump_line_box_trees) - IPC_STRUCT_TRAITS_MEMBER(debug_render_tree) IPC_STRUCT_TRAITS_END() // Tells the renderer to reset all test runners.
diff --git a/content/shell/common/shell_switches.cc b/content/shell/common/shell_switches.cc index 25c1070..a125244 100644 --- a/content/shell/common/shell_switches.cc +++ b/content/shell/common/shell_switches.cc
@@ -28,10 +28,6 @@ // causes the leak detector to cause immediate crash when found leak. const char kCrashOnFailure[] = "crash-on-failure"; -// When run-layout-test is enabled, this causes the line box tree for -// each LayoutBlockFlow to be dumped as well. -const char kDumpLineBoxTrees[] = "dump-line-box-trees"; - // Enable accelerated 2D canvas. const char kEnableAccelerated2DCanvas[] = "enable-accelerated-2d-canvas";
diff --git a/content/shell/common/shell_switches.h b/content/shell/common/shell_switches.h index db78614..4c61a11 100644 --- a/content/shell/common/shell_switches.h +++ b/content/shell/common/shell_switches.h
@@ -18,7 +18,6 @@ extern const char kContentShellDataPath[]; extern const char kCrashDumpsDir[]; extern const char kCrashOnFailure[]; -extern const char kDumpLineBoxTrees[]; extern const char kEnableAccelerated2DCanvas[]; extern const char kEnableFontAntialiasing[]; extern const char kAlwaysUseComplexText[];
diff --git a/content/shell/renderer/layout_test/blink_test_runner.cc b/content/shell/renderer/layout_test/blink_test_runner.cc index 6bc6ad4..633757842 100644 --- a/content/shell/renderer/layout_test/blink_test_runner.cc +++ b/content/shell/renderer/layout_test/blink_test_runner.cc
@@ -889,12 +889,8 @@ return; } - test_runner::LayoutDumpFlags layout_dump_flags = + const test_runner::LayoutDumpFlags& layout_dump_flags = interfaces->TestRunner()->GetLayoutDumpFlags(); - layout_dump_flags.dump_line_box_trees = - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDumpLineBoxTrees); - if (!layout_dump_flags.dump_child_frames()) { std::string layout_dump = DumpLayout( render_view()->GetMainRenderFrame()->GetWebFrame(), layout_dump_flags);
diff --git a/content/test/data/accessibility/aria/aria-posinset-expected-android.txt b/content/test/data/accessibility/aria/aria-posinset-expected-android.txt index 2d8a8cb..cde02d8 100644 --- a/content/test/data/accessibility/aria/aria-posinset-expected-android.txt +++ b/content/test/data/accessibility/aria/aria-posinset-expected-android.txt
@@ -1,12 +1,36 @@ android.webkit.WebView focusable focused scrollable -++android.widget.ListView role_description='list box' collection item_count=4 row_count=4 +++android.widget.ListView role_description='list box' collection item_count=2 row_count=2 ++++android.view.View clickable collection_item focusable name='Item 1' ++++android.view.View clickable collection_item focusable name='Item 2' item_index=1 row_index=1 -++++android.view.View clickable collection_item focusable name='Item 3' item_index=2 row_index=2 -++++android.view.View clickable collection_item focusable name='Item 4' item_index=3 row_index=3 -++android.widget.ListView role_description='list box' collection item_count=5 row_count=5 +++android.widget.ListView role_description='list box' collection item_count=2 row_count=2 ++++android.view.View clickable collection_item focusable name='Item 1' ++++android.view.View clickable collection_item focusable name='Item 2' item_index=1 row_index=1 -++++android.view.View clickable collection_item focusable name='Item 3' item_index=2 row_index=2 -++++android.view.View clickable collection_item focusable name='Item 4' item_index=3 row_index=3 -++++android.view.View clickable collection_item focusable name='Item 5' item_index=4 row_index=4 \ No newline at end of file +++android.view.View +++++android.widget.RadioButton role_description='radio button' checkable clickable focusable +++++android.view.View clickable name='1' +++++android.view.View clickable name=' +' +++++android.widget.RadioButton role_description='radio button' checkable clickable focusable +++++android.view.View clickable name='2' +++android.view.View +++++android.widget.RadioButton role_description='radio button' checkable clickable focusable +++++android.view.View clickable name='Apple' +++++android.view.View clickable name=' +' +++++android.widget.RadioButton role_description='radio button' checkable clickable focusable +++++android.view.View clickable name='Banana' +++android.view.View name='Cake' +++++android.view.View clickable name='Cake' +++++android.view.View +++++++android.widget.RadioButton role_description='radio button' checkable checked clickable focusable name='Chiffon cakes' +++++++android.view.View clickable name=' +' +++++++android.widget.RadioButton role_description='radio button' checkable clickable focusable name='Chocolate cakes' +++android.view.View +++++android.view.View +++++++android.widget.Button role_description='button' clickable focusable name='changedFromRadio' +++++++android.view.View clickable name='red' +++++++android.view.View clickable name=' +' +++++++android.widget.RadioButton role_description='radio button' checkable clickable focusable name='blue' +++android.view.View clickable name='Done' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-posinset-expected-mac.txt b/content/test/data/accessibility/aria/aria-posinset-expected-mac.txt index 4106f47..14e45d9 100644 --- a/content/test/data/accessibility/aria/aria-posinset-expected-mac.txt +++ b/content/test/data/accessibility/aria/aria-posinset-expected-mac.txt
@@ -1,12 +1,39 @@ AXWebArea AXRoleDescription='HTML content' ++AXList AXRoleDescription='list' -++++AXStaticText AXRoleDescription='text' AXValue='Item 1' AXARIASetSize='4' AXARIAPosInSet='1' -++++AXStaticText AXRoleDescription='text' AXValue='Item 2' AXARIASetSize='4' AXARIAPosInSet='2' -++++AXStaticText AXRoleDescription='text' AXValue='Item 3' AXARIASetSize='4' AXARIAPosInSet='3' -++++AXStaticText AXRoleDescription='text' AXValue='Item 4' AXARIASetSize='4' AXARIAPosInSet='4' +++++AXStaticText AXRoleDescription='text' AXValue='Item 1' AXARIASetSize='2' AXARIAPosInSet='1' +++++AXStaticText AXRoleDescription='text' AXValue='Item 2' AXARIASetSize='2' AXARIAPosInSet='2' ++AXList AXRoleDescription='list' -++++AXStaticText AXRoleDescription='text' AXValue='Item 1' AXARIASetSize='5' AXARIAPosInSet='1' -++++AXStaticText AXRoleDescription='text' AXValue='Item 2' AXARIASetSize='5' AXARIAPosInSet='2' -++++AXStaticText AXRoleDescription='text' AXValue='Item 3' AXARIASetSize='5' AXARIAPosInSet='3' -++++AXStaticText AXRoleDescription='text' AXValue='Item 4' AXARIASetSize='5' AXARIAPosInSet='4' -++++AXStaticText AXRoleDescription='text' AXValue='Item 5' AXARIASetSize='5' AXARIAPosInSet='5' +++++AXStaticText AXRoleDescription='text' AXValue='Item 1' AXARIASetSize='2' AXARIAPosInSet='1' +++++AXStaticText AXRoleDescription='text' AXValue='Item 2' AXARIASetSize='2' AXARIAPosInSet='2' +++AXGroup AXRoleDescription='form' +++++AXRadioButton AXRoleDescription='radio button' AXValue='0' AXARIASetSize='4' AXARIAPosInSet='3' +++++AXStaticText AXRoleDescription='text' AXValue='1' +++++AXUnknown AXRoleDescription='unknown' AXTitle=' +' +++++AXRadioButton AXRoleDescription='radio button' AXValue='0' AXARIASetSize='4' AXARIAPosInSet='4' +++++AXStaticText AXRoleDescription='text' AXValue='2' +++AXGroup AXRoleDescription='group' +++++AXRadioButton AXRoleDescription='radio button' AXValue='0' AXARIASetSize='2' AXARIAPosInSet='1' +++++AXStaticText AXRoleDescription='text' AXValue='Apple' +++++AXUnknown AXRoleDescription='unknown' AXTitle=' +' +++++AXRadioButton AXRoleDescription='radio button' AXValue='0' AXARIASetSize='2' AXARIAPosInSet='2' +++++AXStaticText AXRoleDescription='text' AXValue='Banana' +++AXGroup AXRoleDescription='group' AXDescription='Cake' AXTitleUIElement='AXGroup' +++++AXGroup AXRoleDescription='group' +++++++AXStaticText AXRoleDescription='text' AXValue='Cake' +++++AXGroup AXRoleDescription='group' +++++++AXRadioButton AXRoleDescription='radio button' AXTitle='Chiffon cakes' AXValue='1' AXARIASetSize='2' AXARIAPosInSet='1' +++++++AXUnknown AXRoleDescription='unknown' AXTitle=' +' +++++++AXRadioButton AXRoleDescription='radio button' AXTitle='Chocolate cakes' AXValue='0' AXARIASetSize='2' AXARIAPosInSet='2' +++AXGroup AXRoleDescription='form' +++++AXGroup AXRoleDescription='group' +++++++AXButton AXRoleDescription='button' AXTitle='changedFromRadio' +++++++AXGroup AXRoleDescription='group' +++++++++AXStaticText AXRoleDescription='text' AXValue='red' +++++++AXUnknown AXRoleDescription='unknown' AXTitle=' +' +++++++AXRadioButton AXRoleDescription='radio button' AXTitle='blue' AXValue='0' AXARIASetSize='1' AXARIAPosInSet='1' +++AXGroup AXRoleDescription='group' +++++AXStaticText AXRoleDescription='text' AXValue='Done' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-posinset-expected-win.txt b/content/test/data/accessibility/aria/aria-posinset-expected-win.txt index 6cae42b..401ab3e1 100644 --- a/content/test/data/accessibility/aria/aria-posinset-expected-win.txt +++ b/content/test/data/accessibility/aria/aria-posinset-expected-win.txt
@@ -1,12 +1,39 @@ ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE ++ROLE_SYSTEM_LIST -++++ROLE_SYSTEM_LISTITEM name='Item 1' FOCUSABLE setsize:4 posinset:1 -++++ROLE_SYSTEM_LISTITEM name='Item 2' FOCUSABLE setsize:4 posinset:2 -++++ROLE_SYSTEM_LISTITEM name='Item 3' FOCUSABLE setsize:4 posinset:3 -++++ROLE_SYSTEM_LISTITEM name='Item 4' FOCUSABLE setsize:4 posinset:4 +++++ROLE_SYSTEM_LISTITEM name='Item 1' FOCUSABLE setsize:2 posinset:1 +++++ROLE_SYSTEM_LISTITEM name='Item 2' FOCUSABLE setsize:2 posinset:2 ++ROLE_SYSTEM_LIST -++++ROLE_SYSTEM_LISTITEM name='Item 1' FOCUSABLE setsize:5 posinset:1 -++++ROLE_SYSTEM_LISTITEM name='Item 2' FOCUSABLE setsize:5 posinset:2 -++++ROLE_SYSTEM_LISTITEM name='Item 3' FOCUSABLE setsize:5 posinset:3 -++++ROLE_SYSTEM_LISTITEM name='Item 4' FOCUSABLE setsize:5 posinset:4 -++++ROLE_SYSTEM_LISTITEM name='Item 5' FOCUSABLE setsize:5 posinset:5 +++++ROLE_SYSTEM_LISTITEM name='Item 1' FOCUSABLE setsize:2 posinset:1 +++++ROLE_SYSTEM_LISTITEM name='Item 2' FOCUSABLE setsize:2 posinset:2 +++IA2_ROLE_FORM +++++ROLE_SYSTEM_RADIOBUTTON FOCUSABLE setsize:4 posinset:3 +++++ROLE_SYSTEM_STATICTEXT name='1' +++++ROLE_SYSTEM_WHITESPACE name=' +' +++++ROLE_SYSTEM_RADIOBUTTON FOCUSABLE setsize:4 posinset:4 +++++ROLE_SYSTEM_STATICTEXT name='2' +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_RADIOBUTTON FOCUSABLE setsize:2 posinset:1 +++++ROLE_SYSTEM_STATICTEXT name='Apple' +++++ROLE_SYSTEM_WHITESPACE name=' +' +++++ROLE_SYSTEM_RADIOBUTTON FOCUSABLE setsize:2 posinset:2 +++++ROLE_SYSTEM_STATICTEXT name='Banana' +++ROLE_SYSTEM_GROUPING name='Cake' +++++IA2_ROLE_LABEL +++++++ROLE_SYSTEM_STATICTEXT name='Cake' +++++IA2_ROLE_SECTION +++++++ROLE_SYSTEM_RADIOBUTTON name='Chiffon cakes' FOCUSABLE setsize:2 posinset:1 +++++++ROLE_SYSTEM_WHITESPACE name=' +' +++++++ROLE_SYSTEM_RADIOBUTTON name='Chocolate cakes' FOCUSABLE setsize:2 posinset:2 +++IA2_ROLE_FORM +++++IA2_ROLE_PARAGRAPH +++++++ROLE_SYSTEM_PUSHBUTTON name='changedFromRadio' FOCUSABLE +++++++IA2_ROLE_LABEL +++++++++ROLE_SYSTEM_STATICTEXT name='red' +++++++ROLE_SYSTEM_WHITESPACE name=' +' +++++++ROLE_SYSTEM_RADIOBUTTON name='blue' FOCUSABLE setsize:1 posinset:1 +++IA2_ROLE_SECTION +++++ROLE_SYSTEM_STATICTEXT name='Done' \ No newline at end of file
diff --git a/content/test/data/accessibility/aria/aria-posinset.html b/content/test/data/accessibility/aria/aria-posinset.html index e9ffd1c..ea61f59 100644 --- a/content/test/data/accessibility/aria/aria-posinset.html +++ b/content/test/data/accessibility/aria/aria-posinset.html
@@ -3,21 +3,52 @@ @MAC-ALLOW:AXARIA* @WIN-ALLOW:setsize* @WIN-ALLOW:posinset* +@WAIT-FOR:Done --> <html> -<body> +<body onload="loaded()"> <div role="listbox"> - <div tabIndex="0" aria-setsize="4" aria-posinset="1" role="option">Item 1</div> - <div tabIndex="0" aria-setsize="4" aria-posinset="2" role="option">Item 2</div> - <div tabIndex="0" aria-setsize="4" aria-posinset="3" role="option">Item 3</div> - <div tabIndex="0" aria-setsize="4" aria-posinset="4" role="option">Item 4</div> + <div tabIndex="0" aria-setsize="2" aria-posinset="1" role="option">Item 1</div> + <div tabIndex="0" aria-setsize="2" aria-posinset="2" role="option">Item 2</div> </div> <div role="listbox"> <div tabIndex="0" role="option">Item 1</div> <div tabIndex="0" role="option">Item 2</div> - <div tabIndex="0" role="option">Item 3</div> - <div tabIndex="0" role="option">Item 4</div> - <div tabIndex="0" role="option">Item 5</div> </div> +<form> + <input type="radio" name="number" value="1" aria-setsize="4" aria-posinset="3">1<br> + <input type="radio" name="number" value="2" aria-setsize="4" aria-posinset="4">2 +</form> +<input type="radio" name="fruits" value="Apple">Apple<br> +<input type="radio" name="fruits" value="Banana">Banana +<fieldset> + <legend>Cake</legend> + <label><input type="radio" name="cake" value="Chiffon cakes" checked>Chiffon cakes</label><br> + <label><input type="radio" name="cake" value="Chocolate cakes">Chocolate cakes</label> +</fieldset> +</form> +<form> + <p id = "pTag"> + <label id="parent"><input type="radio" id="elem" name="color" value="red" checked>red</label><br> + <label><input type="radio" name="color" value="blue">blue</label> + </p> +</form> </body> +<script> +function loaded(){ + var parent = document.getElementById("parent"); + var child = document.getElementById("elem"); + parent.removeChild(child); + + var pTag = document.getElementById("pTag"); + child = document.createElement("input"); + child.type = "radio"; + child.name = "color"; + pTag.insertBefore(child, parent); + + child.type = "button"; + child.value = "changedFromRadio"; + document.body.appendChild(document.createTextNode('Done')); +} +</script> </html>
diff --git a/content/test/data/page_with_click_handler.html b/content/test/data/page_with_click_handler.html new file mode 100644 index 0000000..cebf4ec --- /dev/null +++ b/content/test/data/page_with_click_handler.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<html style="width: 100%; height: 100%"> +<head> + <script> + clicksReceived = 0; + + function clickHandler(e) { + var clickResult = document.getElementById("click-results"); + clicksReceived++; + if (clicksReceived == 1) + clickResult.textContent = "1 click received"; + else + clickResult.textContent = clicksReceived + " clicks received"; + } + + function getClickStatus() { + var clickResult = document.getElementById("click-results"); + return clickResult.textContent; + } + + window.addEventListener('load', function(){ + document.body.addEventListener('click', + function(e){ + clickHandler(e); + }, false); + }, false); + </script> +</head> + +<!-- Be sure to set 100% width/height so the test can determine an appropriate + screen region for targeting events. --> +<body style="width: 100%; height: 100%"> + Page with Click Handler + <div id="click-results">0 clicks received</div> +</body> +</html>
diff --git a/content/test/data/web_ui_mojo_shell_test.js b/content/test/data/web_ui_mojo_shell_test.js index 32077aa..ab0661d5 100644 --- a/content/test/data/web_ui_mojo_shell_test.js +++ b/content/test/data/web_ui_mojo_shell_test.js
@@ -14,10 +14,11 @@ 'mojo/public/js/core', 'mojo/public/js/router', 'mojo/services/network/public/interfaces/url_loader.mojom', - 'mojo/shell/public/interfaces/shell.mojom', + 'mojo/shell/public/interfaces/connector.mojom', 'content/public/renderer/service_provider', 'content/public/test/test_mojo_service.mojom', -], function (core, router, urlMojom, shellMojom, serviceRegistry, testMojom) { +], function (core, router, urlMojom, connectorMojom, serviceRegistry, + testMojom) { var connectToService = function(serviceProvider, iface) { var pipe = core.createMessagePipe(); @@ -29,12 +30,12 @@ return function() { domAutomationController.setAutomationId(0); var connectorPipe = - serviceRegistry.connectToService(shellMojom.Connector.name); - var connector = new shellMojom.Connector.proxyClass( + serviceRegistry.connectToService(connectorMojom.Connector.name); + var connector = new connectorMojom.Connector.proxyClass( new router.Router(connectorPipe)); connector.connect( - TEST_APP_URL, 1, + TEST_APP_URL, connectorMojom.kInheritUserID, function (services) { var test = connectToService(services, testMojom.TestMojoService); test.getRequestorName().then(function(response) {
diff --git a/device/usb/mojo/BUILD.gn b/device/usb/mojo/BUILD.gn index d48cf37..a2cc898 100644 --- a/device/usb/mojo/BUILD.gn +++ b/device/usb/mojo/BUILD.gn
@@ -8,6 +8,8 @@ "device_impl.h", "device_manager_impl.cc", "device_manager_impl.h", + "permission_provider.cc", + "permission_provider.h", "type_converters.cc", "type_converters.h", ]
diff --git a/device/usb/mojo/device_impl.cc b/device/usb/mojo/device_impl.cc index ae5f4bb..9472571 100644 --- a/device/usb/mojo/device_impl.cc +++ b/device/usb/mojo/device_impl.cc
@@ -50,16 +50,6 @@ return base::Bind(&CallMojoCallback<Args...>, base::Passed(&callback_ptr)); } -void OnPermissionCheckComplete( - const base::Callback<void(bool)>& callback, - const base::Callback<void(const base::Callback<void(bool)>&)>& action, - bool allowed) { - if (allowed) - action.Run(callback); - else - callback.Run(false); -} - scoped_refptr<net::IOBuffer> CreateTransferBuffer(size_t size) { scoped_refptr<net::IOBuffer> buffer = new net::IOBuffer( std::max(static_cast<size_t>(1u), static_cast<size_t>(size))); @@ -82,27 +72,6 @@ callback->Run(mojo::ConvertTo<TransferStatus>(status), std::move(data)); } -void OnControlTransferInPermissionCheckComplete( - scoped_refptr<UsbDeviceHandle> device_handle, - ControlTransferParamsPtr params, - int length, - int timeout, - scoped_ptr<Device::ControlTransferInCallback> callback, - bool allowed) { - if (allowed) { - scoped_refptr<net::IOBuffer> buffer = CreateTransferBuffer(length); - device_handle->ControlTransfer( - USB_DIRECTION_INBOUND, - mojo::ConvertTo<UsbDeviceHandle::TransferRequestType>(params->type), - mojo::ConvertTo<UsbDeviceHandle::TransferRecipient>(params->recipient), - params->request, params->value, params->index, buffer, length, timeout, - base::Bind(&OnTransferIn, base::Passed(&callback))); - } else { - mojo::Array<uint8_t> data; - callback->Run(TransferStatus::PERMISSION_DENIED, std::move(data)); - } -} - void OnTransferOut(scoped_ptr<MojoTransferOutCallback> callback, UsbTransferStatus status, scoped_refptr<net::IOBuffer> buffer, @@ -110,28 +79,6 @@ callback->Run(mojo::ConvertTo<TransferStatus>(status)); } -void OnControlTransferOutPermissionCheckComplete( - scoped_refptr<UsbDeviceHandle> device_handle, - ControlTransferParamsPtr params, - mojo::Array<uint8_t> data, - int timeout, - scoped_ptr<Device::ControlTransferOutCallback> callback, - bool allowed) { - if (allowed) { - scoped_refptr<net::IOBuffer> buffer = CreateTransferBuffer(data.size()); - const std::vector<uint8_t>& storage = data.storage(); - std::copy(storage.begin(), storage.end(), buffer->data()); - device_handle->ControlTransfer( - USB_DIRECTION_OUTBOUND, - mojo::ConvertTo<UsbDeviceHandle::TransferRequestType>(params->type), - mojo::ConvertTo<UsbDeviceHandle::TransferRecipient>(params->recipient), - params->request, params->value, params->index, buffer, data.size(), - timeout, base::Bind(&OnTransferOut, base::Passed(&callback))); - } else { - callback->Run(TransferStatus::PERMISSION_DENIED); - } -} - mojo::Array<IsochronousPacketPtr> BuildIsochronousPacketArray( mojo::Array<uint32_t> packet_lengths, TransferStatus status) { @@ -177,21 +124,21 @@ } // namespace DeviceImpl::DeviceImpl(scoped_refptr<UsbDevice> device, - PermissionProviderPtr permission_provider, + DeviceInfoPtr device_info, + base::WeakPtr<PermissionProvider> permission_provider, mojo::InterfaceRequest<Device> request) : device_(device), + device_info_(std::move(device_info)), + permission_provider_(permission_provider), observer_(this), - permission_provider_(std::move(permission_provider)), binding_(this, std::move(request)), weak_factory_(this) { DCHECK(device_); // This object owns itself and will be destroyed if, - // * the device is disconnected, - // * the message pipe it is bound to is closed, or - // * the PermissionProvider it depends on is unavailable. + // * the device is disconnected or + // * the message pipe it is bound to is closed observer_.Add(device_.get()); binding_.set_connection_error_handler([this]() { delete this; }); - permission_provider_.set_connection_error_handler([this]() { delete this; }); } DeviceImpl::~DeviceImpl() { @@ -204,38 +151,35 @@ device_handle_ = nullptr; } -void DeviceImpl::HasControlTransferPermission( +bool DeviceImpl::HasControlTransferPermission( ControlTransferRecipient recipient, - uint16_t index, - const base::Callback<void(bool)>& callback) { + uint16_t index) { DCHECK(device_handle_); const UsbConfigDescriptor* config = device_->GetActiveConfiguration(); + if (!permission_provider_) + return false; + if (recipient == ControlTransferRecipient::INTERFACE || recipient == ControlTransferRecipient::ENDPOINT) { - if (!config) { - callback.Run(false); - return; - } + if (!config) + return false; uint8_t interface_number = index & 0xff; - if (recipient == ControlTransferRecipient::ENDPOINT) { - if (!device_handle_->FindInterfaceByEndpoint(index & 0xff, - &interface_number)) { - callback.Run(false); - return; - } + if (recipient == ControlTransferRecipient::ENDPOINT && + !device_handle_->FindInterfaceByEndpoint(index & 0xff, + &interface_number)) { + return false; } - permission_provider_->HasInterfacePermission( - interface_number, config->configuration_value, - DeviceInfo::From(*device_), callback); + return permission_provider_->HasInterfacePermission( + interface_number, config->configuration_value, *device_info_); } else if (config) { - permission_provider_->HasConfigurationPermission( - config->configuration_value, DeviceInfo::From(*device_), callback); + return permission_provider_->HasConfigurationPermission( + config->configuration_value, *device_info_); } else { // Client must already have device permission to have gotten this far. - callback.Run(true); + return true; } } @@ -246,7 +190,7 @@ } void DeviceImpl::GetDeviceInfo(const GetDeviceInfoCallback& callback) { - callback.Run(DeviceInfo::From(*device_)); + callback.Run(device_info_->Clone()); } void DeviceImpl::GetConfiguration(const GetConfigurationCallback& callback) { @@ -274,12 +218,12 @@ return; } - auto set_configuration = - base::Bind(&UsbDeviceHandle::SetConfiguration, device_handle_, value); - permission_provider_->HasConfigurationPermission( - value, DeviceInfo::From(*device_), - base::Bind(&OnPermissionCheckComplete, WrapMojoCallback(callback), - set_configuration)); + if (permission_provider_ && + permission_provider_->HasConfigurationPermission(value, *device_info_)) { + device_handle_->SetConfiguration(value, WrapMojoCallback(callback)); + } else { + callback.Run(false); + } } void DeviceImpl::ClaimInterface(uint8_t interface_number, @@ -295,12 +239,14 @@ return; } - auto claim_interface = base::Bind(&UsbDeviceHandle::ClaimInterface, - device_handle_, interface_number); - permission_provider_->HasInterfacePermission( - interface_number, config->configuration_value, DeviceInfo::From(*device_), - base::Bind(&OnPermissionCheckComplete, WrapMojoCallback(callback), - claim_interface)); + if (permission_provider_ && + permission_provider_->HasInterfacePermission( + interface_number, config->configuration_value, *device_info_)) { + device_handle_->ClaimInterface(interface_number, + WrapMojoCallback(callback)); + } else { + callback.Run(false); + } } void DeviceImpl::ReleaseInterface(uint8_t interface_number, @@ -355,14 +301,20 @@ return; } - auto callback_ptr = make_scoped_ptr(new ControlTransferInCallback(callback)); - ControlTransferRecipient recipient = params->recipient; - uint16_t index = params->index; - HasControlTransferPermission( - recipient, index, - base::Bind(&OnControlTransferInPermissionCheckComplete, device_handle_, - base::Passed(¶ms), length, timeout, - base::Passed(&callback_ptr))); + if (HasControlTransferPermission(params->recipient, params->index)) { + scoped_refptr<net::IOBuffer> buffer = CreateTransferBuffer(length); + auto callback_ptr = + make_scoped_ptr(new ControlTransferInCallback(callback)); + device_handle_->ControlTransfer( + USB_DIRECTION_INBOUND, + mojo::ConvertTo<UsbDeviceHandle::TransferRequestType>(params->type), + mojo::ConvertTo<UsbDeviceHandle::TransferRecipient>(params->recipient), + params->request, params->value, params->index, buffer, length, timeout, + base::Bind(&OnTransferIn, base::Passed(&callback_ptr))); + } else { + mojo::Array<uint8_t> data; + callback.Run(TransferStatus::PERMISSION_DENIED, std::move(data)); + } } void DeviceImpl::ControlTransferOut( @@ -375,14 +327,21 @@ return; } - auto callback_ptr = make_scoped_ptr(new ControlTransferOutCallback(callback)); - ControlTransferRecipient recipient = params->recipient; - uint16_t index = params->index; - HasControlTransferPermission( - recipient, index, - base::Bind(&OnControlTransferOutPermissionCheckComplete, device_handle_, - base::Passed(¶ms), base::Passed(&data), timeout, - base::Passed(&callback_ptr))); + if (HasControlTransferPermission(params->recipient, params->index)) { + scoped_refptr<net::IOBuffer> buffer = CreateTransferBuffer(data.size()); + const std::vector<uint8_t>& storage = data.storage(); + std::copy(storage.begin(), storage.end(), buffer->data()); + auto callback_ptr = + make_scoped_ptr(new ControlTransferOutCallback(callback)); + device_handle_->ControlTransfer( + USB_DIRECTION_OUTBOUND, + mojo::ConvertTo<UsbDeviceHandle::TransferRequestType>(params->type), + mojo::ConvertTo<UsbDeviceHandle::TransferRecipient>(params->recipient), + params->request, params->value, params->index, buffer, data.size(), + timeout, base::Bind(&OnTransferOut, base::Passed(&callback_ptr))); + } else { + callback.Run(TransferStatus::PERMISSION_DENIED); + } } void DeviceImpl::GenericTransferIn(uint8_t endpoint_number,
diff --git a/device/usb/mojo/device_impl.h b/device/usb/mojo/device_impl.h index 487a7d4..6c77d386 100644 --- a/device/usb/mojo/device_impl.h +++ b/device/usb/mojo/device_impl.h
@@ -12,8 +12,8 @@ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" +#include "device/usb/mojo/permission_provider.h" #include "device/usb/public/interfaces/device.mojom.h" -#include "device/usb/public/interfaces/permission_provider.mojom.h" #include "device/usb/usb_device.h" #include "device/usb/usb_device_handle.h" #include "mojo/public/cpp/bindings/binding.h" @@ -27,13 +27,16 @@ namespace device { namespace usb { +class PermissionProvider; + // Implementation of the public Device interface. Instances of this class are // constructed by DeviceManagerImpl and are strongly bound to their MessagePipe // lifetime. class DeviceImpl : public Device, public device::UsbDevice::Observer { public: DeviceImpl(scoped_refptr<UsbDevice> device, - PermissionProviderPtr permission_provider, + DeviceInfoPtr device_info, + base::WeakPtr<PermissionProvider> permission_provider, mojo::InterfaceRequest<Device> request); ~DeviceImpl() override; @@ -43,9 +46,8 @@ void CloseHandle(); // Checks interface permissions for control transfers. - void HasControlTransferPermission(ControlTransferRecipient recipient, - uint16_t index, - const base::Callback<void(bool)>& callback); + bool HasControlTransferPermission(ControlTransferRecipient recipient, + uint16_t index); // Handles completion of an open request. void OnOpen(const OpenCallback& callback, @@ -97,15 +99,16 @@ const IsochronousTransferOutCallback& callback) override; // device::UsbDevice::Observer implementation: - void OnDeviceRemoved(scoped_refptr<device::UsbDevice>) override; + void OnDeviceRemoved(scoped_refptr<device::UsbDevice> device) override; - scoped_refptr<UsbDevice> device_; + const scoped_refptr<UsbDevice> device_; + const DeviceInfoPtr device_info_; + base::WeakPtr<PermissionProvider> permission_provider_; ScopedObserver<device::UsbDevice, device::UsbDevice::Observer> observer_; // The device handle. Will be null before the device is opened and after it // has been closed. scoped_refptr<UsbDeviceHandle> device_handle_; - PermissionProviderPtr permission_provider_; mojo::Binding<Device> binding_; base::WeakPtrFactory<DeviceImpl> weak_factory_;
diff --git a/device/usb/mojo/device_impl_unittest.cc b/device/usb/mojo/device_impl_unittest.cc index 25cc048e..78a1f85 100644 --- a/device/usb/mojo/device_impl_unittest.cc +++ b/device/usb/mojo/device_impl_unittest.cc
@@ -23,6 +23,7 @@ #include "device/usb/mock_usb_device.h" #include "device/usb/mock_usb_device_handle.h" #include "device/usb/mojo/fake_permission_provider.h" +#include "device/usb/mojo/type_converters.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "net/base/io_buffer.h" #include "testing/gtest/include/gtest/gtest.h" @@ -168,11 +169,11 @@ new MockUsbDevice(vendor_id, product_id, manufacturer, product, serial); mock_handle_ = new MockUsbDeviceHandle(mock_device_.get()); - PermissionProviderPtr permission_provider; - permission_provider_.Bind(mojo::GetProxy(&permission_provider)); DevicePtr proxy; - new DeviceImpl(mock_device_, std::move(permission_provider), - mojo::GetProxy(&proxy)); + new DeviceImpl( + mock_device_, + DeviceInfo::From(static_cast<const UsbDevice&>(*mock_device_)), + permission_provider_.GetWeakPtr(), mojo::GetProxy(&proxy)); // Set up mock handle calls to respond based on mock device configs // established by the test.
diff --git a/device/usb/mojo/device_manager_impl.cc b/device/usb/mojo/device_manager_impl.cc index 78ecaf9c..69e238a7 100644 --- a/device/usb/mojo/device_manager_impl.cc +++ b/device/usb/mojo/device_manager_impl.cc
@@ -13,6 +13,7 @@ #include "base/stl_util.h" #include "device/core/device_client.h" #include "device/usb/mojo/device_impl.h" +#include "device/usb/mojo/permission_provider.h" #include "device/usb/mojo/type_converters.h" #include "device/usb/public/interfaces/device.mojom.h" #include "device/usb/usb_device.h" @@ -24,51 +25,30 @@ namespace device { namespace usb { -namespace { - -using DeviceList = DeviceManagerImpl::DeviceList; -using DeviceMap = DeviceManagerImpl::DeviceMap; - -void FilterAndConvertDevicesAndThen( - const DeviceMap& devices, - const DeviceManagerImpl::GetDevicesCallback& callback, - mojo::Array<mojo::String> allowed_guids) { - mojo::Array<DeviceInfoPtr> allowed_devices(allowed_guids.size()); - for (size_t i = 0; i < allowed_guids.size(); ++i) { - const auto it = devices.find(allowed_guids[i]); - DCHECK(it != devices.end()); - allowed_devices[i] = DeviceInfo::From(*it->second); - } - - callback.Run(std::move(allowed_devices)); -} - -} // namespace - // static -void DeviceManagerImpl::Create(PermissionProviderPtr permission_provider, - mojo::InterfaceRequest<DeviceManager> request) { - // The created object is owned by its binding. - new DeviceManagerImpl(std::move(permission_provider), std::move(request)); +void DeviceManagerImpl::Create( + base::WeakPtr<PermissionProvider> permission_provider, + mojo::InterfaceRequest<DeviceManager> request) { + DCHECK(DeviceClient::Get()); + UsbService* usb_service = DeviceClient::Get()->GetUsbService(); + if (usb_service) { + new DeviceManagerImpl(permission_provider, usb_service, std::move(request)); + } } DeviceManagerImpl::DeviceManagerImpl( - PermissionProviderPtr permission_provider, + base::WeakPtr<PermissionProvider> permission_provider, + UsbService* usb_service, mojo::InterfaceRequest<DeviceManager> request) - : permission_provider_(std::move(permission_provider)), + : permission_provider_(permission_provider), + usb_service_(usb_service), observer_(this), binding_(this, std::move(request)), weak_factory_(this) { - // This object owns itself and will be destroyed if either the message pipe - // it is bound to is closed or the PermissionProvider it depends on is - // unavailable. + // This object owns itself and will be destroyed if the message pipe it is + // bound to is closed or the UsbService is shut down. binding_.set_connection_error_handler([this]() { delete this; }); - permission_provider_.set_connection_error_handler([this]() { delete this; }); - - DCHECK(DeviceClient::Get()); - usb_service_ = DeviceClient::Get()->GetUsbService(); - if (usb_service_) - observer_.Add(usb_service_); + observer_.Add(usb_service_); } DeviceManagerImpl::~DeviceManagerImpl() { @@ -77,12 +57,6 @@ void DeviceManagerImpl::GetDevices(EnumerationOptionsPtr options, const GetDevicesCallback& callback) { - if (!usb_service_) { - mojo::Array<DeviceInfoPtr> no_devices; - callback.Run(std::move(no_devices)); - return; - } - usb_service_->GetDevices(base::Bind(&DeviceManagerImpl::OnGetDevices, weak_factory_.GetWeakPtr(), base::Passed(&options), callback)); @@ -97,131 +71,79 @@ void DeviceManagerImpl::GetDevice( const mojo::String& guid, mojo::InterfaceRequest<Device> device_request) { - if (!usb_service_) - return; - scoped_refptr<UsbDevice> device = usb_service_->GetDevice(guid); if (!device) return; - mojo::Array<DeviceInfoPtr> requested_devices(1); - requested_devices[0] = DeviceInfo::From(*device); - permission_provider_->HasDevicePermission( - std::move(requested_devices), - base::Bind(&DeviceManagerImpl::OnGetDevicePermissionCheckComplete, - base::Unretained(this), device, - base::Passed(&device_request))); + DeviceInfoPtr device_info = DeviceInfo::From(*device); + if (permission_provider_ && + permission_provider_->HasDevicePermission(*device_info)) { + new DeviceImpl(device, std::move(device_info), permission_provider_, + std::move(device_request)); + } } -void DeviceManagerImpl::OnGetDevicePermissionCheckComplete( - scoped_refptr<UsbDevice> device, - mojo::InterfaceRequest<Device> device_request, - mojo::Array<mojo::String> allowed_guids) { - if (allowed_guids.size() == 0) - return; - - DCHECK(allowed_guids.size() == 1); - PermissionProviderPtr permission_provider; - permission_provider_->Bind(mojo::GetProxy(&permission_provider)); - new DeviceImpl(device, std::move(permission_provider), - std::move(device_request)); -} - -void DeviceManagerImpl::OnGetDevices(EnumerationOptionsPtr options, - const GetDevicesCallback& callback, - const DeviceList& devices) { +void DeviceManagerImpl::OnGetDevices( + EnumerationOptionsPtr options, + const GetDevicesCallback& callback, + const std::vector<scoped_refptr<UsbDevice>>& devices) { std::vector<UsbDeviceFilter> filters; if (options) filters = options->filters.To<std::vector<UsbDeviceFilter>>(); - std::map<std::string, scoped_refptr<UsbDevice>> device_map; - mojo::Array<DeviceInfoPtr> requested_devices; + mojo::Array<DeviceInfoPtr> device_infos; for (const auto& device : devices) { if (filters.empty() || UsbDeviceFilter::MatchesAny(device, filters)) { - device_map[device->guid()] = device; - requested_devices.push_back(DeviceInfo::From(*device)); + DeviceInfoPtr device_info = DeviceInfo::From(*device); + if (permission_provider_ && + permission_provider_->HasDevicePermission(*device_info)) { + device_infos.push_back(std::move(device_info)); + } } } - permission_provider_->HasDevicePermission( - std::move(requested_devices), - base::Bind(&FilterAndConvertDevicesAndThen, device_map, callback)); + callback.Run(std::move(device_infos)); } void DeviceManagerImpl::OnDeviceAdded(scoped_refptr<UsbDevice> device) { - DCHECK(!ContainsKey(devices_removed_, device->guid())); - devices_added_[device->guid()] = device; - MaybeRunDeviceChangesCallback(); -} - -void DeviceManagerImpl::OnDeviceRemoved(scoped_refptr<UsbDevice> device) { - if (devices_added_.erase(device->guid()) == 0) - devices_removed_[device->guid()] = device; - MaybeRunDeviceChangesCallback(); -} - -void DeviceManagerImpl::WillDestroyUsbService() { - observer_.RemoveAll(); - usb_service_ = nullptr; -} - -void DeviceManagerImpl::MaybeRunDeviceChangesCallback() { - if (!permission_request_pending_ && !device_change_callbacks_.empty()) { - DeviceMap devices_added; - devices_added.swap(devices_added_); - DeviceMap devices_removed; - devices_removed.swap(devices_removed_); - - mojo::Array<DeviceInfoPtr> requested_devices(devices_added.size() + - devices_removed.size()); - { - size_t i = 0; - for (const auto& map_entry : devices_added) - requested_devices[i++] = DeviceInfo::From(*map_entry.second); - for (const auto& map_entry : devices_removed) - requested_devices[i++] = DeviceInfo::From(*map_entry.second); - } - - permission_request_pending_ = true; - permission_provider_->HasDevicePermission( - std::move(requested_devices), - base::Bind(&DeviceManagerImpl::OnEnumerationPermissionCheckComplete, - base::Unretained(this), devices_added, devices_removed)); + DeviceInfoPtr device_info = DeviceInfo::From(*device); + if (permission_provider_ && + permission_provider_->HasDevicePermission(*device_info)) { + devices_added_[device->guid()] = std::move(device_info); + MaybeRunDeviceChangesCallback(); } } -void DeviceManagerImpl::OnEnumerationPermissionCheckComplete( - const DeviceMap& devices_added, - const DeviceMap& devices_removed, - mojo::Array<mojo::String> allowed_guids) { - permission_request_pending_ = false; - - if (allowed_guids.size() > 0) { - DeviceChangeNotificationPtr notification = DeviceChangeNotification::New(); - notification->devices_added.resize(0); - notification->devices_removed.resize(0); - - for (size_t i = 0; i < allowed_guids.size(); ++i) { - const mojo::String& guid = allowed_guids[i]; - auto it = devices_added.find(guid); - if (it != devices_added.end()) { - DCHECK(!ContainsKey(devices_removed, guid)); - notification->devices_added.push_back(DeviceInfo::From(*it->second)); - } else { - it = devices_removed.find(guid); - DCHECK(it != devices_removed.end()); - notification->devices_removed.push_back(DeviceInfo::From(*it->second)); - } +void DeviceManagerImpl::OnDeviceRemoved(scoped_refptr<UsbDevice> device) { + if (devices_added_.erase(device->guid()) == 0) { + DeviceInfoPtr device_info = DeviceInfo::From(*device); + if (permission_provider_ && + permission_provider_->HasDevicePermission(*device_info)) { + devices_removed_.push_back(std::move(device_info)); + MaybeRunDeviceChangesCallback(); } + } +} - DCHECK(!device_change_callbacks_.empty()); +void DeviceManagerImpl::WillDestroyUsbService() { + delete this; +} + +void DeviceManagerImpl::MaybeRunDeviceChangesCallback() { + if (!device_change_callbacks_.empty()) { + DeviceChangeNotificationPtr notification = DeviceChangeNotification::New(); + notification->devices_added.SetToEmpty(); + notification->devices_removed.SetToEmpty(); + for (auto& map_entry : devices_added_) { + notification->devices_added.push_back(std::move(map_entry.second)); + } + devices_added_.clear(); + notification->devices_removed.Swap(&devices_removed_); + const GetDeviceChangesCallback& callback = device_change_callbacks_.front(); callback.Run(std::move(notification)); device_change_callbacks_.pop(); } - - if (devices_added_.size() > 0 || !devices_removed_.empty()) - MaybeRunDeviceChangesCallback(); } } // namespace usb
diff --git a/device/usb/mojo/device_manager_impl.h b/device/usb/mojo/device_manager_impl.h index 85e46ce..6ddf5d1 100644 --- a/device/usb/mojo/device_manager_impl.h +++ b/device/usb/mojo/device_manager_impl.h
@@ -14,7 +14,6 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observer.h" #include "device/usb/public/interfaces/device_manager.mojom.h" -#include "device/usb/public/interfaces/permission_provider.mojom.h" #include "device/usb/usb_service.h" #include "mojo/public/cpp/bindings/array.h" #include "mojo/public/cpp/bindings/binding.h" @@ -32,20 +31,17 @@ namespace usb { -class DeviceManagerDelegate; +class PermissionProvider; // Implementation of the public DeviceManager interface. This interface can be // requested from the devices app located at "mojo:devices", if available. -class DeviceManagerImpl : public DeviceManager, - public device::UsbService::Observer { +class DeviceManagerImpl : public DeviceManager, public UsbService::Observer { public: - using DeviceList = std::vector<scoped_refptr<UsbDevice>>; - using DeviceMap = std::map<std::string, scoped_refptr<device::UsbDevice>>; - - static void Create(PermissionProviderPtr permission_provider, + static void Create(base::WeakPtr<PermissionProvider> permission_provider, mojo::InterfaceRequest<DeviceManager> request); - DeviceManagerImpl(PermissionProviderPtr permission_provider, + DeviceManagerImpl(base::WeakPtr<PermissionProvider> permission_provider, + UsbService* usb_service, mojo::InterfaceRequest<DeviceManager> request); ~DeviceManagerImpl() override; @@ -62,40 +58,29 @@ mojo::InterfaceRequest<Device> device_request) override; // Callbacks to handle the async responses from the underlying UsbService. - void OnGetDevicePermissionCheckComplete( - scoped_refptr<device::UsbDevice> device, - mojo::InterfaceRequest<Device> device_request, - mojo::Array<mojo::String> allowed_guids); void OnGetDevices(EnumerationOptionsPtr options, const GetDevicesCallback& callback, - const DeviceList& devices); + const std::vector<scoped_refptr<UsbDevice>>& devices); // UsbService::Observer implementation: - void OnDeviceAdded(scoped_refptr<device::UsbDevice> device) override; - void OnDeviceRemoved(scoped_refptr<device::UsbDevice> device) override; + void OnDeviceAdded(scoped_refptr<UsbDevice> device) override; + void OnDeviceRemoved(scoped_refptr<UsbDevice> device) override; void WillDestroyUsbService() override; void MaybeRunDeviceChangesCallback(); - void OnEnumerationPermissionCheckComplete( - const DeviceMap& devices_added, - const DeviceMap& devices_removed, - mojo::Array<mojo::String> allowed_guids); - PermissionProviderPtr permission_provider_; + base::WeakPtr<PermissionProvider> permission_provider_; // If there are unfinished calls to GetDeviceChanges their callbacks // are stored in |device_change_callbacks_|. Otherwise device changes // are collected in |devices_added_| and |devices_removed_| until the // next call to GetDeviceChanges. std::queue<GetDeviceChangesCallback> device_change_callbacks_; - DeviceMap devices_added_; - DeviceMap devices_removed_; - // To ensure that GetDeviceChangesCallbacks are called in the correct order - // only perform a single request to |permission_provider_| at a time. - bool permission_request_pending_ = false; + std::map<std::string, DeviceInfoPtr> devices_added_; + std::vector<DeviceInfoPtr> devices_removed_; UsbService* usb_service_; - ScopedObserver<device::UsbService, device::UsbService::Observer> observer_; + ScopedObserver<UsbService, UsbService::Observer> observer_; mojo::Closure connection_error_handler_;
diff --git a/device/usb/mojo/device_manager_impl_unittest.cc b/device/usb/mojo/device_manager_impl_unittest.cc index 139f5a03..9fc01df2 100644 --- a/device/usb/mojo/device_manager_impl_unittest.cc +++ b/device/usb/mojo/device_manager_impl_unittest.cc
@@ -38,10 +38,8 @@ protected: DeviceManagerPtr ConnectToDeviceManager() { - PermissionProviderPtr permission_provider; - permission_provider_.Bind(mojo::GetProxy(&permission_provider)); DeviceManagerPtr device_manager; - DeviceManagerImpl::Create(std::move(permission_provider), + DeviceManagerImpl::Create(permission_provider_.GetWeakPtr(), mojo::GetProxy(&device_manager)); return device_manager; }
diff --git a/device/usb/mojo/fake_permission_provider.cc b/device/usb/mojo/fake_permission_provider.cc index 9dd7b4f..c100318 100644 --- a/device/usb/mojo/fake_permission_provider.cc +++ b/device/usb/mojo/fake_permission_provider.cc
@@ -10,36 +10,30 @@ namespace device { namespace usb { -FakePermissionProvider::FakePermissionProvider() {} +FakePermissionProvider::FakePermissionProvider() : weak_factory_(this) {} FakePermissionProvider::~FakePermissionProvider() {} -void FakePermissionProvider::HasDevicePermission( - mojo::Array<DeviceInfoPtr> requested_devices, - const HasDevicePermissionCallback& callback) { - mojo::Array<mojo::String> allowed_guids(requested_devices.size()); - for (size_t i = 0; i < requested_devices.size(); ++i) - allowed_guids[i] = requested_devices[i]->guid; - callback.Run(std::move(allowed_guids)); +base::WeakPtr<PermissionProvider> FakePermissionProvider::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); } -void FakePermissionProvider::HasConfigurationPermission( - uint8_t requested_configuration, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) { - callback.Run(true); +bool FakePermissionProvider::HasDevicePermission( + const device::usb::DeviceInfo& device_info) const { + return true; } -void FakePermissionProvider::HasInterfacePermission( + +bool FakePermissionProvider::HasConfigurationPermission( + uint8_t requested_configuration, + const device::usb::DeviceInfo& device_info) const { + return true; +} + +bool FakePermissionProvider::HasInterfacePermission( uint8_t requested_interface, uint8_t configuration_value, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) { - callback.Run(true); -} - -void FakePermissionProvider::Bind( - mojo::InterfaceRequest<PermissionProvider> request) { - bindings_.AddBinding(this, std::move(request)); + const device::usb::DeviceInfo& device_info) const { + return true; } } // namespace usb
diff --git a/device/usb/mojo/fake_permission_provider.h b/device/usb/mojo/fake_permission_provider.h index 5ca1610..8d038132 100644 --- a/device/usb/mojo/fake_permission_provider.h +++ b/device/usb/mojo/fake_permission_provider.h
@@ -7,10 +7,8 @@ #include <stdint.h> -#include "device/usb/public/interfaces/permission_provider.mojom.h" -#include "mojo/public/cpp/bindings/array.h" -#include "mojo/public/cpp/bindings/binding_set.h" -#include "mojo/public/cpp/bindings/interface_request.h" +#include "base/memory/weak_ptr.h" +#include "device/usb/mojo/permission_provider.h" namespace device { namespace usb { @@ -20,22 +18,16 @@ FakePermissionProvider(); ~FakePermissionProvider() override; - void HasDevicePermission( - mojo::Array<DeviceInfoPtr> requested_devices, - const HasDevicePermissionCallback& callback) override; - void HasConfigurationPermission( - uint8_t requested_configuration, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) override; - void HasInterfacePermission( - uint8_t requested_interface, - uint8_t configuration_value, - device::usb::DeviceInfoPtr device, - const HasInterfacePermissionCallback& callback) override; - void Bind(mojo::InterfaceRequest<PermissionProvider> request) override; + base::WeakPtr<PermissionProvider> GetWeakPtr(); + bool HasDevicePermission(const DeviceInfo& device_info) const override; + bool HasConfigurationPermission(uint8_t requested_configuration, + const DeviceInfo& device_info) const override; + bool HasInterfacePermission(uint8_t requested_interface, + uint8_t configuration_value, + const DeviceInfo& device_info) const override; private: - mojo::BindingSet<PermissionProvider> bindings_; + base::WeakPtrFactory<PermissionProvider> weak_factory_; }; } // namespace usb
diff --git a/device/usb/mojo/permission_provider.cc b/device/usb/mojo/permission_provider.cc new file mode 100644 index 0000000..3d6d956 --- /dev/null +++ b/device/usb/mojo/permission_provider.cc
@@ -0,0 +1,15 @@ +// 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 "device/usb/mojo/permission_provider.h" + +namespace device { +namespace usb { + +PermissionProvider::PermissionProvider() {} + +PermissionProvider::~PermissionProvider() {} + +} // namespace usb +} // namespace device
diff --git a/device/usb/mojo/permission_provider.h b/device/usb/mojo/permission_provider.h new file mode 100644 index 0000000..8366047 --- /dev/null +++ b/device/usb/mojo/permission_provider.h
@@ -0,0 +1,34 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEVICE_USB_MOJO_PERMISSION_PROVIDER_H_ +#define DEVICE_USB_MOJO_PERMISSION_PROVIDER_H_ + +#include <stdint.h> + +namespace device { +namespace usb { + +class DeviceInfo; + +// An implementation of this interface must be provided to a DeviceManager in +// order to implement device permission checks. +class PermissionProvider { + public: + PermissionProvider(); + virtual ~PermissionProvider(); + + virtual bool HasDevicePermission(const DeviceInfo& device_info) const = 0; + virtual bool HasConfigurationPermission( + uint8_t requested_configuration, + const DeviceInfo& device_info) const = 0; + virtual bool HasInterfacePermission(uint8_t requested_interface, + uint8_t configuration_value, + const DeviceInfo& device_info) const = 0; +}; + +} // namespace usb +} // namespace device + +#endif // DEVICE_USB_MOJO_PERMISSION_PROVIDER_H_
diff --git a/device/usb/public/interfaces/BUILD.gn b/device/usb/public/interfaces/BUILD.gn index f9d6e0c9..eca5418 100644 --- a/device/usb/public/interfaces/BUILD.gn +++ b/device/usb/public/interfaces/BUILD.gn
@@ -8,6 +8,5 @@ sources = [ "device.mojom", "device_manager.mojom", - "permission_provider.mojom", ] }
diff --git a/device/usb/public/interfaces/permission_provider.mojom b/device/usb/public/interfaces/permission_provider.mojom deleted file mode 100644 index f5d7111..0000000 --- a/device/usb/public/interfaces/permission_provider.mojom +++ /dev/null
@@ -1,29 +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. - -module device.usb; - -import "device.mojom"; - -interface PermissionProvider { - // Filters a set of |requested_devices| down to the set of |allowed_guids| - // that should be accessible to clients of the DeviceManager instance. - HasDevicePermission(array<DeviceInfo> requested_devices) - => (array<string> allowed_guids); - - // Returns whether or not the client has permission to access - // |requested_configuration| on |device|. - HasConfigurationPermission(uint8 requested_configuration, - DeviceInfo device) => (bool allowed); - - // Returns whether or not the client has permission to access - // |requested_interface| on |device| when it is in configuration - // |configuration_value|. - HasInterfacePermission(uint8 requested_interface, - uint8 configuration_value, - DeviceInfo device) => (bool allowed); - - // Requests a new binding to this service. - Bind(PermissionProvider& request); -};
diff --git a/device/usb/usb.gyp b/device/usb/usb.gyp index ee6d34f..a553f57 100644 --- a/device/usb/usb.gyp +++ b/device/usb/usb.gyp
@@ -29,6 +29,8 @@ 'mojo/device_manager_impl.h', 'mojo/type_converters.cc', 'mojo/type_converters.h', + 'mojo/permission_provider.cc', + 'mojo/permission_provider.h', 'usb_configuration_android.cc', 'usb_configuration_android.h', 'usb_context.cc', @@ -128,7 +130,6 @@ 'sources': [ 'public/interfaces/device.mojom', 'public/interfaces/device_manager.mojom', - 'public/interfaces/permission_provider.mojom', ], 'includes': [ '../../mojo/mojom_bindings_generator.gypi',
diff --git a/docs/closure_compilation.md b/docs/closure_compilation.md index 2f0907ab..931029c 100644 --- a/docs/closure_compilation.md +++ b/docs/closure_compilation.md
@@ -39,7 +39,7 @@ ## Assumptions A working Chrome checkout. See here: -http://www.chromium.org/developers/how-tos/get-the-code +https://www.chromium.org/developers/how-tos/get-the-code ## Typechecking Your Javascript
diff --git a/docs/common_build_tasks.md b/docs/common_build_tasks.md index c181055..a518dff 100644 --- a/docs/common_build_tasks.md +++ b/docs/common_build_tasks.md
@@ -6,7 +6,7 @@ system. If you're new to Chromium development, read the -[getting started guides](http://dev.chromium.org/developers/how-tos/get-the-code). +[getting started guides](https://www.chromium.org/developers/how-tos/get-the-code). There is some additional documentation on [setting GYP build parameters](http://dev.chromium.org/developers/gyp-environment-variables).
diff --git a/docs/ios_build_instructions.md b/docs/ios_build_instructions.md index 0f772a1..8a4e60b 100644 --- a/docs/ios_build_instructions.md +++ b/docs/ios_build_instructions.md
@@ -92,13 +92,13 @@ ## Converting an existing Mac checkout into an iOS checkout -If you want to convert your Mac checkout into an iOS checkout, you can -follow those steps: +If you want to convert your Mac checkout into an iOS checkout, follow the steps +below: -1. Add `target_os = [ "ios" ]` to the bottom of your `chromium/.gclient` +1. Add `target_os = [ "ios" ]` to the bottom of your `chromium/.gclient` file. -2. Make sure you have the following in your `chromium/chromium.gyp_env` +1. Make sure you have the following in your `chromium/chromium.gyp_env` file (removing the `chromium_ios_signing=0` if you want to make developer-signed builds): @@ -109,9 +109,8 @@ } ``` -Then make sure you sync again to get all the new files like the following. At -the end it will run `build/gyp_chromium` which will regenerate all the build -files according to the new settings. +1. Make sure to sync again to fetch the iOS specific dependencies and +regenerate build rules using: ```shell gclient sync @@ -120,6 +119,6 @@ ## Troubleshooting If your build fails, check the iOS columns of [the Mac -waterfall](http://build.chromium.org/p/chromium.mac/console) (the last -two) to see if the bots are green. In general they should be, since -failures on those bots will close the tree. +waterfall](http://build.chromium.org/p/chromium.mac/console) (the last two) to +see if the bots are green. In general they should be, since failures on those +bots will close the tree.
diff --git a/docs/linux_build_instructions.md b/docs/linux_build_instructions.md index 7802382a..e6ecbe75 100644 --- a/docs/linux_build_instructions.md +++ b/docs/linux_build_instructions.md
@@ -4,7 +4,7 @@ ## Get the code -[Get the Code](http://dev.chromium.org/developers/how-tos/get-the-code). The +[Get the Code](https://www.chromium.org/developers/how-tos/get-the-code). The general instructions on the "Get the code" page cover basic Linux build setup and configuration.
diff --git a/docs/mac_build_instructions.md b/docs/mac_build_instructions.md index da40344..f0fa683 100644 --- a/docs/mac_build_instructions.md +++ b/docs/mac_build_instructions.md
@@ -18,7 +18,7 @@ ## Getting the code -[Check out the source code](http://dev.chromium.org/developers/how-tos/get-the-code) +[Check out the source code](https://www.chromium.org/developers/how-tos/get-the-code) using Git. Before checking out, go to the
diff --git a/docs/profiling_content_shell_on_android.md b/docs/profiling_content_shell_on_android.md index cf33d06..7fb21c2 100644 --- a/docs/profiling_content_shell_on_android.md +++ b/docs/profiling_content_shell_on_android.md
@@ -18,7 +18,7 @@ 1. Get the code! You’ll want a second checkout as this will be android-specific. You know the drill: - http://dev.chromium.org/developers/how-tos/get-the-code + https://www.chromium.org/developers/how-tos/get-the-code 1. Append this to your `.gclient` file: `target_os = ['android']` 1. Create `chromium.gyp_env` next to your `.gclient` file: `echo "{ 'GYP_DEFINES': 'OS=android', }" > chromium.gyp_env`
diff --git a/extensions/browser/api/socket/tcp_socket.cc b/extensions/browser/api/socket/tcp_socket.cc index 2a8e718..a69ed02 100644 --- a/extensions/browser/api/socket/tcp_socket.cc +++ b/extensions/browser/api/socket/tcp_socket.cc
@@ -86,6 +86,12 @@ callback.Run(net::ERR_CONNECTION_FAILED); return; } + + if (is_connected_) { + callback.Run(net::ERR_SOCKET_IS_CONNECTED); + return; + } + DCHECK(!server_socket_.get()); socket_mode_ = CLIENT; connect_callback_ = callback; @@ -130,7 +136,9 @@ return; } - if (!read_callback_.is_null()) { + if (!read_callback_.is_null() || !connect_callback_.is_null()) { + // It's illegal to read a net::TCPSocket while a pending Connect or Read is + // already in progress. callback.Run(net::ERR_IO_PENDING, NULL); return; } @@ -140,7 +148,7 @@ return; } - if (!socket_.get()) { + if (!socket_.get() || !is_connected_) { callback.Run(net::ERR_SOCKET_NOT_CONNECTED, NULL); return; } @@ -277,8 +285,12 @@ DCHECK(!connect_callback_.is_null()); DCHECK(!is_connected_); is_connected_ = result == net::OK; - connect_callback_.Run(result); + + // The completion callback may re-enter TCPSocket, e.g. to Read(); therefore + // we reset |connect_callback_| before calling it. + CompletionCallback connect_callback = connect_callback_; connect_callback_.Reset(); + connect_callback.Run(result); } void TCPSocket::OnReadComplete(scoped_refptr<net::IOBuffer> io_buffer,
diff --git a/extensions/browser/extension_function_histogram_value.h b/extensions/browser/extension_function_histogram_value.h index 9b5b339b..9d9b366 100644 --- a/extensions/browser/extension_function_histogram_value.h +++ b/extensions/browser/extension_function_histogram_value.h
@@ -702,7 +702,7 @@ GCM_SEND, SERIAL_CONNECT, SERIAL_DISCONNECT, - MEDIAGALLERIES_GETALLMEDIAFILESYSTEMMETADATA, + DELETED_MEDIAGALLERIES_GETALLMEDIAFILESYSTEMMETADATA, FIRSTRUNPRIVATE_GETLOCALIZEDSTRINGS, FIRSTRUNPRIVATE_LAUNCHTUTORIAL, SOCKETS_UDP_SETPAUSED, @@ -777,7 +777,7 @@ FILESYSTEMPROVIDER_UNMOUNT, FILESYSTEMPROVIDERINTERNAL_UNMOUNTREQUESTEDSUCCESS, DELETED_FILESYSTEMPROVIDERINTERNAL_UNMOUNTREQUESTEDERROR, - MEDIAGALLERIES_DROPPERMISSIONFORMEDIAFILESYSTEM, + DELETED_MEDIAGALLERIES_DROPPERMISSIONFORMEDIAFILESYSTEM, WEBCAMPRIVATE_SET, WEBCAMPRIVATE_RESET, WEBCAMPRIVATE_GET, @@ -945,8 +945,8 @@ EASYUNLOCKPRIVATE_CONNECTTOBLUETOOTHSERVICEINSECURELY, MEDIAGALLERIES_ADDGALLERYWATCH, MEDIAGALLERIES_REMOVEGALLERYWATCH, - MEDIAGALLERIES_GETALLGALLERYWATCH, - MEDIAGALLERIES_REMOVEALLGALLERYWATCH, + DELETED_MEDIAGALLERIES_GETALLGALLERYWATCH, + DELETED_MEDIAGALLERIES_REMOVEALLGALLERYWATCH, MANAGEMENT_GETSELF, APP_CURRENTWINDOWINTERNAL_SETVISIBLEONALLWORKSPACES, EASYUNLOCKPRIVATE_GETSIGNINCHALLENGE,
diff --git a/extensions/common/feature_switch.cc b/extensions/common/feature_switch.cc index 88301f1..36fb3857 100644 --- a/extensions/common/feature_switch.cc +++ b/extensions/common/feature_switch.cc
@@ -52,7 +52,7 @@ FeatureSwitch::DEFAULT_DISABLED), extension_action_redesign(switches::kExtensionActionRedesign, kExtensionActionRedesignExperiment, - FeatureSwitch::DEFAULT_DISABLED), + FeatureSwitch::DEFAULT_ENABLED), extension_action_redesign_override(switches::kExtensionActionRedesign, FeatureSwitch::DEFAULT_ENABLED), scripts_require_action(switches::kScriptsRequireAction,
diff --git a/extensions/common/file_util.cc b/extensions/common/file_util.cc index ae12f2c..830cc48 100644 --- a/extensions/common/file_util.cc +++ b/extensions/common/file_util.cc
@@ -441,8 +441,10 @@ return base::FilePath(); // Drop the leading slashes and convert %-encoded UTF8 to regular UTF8. - std::string file_path = net::UnescapeURLComponent(url_path, - net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); + std::string file_path = net::UnescapeURLComponent( + url_path, + net::UnescapeRule::SPACES | + net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS); size_t skip = file_path.find_first_not_of("/\\"); if (skip != file_path.npos) file_path = file_path.substr(skip); @@ -460,8 +462,10 @@ base::FilePath ExtensionResourceURLToFilePath(const GURL& url, const base::FilePath& root) { - std::string host = net::UnescapeURLComponent(url.host(), - net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS); + std::string host = net::UnescapeURLComponent( + url.host(), + net::UnescapeRule::SPACES | + net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS); if (host.empty()) return base::FilePath();
diff --git a/extensions/common/file_util_unittest.cc b/extensions/common/file_util_unittest.cc index c058400..e63856c3 100644 --- a/extensions/common/file_util_unittest.cc +++ b/extensions/common/file_util_unittest.cc
@@ -454,26 +454,20 @@ const char* url; const char* expected_relative_path; } test_cases[] = { - { URL_PREFIX "simple.html", - "simple.html" }, - { URL_PREFIX "directory/to/file.html", - "directory/to/file.html" }, - { URL_PREFIX "escape%20spaces.html", - "escape spaces.html" }, - { URL_PREFIX "%C3%9Cber.html", - "\xC3\x9C" "ber.html" }, + {URL_PREFIX "simple.html", "simple.html"}, + {URL_PREFIX "directory/to/file.html", "directory/to/file.html"}, + {URL_PREFIX "escape%20spaces.html", "escape spaces.html"}, + {URL_PREFIX "%C3%9Cber.html", + "\xC3\x9C" + "ber.html"}, #if defined(OS_WIN) - { URL_PREFIX "C%3A/simple.html", - "" }, + {URL_PREFIX "C%3A/simple.html", ""}, #endif - { URL_PREFIX "////simple.html", - "simple.html" }, - { URL_PREFIX "/simple.html", - "simple.html" }, - { URL_PREFIX "\\simple.html", - "simple.html" }, - { URL_PREFIX "\\\\foo\\simple.html", - "foo/simple.html" }, + {URL_PREFIX "////simple.html", "simple.html"}, + {URL_PREFIX "/simple.html", "simple.html"}, + {URL_PREFIX "\\simple.html", "simple.html"}, + {URL_PREFIX "\\\\foo\\simple.html", "foo/simple.html"}, + {URL_PREFIX "..%2f..%2fsimple.html", "..%2f..%2fsimple.html"}, }; #undef URL_PREFIX @@ -506,6 +500,10 @@ ASSERT_TRUE(base::WriteFile(resource_path, data, sizeof(data))); resource_path = api_path.Append(FILE_PATH_LITERAL("escape spaces.js")); ASSERT_TRUE(base::WriteFile(resource_path, data, sizeof(data))); + resource_path = api_path.Append(FILE_PATH_LITERAL("escape spaces.js")); + ASSERT_TRUE(base::WriteFile(resource_path, data, sizeof(data))); + resource_path = api_path.Append(FILE_PATH_LITERAL("..%2f..%2fsimple.html")); + ASSERT_TRUE(base::WriteFile(resource_path, data, sizeof(data))); #ifdef FILE_PATH_USES_WIN_SEPARATORS #define SEP "\\" @@ -517,27 +515,21 @@ const char* url; const base::FilePath::CharType* expected_path; } test_cases[] = { - { URL_PREFIX "apiname/test.js", - FILE_PATH_LITERAL("test.js") }, - { URL_PREFIX "/apiname/test.js", - FILE_PATH_LITERAL("test.js") }, - // Test % escape - { URL_PREFIX "apiname/%74%65st.js", - FILE_PATH_LITERAL("test.js") }, - { URL_PREFIX "apiname/escape%20spaces.js", - FILE_PATH_LITERAL("escape spaces.js") }, - // Test file does not exist. - { URL_PREFIX "apiname/directory/to/file.js", - NULL }, - // Test apiname/../../test.js - { URL_PREFIX "apiname/../../test.js", - FILE_PATH_LITERAL("test.js") }, - { URL_PREFIX "apiname/..%2F../test.js", - NULL }, - { URL_PREFIX "apiname/f/../../../test.js", - FILE_PATH_LITERAL("test.js") }, - { URL_PREFIX "apiname/f%2F..%2F..%2F../test.js", - NULL }, + {URL_PREFIX "apiname/test.js", FILE_PATH_LITERAL("test.js")}, + {URL_PREFIX "/apiname/test.js", FILE_PATH_LITERAL("test.js")}, + // Test % escape + {URL_PREFIX "apiname/%74%65st.js", FILE_PATH_LITERAL("test.js")}, + {URL_PREFIX "apiname/escape%20spaces.js", + FILE_PATH_LITERAL("escape spaces.js")}, + // Test file does not exist. + {URL_PREFIX "apiname/directory/to/file.js", NULL}, + // Test apiname/../../test.js + {URL_PREFIX "apiname/../../test.js", FILE_PATH_LITERAL("test.js")}, + {URL_PREFIX "apiname/..%2F../test.js", NULL}, + {URL_PREFIX "apiname/f/../../../test.js", FILE_PATH_LITERAL("test.js")}, + {URL_PREFIX "apiname/f%2F..%2F..%2F../test.js", NULL}, + {URL_PREFIX "apiname/..%2f..%2fsimple.html", + FILE_PATH_LITERAL("..%2f..%2fsimple.html")}, }; #undef SEP #undef URL_PREFIX
diff --git a/extensions/renderer/module_system.cc b/extensions/renderer/module_system.cc index f027413..4ca689a 100644 --- a/extensions/renderer/module_system.cc +++ b/extensions/renderer/module_system.cc
@@ -399,7 +399,7 @@ v8::Local<v8::External>::Cast(module_system_value)->Value()); v8::Local<v8::Value> v8_module_name; - if (!GetProperty(context, parameters, kModuleName, &v8_module_name)) { + if (!GetPrivateProperty(context, parameters, kModuleName, &v8_module_name)) { Warn(isolate, "Cannot find module."); return; } @@ -419,7 +419,7 @@ v8::Local<v8::Object> module = v8::Local<v8::Object>::Cast(module_value); v8::Local<v8::Value> field_value; - if (!GetProperty(context, parameters, kModuleField, &field_value)) { + if (!GetPrivateProperty(context, parameters, kModuleField, &field_value)) { module_system->HandleException(try_catch); return; } @@ -479,9 +479,9 @@ v8::HandleScope handle_scope(GetIsolate()); v8::Local<v8::Object> parameters = v8::Object::New(GetIsolate()); v8::Local<v8::Context> context = context_->v8_context(); - SetProperty(context, parameters, kModuleName, + SetPrivateProperty(context, parameters, kModuleName, ToV8StringUnsafe(GetIsolate(), module_name.c_str())); - SetProperty(context, parameters, kModuleField, + SetPrivateProperty(context, parameters, kModuleField, ToV8StringUnsafe(GetIsolate(), module_field.c_str())); auto maybe = object->SetAccessor( context, ToV8StringUnsafe(GetIsolate(), field.c_str()), getter, NULL,
diff --git a/gpu/BUILD.gn b/gpu/BUILD.gn index bf1d6b0..d426e15 100644 --- a/gpu/BUILD.gn +++ b/gpu/BUILD.gn
@@ -45,7 +45,6 @@ "//gpu/command_buffer/common:common_sources", "//gpu/command_buffer/service:service_sources", "//gpu/config:config_sources", - "//gpu/ipc:ipc_sources", "//gpu/ipc/common:ipc_common_sources", ] }
diff --git a/gpu/command_buffer/common/BUILD.gn b/gpu/command_buffer/common/BUILD.gn index af72aba..ea6d606 100644 --- a/gpu/command_buffer/common/BUILD.gn +++ b/gpu/command_buffer/common/BUILD.gn
@@ -91,5 +91,5 @@ ] typemaps = [ "mojo.typemap" ] - typemap_deps = [ "//gpu/ipc" ] + typemap_deps = [ "//gpu/ipc/common" ] }
diff --git a/gpu/command_buffer/common/mojo.typemap b/gpu/command_buffer/common/mojo.typemap index 4e27856..cbc36c56a 100644 --- a/gpu/command_buffer/common/mojo.typemap +++ b/gpu/command_buffer/common/mojo.typemap
@@ -8,42 +8,42 @@ "typename": "gpu::Capabilities", "headers": [ "gpu/command_buffer/common/capabilities.h", - "gpu/ipc/gpu_command_buffer_traits.h" + "gpu/ipc/common/gpu_command_buffer_traits.h" ] }, "gpu.mojom.CommandBufferState": { "typename": "gpu::CommandBuffer::State", "headers": [ "gpu/command_buffer/common/command_buffer.h", - "gpu/ipc/gpu_command_buffer_traits.h" + "gpu/ipc/common/gpu_command_buffer_traits.h" ] }, "gpu.mojom.Mailbox": { "typename": "gpu::Mailbox", "headers": [ "gpu/command_buffer/common/mailbox.h", - "gpu/ipc/gpu_command_buffer_traits.h" + "gpu/ipc/common/gpu_command_buffer_traits.h" ] }, "gpu.mojom.MailboxHolder": { "typename": "gpu::MailboxHolder", "headers": [ "gpu/command_buffer/common/mailbox_holder.h", - "gpu/ipc/gpu_command_buffer_traits.h" + "gpu/ipc/common/gpu_command_buffer_traits.h" ] }, "gpu.mojom.SyncToken": { "typename": "gpu::SyncToken", "headers": [ "gpu/command_buffer/common/sync_token.h", - "gpu/ipc/gpu_command_buffer_traits.h" + "gpu/ipc/common/gpu_command_buffer_traits.h" ] }, "gpu.mojom.ValueState": { "typename": "gpu::ValueState", "headers": [ "gpu/command_buffer/common/value_state.h", - "gpu/ipc/gpu_command_buffer_traits.h" + "gpu/ipc/common/gpu_command_buffer_traits.h" ] } }
diff --git a/gpu/command_buffer/service/feature_info_unittest.cc b/gpu/command_buffer/service/feature_info_unittest.cc index c4906a3..a842ec2 100644 --- a/gpu/command_buffer/service/feature_info_unittest.cc +++ b/gpu/command_buffer/service/feature_info_unittest.cc
@@ -1198,7 +1198,7 @@ TEST_P(FeatureInfoTest, InitializeSamplersWithARBSamplerObjects) { SetupInitExpectationsWithGLVersion( - "GL_ARB_sampler_objects", "", "OpenGL 3.0"); + "GL_ARB_sampler_objects", "", "3.0"); EXPECT_TRUE(info_->feature_flags().enable_samplers); } @@ -1242,7 +1242,7 @@ } TEST_P(FeatureInfoTest, InitializeWithoutSamplers) { - SetupInitExpectationsWithGLVersion("", "", "OpenGL GL 3.0"); + SetupInitExpectationsWithGLVersion("", "", "3.0"); EXPECT_FALSE(info_->feature_flags().enable_samplers); }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_drawing.cc b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_drawing.cc index 40d1361..ce0d13a 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_drawing.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_drawing.cc
@@ -62,7 +62,7 @@ // Most of the tests in this file assume they're running on // desktop OpenGL, and large portions of the tests will become // no-ops if they aren't. - init.gl_version = "opengl 2.1"; + init.gl_version = "2.1"; init.has_alpha = true; init.has_depth = true; init.request_alpha = true;
diff --git a/gpu/command_buffer/service/gpu_tracer_unittest.cc b/gpu/command_buffer/service/gpu_tracer_unittest.cc index a88b070d..760818d1 100644 --- a/gpu/command_buffer/service/gpu_tracer_unittest.cc +++ b/gpu/command_buffer/service/gpu_tracer_unittest.cc
@@ -96,7 +96,7 @@ const char* gl_version = "3.2"; const char* extensions = ""; if (GetTimerType() == gfx::GPUTiming::kTimerTypeEXT) { - gl_version = "opengl 2.1"; + gl_version = "2.1"; extensions = "GL_EXT_timer_query"; } else if (GetTimerType() == gfx::GPUTiming::kTimerTypeDisjoint) { gl_version = "opengl es 3.0";
diff --git a/gpu/command_buffer/service/renderbuffer_manager_unittest.cc b/gpu/command_buffer/service/renderbuffer_manager_unittest.cc index e98b3c1..815d8ee 100644 --- a/gpu/command_buffer/service/renderbuffer_manager_unittest.cc +++ b/gpu/command_buffer/service/renderbuffer_manager_unittest.cc
@@ -36,7 +36,7 @@ gl_.get(), depth24_supported ? "GL_OES_depth24" : "", "", - use_gles ? "OpenGL ES 2.0" : "OpenGL 2.1"); + use_gles ? "OpenGL ES 2.0" : "2.1"); feature_info_->InitializeForTesting(); manager_.reset(new RenderbufferManager( memory_tracker, kMaxSize, kMaxSamples, feature_info_.get()));
diff --git a/gpu/config/software_rendering_list_json.cc b/gpu/config/software_rendering_list_json.cc index fb8b84c..ed1dcd66 100644 --- a/gpu/config/software_rendering_list_json.cc +++ b/gpu/config/software_rendering_list_json.cc
@@ -87,6 +87,9 @@ "op": ">=", "value": "10.0.4" } + }, + { + "driver_vendor": ".*ANGLE.*" } ], "features": [
diff --git a/gpu/gpu.gyp b/gpu/gpu.gyp index 07b7cab..b8dec1b 100644 --- a/gpu/gpu.gyp +++ b/gpu/gpu.gyp
@@ -523,7 +523,6 @@ 'command_buffer_service', 'gles2_cmd_helper', 'gpu_config', - 'gpu_ipc', 'gpu_ipc_common', ], 'sources': [ @@ -594,17 +593,6 @@ 'msvs_disabled_warnings': [4267, ], }, { - # GN version: //gpu/ipc - 'target_name': 'gpu_ipc', - 'type': 'static_library', - 'includes': [ - 'gpu_ipc.gypi', - ], - 'dependencies': [ - 'command_buffer_common', - ], - }, - { # GN version: //gpu/ipc/common 'target_name': 'gpu_ipc_common', 'type': 'static_library', @@ -644,7 +632,6 @@ 'command_buffer_service.gypi', 'gles2_cmd_helper.gypi', 'gpu_config.gypi', - 'gpu_ipc.gypi', 'gpu_ipc_common.gypi', '../build/android/increase_size_for_speed.gypi', ], @@ -698,14 +685,6 @@ ], }, { - # GN version: //gpu/ipc - 'target_name': 'gpu_ipc', - 'type': 'none', - 'dependencies': [ - 'gpu', - ], - }, - { # GN version: //gpu/ipc/common 'target_name': 'gpu_ipc_common', 'type': 'none', @@ -740,30 +719,6 @@ }, }, { - 'target_name': 'gpu_ipc_win64', - 'type': 'static_library', - 'variables': { - 'nacl_win64_target': 1, - }, - 'includes': [ - 'gpu_ipc.gypi', - ], - 'dependencies': [ - '../base/base.gyp:base_win64', - '../ipc/ipc.gyp:ipc_win64', - 'command_buffer_common_win64', - ], - 'defines': [ - '<@(nacl_win64_defines)', - 'GPU_IMPLEMENTATION', - ], - 'configurations': { - 'Common_Base': { - 'msvs_target_platform': 'x64', - }, - }, - }, - { 'target_name': 'gpu_ipc_common_win64', 'type': 'static_library', 'variables': {
diff --git a/gpu/gpu_ipc.gypi b/gpu/gpu_ipc.gypi deleted file mode 100644 index 1d6e1c9..0000000 --- a/gpu/gpu_ipc.gypi +++ /dev/null
@@ -1,28 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'dependencies': [ - '../ipc/ipc.gyp:ipc', - '../third_party/khronos/khronos.gyp:khronos_headers', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - 'ipc/gpu_command_buffer_traits.cc', - 'ipc/gpu_command_buffer_traits.h', - 'ipc/id_type_traits.h', - ], - 'conditions': [ - # This section applies to gpu_ipc_win64, used by the NaCl Win64 helper - # (nacl64.exe). - ['nacl_win64_target==1', { - # gpu_ipc_win64 must only link against the 64-bit ipc target. - 'dependencies!': [ - '../ipc/ipc.gyp:ipc', - ], - }], - ], -}
diff --git a/gpu/gpu_ipc_common.gypi b/gpu/gpu_ipc_common.gypi index 48f404a..9cbe65a8 100644 --- a/gpu/gpu_ipc_common.gypi +++ b/gpu/gpu_ipc_common.gypi
@@ -6,11 +6,15 @@ 'dependencies': [ '../base/base.gyp:base', '../ipc/ipc.gyp:ipc', + '../third_party/khronos/khronos.gyp:khronos_headers', ], 'include_dirs': [ '..', ], 'sources': [ + 'ipc/common/gpu_command_buffer_traits.cc', + 'ipc/common/gpu_command_buffer_traits.h', + 'ipc/common/id_type_traits.h', 'ipc/common/memory_stats.cc', 'ipc/common/memory_stats.h', ], @@ -20,6 +24,7 @@ ['nacl_win64_target==1', { # gpu_ipc_win64 must only link against the 64-bit ipc target. 'dependencies!': [ + '../base/base.gyp:base', '../ipc/ipc.gyp:ipc', ], }],
diff --git a/gpu/gpu_nacl.gyp b/gpu/gpu_nacl.gyp index 1f38619..7c8cfc0f 100644 --- a/gpu/gpu_nacl.gyp +++ b/gpu/gpu_nacl.gyp
@@ -117,7 +117,7 @@ 'build_nonsfi_helper': 1, }, 'includes': [ - 'gpu_ipc.gypi', + 'gpu_ipc_common.gypi', ], 'dependencies': [ '../base/base_nacl.gyp:base_nacl',
diff --git a/gpu/ipc/BUILD.gn b/gpu/ipc/BUILD.gn deleted file mode 100644 index bcf999d..0000000 --- a/gpu/ipc/BUILD.gn +++ /dev/null
@@ -1,35 +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. - -group("ipc") { - if (is_component_build) { - public_deps = [ - "//gpu", - ] - } else { - public_deps = [ - ":ipc_sources", - ] - } -} - -source_set("ipc_sources") { - visibility = [ "//gpu/*" ] - - sources = [ - "gpu_command_buffer_traits.cc", - "gpu_command_buffer_traits.h", - "id_type_traits.h", - ] - - configs += [ - "//gpu:gpu_implementation", - "//third_party/khronos:khronos_headers", - ] - - deps = [ - "//gpu/command_buffer/common:common_sources", - "//ipc", - ] -}
diff --git a/gpu/ipc/common/BUILD.gn b/gpu/ipc/common/BUILD.gn index d99f577..5d4cb18 100644 --- a/gpu/ipc/common/BUILD.gn +++ b/gpu/ipc/common/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. -group("ipc") { +group("common") { if (is_component_build) { public_deps = [ "//gpu", @@ -18,14 +18,21 @@ visibility = [ "//gpu/*" ] sources = [ + "gpu_command_buffer_traits.cc", + "gpu_command_buffer_traits.h", + "id_type_traits.h", "memory_stats.cc", "memory_stats.h", ] - configs += [ "//gpu:gpu_implementation" ] + configs += [ + "//gpu:gpu_implementation", + "//third_party/khronos:khronos_headers", + ] deps = [ "//base", + "//gpu/command_buffer/common:common_sources", "//ipc", ] }
diff --git a/gpu/ipc/DEPS b/gpu/ipc/common/DEPS similarity index 100% rename from gpu/ipc/DEPS rename to gpu/ipc/common/DEPS
diff --git a/gpu/ipc/OWNERS b/gpu/ipc/common/OWNERS similarity index 100% rename from gpu/ipc/OWNERS rename to gpu/ipc/common/OWNERS
diff --git a/gpu/ipc/gpu_command_buffer_traits.cc b/gpu/ipc/common/gpu_command_buffer_traits.cc similarity index 95% rename from gpu/ipc/gpu_command_buffer_traits.cc rename to gpu/ipc/common/gpu_command_buffer_traits.cc index be302db..f5d4728 100644 --- a/gpu/ipc/gpu_command_buffer_traits.cc +++ b/gpu/ipc/common/gpu_command_buffer_traits.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "gpu/ipc/gpu_command_buffer_traits.h" +#include "gpu/ipc/common/gpu_command_buffer_traits.h" #include <stddef.h> #include <stdint.h> @@ -15,25 +15,25 @@ // Generate param traits size methods. #include "ipc/param_traits_size_macros.h" namespace IPC { -#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +#include "gpu/ipc/common/gpu_command_buffer_traits_multi.h" } // namespace IPC // Generate param traits write methods. #include "ipc/param_traits_write_macros.h" namespace IPC { -#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +#include "gpu/ipc/common/gpu_command_buffer_traits_multi.h" } // namespace IPC // Generate param traits read methods. #include "ipc/param_traits_read_macros.h" namespace IPC { -#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +#include "gpu/ipc/common/gpu_command_buffer_traits_multi.h" } // namespace IPC // Generate param traits log methods. #include "ipc/param_traits_log_macros.h" namespace IPC { -#include "gpu/ipc/gpu_command_buffer_traits_multi.h" +#include "gpu/ipc/common/gpu_command_buffer_traits_multi.h" } // namespace IPC namespace IPC {
diff --git a/gpu/ipc/gpu_command_buffer_traits.h b/gpu/ipc/common/gpu_command_buffer_traits.h similarity index 95% rename from gpu/ipc/gpu_command_buffer_traits.h rename to gpu/ipc/common/gpu_command_buffer_traits.h index a968f02f..1bf5314e 100644 --- a/gpu/ipc/gpu_command_buffer_traits.h +++ b/gpu/ipc/common/gpu_command_buffer_traits.h
@@ -7,8 +7,8 @@ #include "gpu/command_buffer/common/command_buffer.h" #include "gpu/gpu_export.h" -#include "gpu/ipc/gpu_command_buffer_traits_multi.h" -#include "gpu/ipc/id_type_traits.h" +#include "gpu/ipc/common/gpu_command_buffer_traits_multi.h" +#include "gpu/ipc/common/id_type_traits.h" #include "ipc/ipc_message_utils.h" namespace gpu {
diff --git a/gpu/ipc/gpu_command_buffer_traits_multi.h b/gpu/ipc/common/gpu_command_buffer_traits_multi.h similarity index 100% rename from gpu/ipc/gpu_command_buffer_traits_multi.h rename to gpu/ipc/common/gpu_command_buffer_traits_multi.h
diff --git a/gpu/ipc/id_type_traits.h b/gpu/ipc/common/id_type_traits.h similarity index 100% rename from gpu/ipc/id_type_traits.h rename to gpu/ipc/common/id_type_traits.h
diff --git a/infra/config/cq.cfg b/infra/config/cq.cfg index 584bb1f..ce8180a1 100644 --- a/infra/config/cq.cfg +++ b/infra/config/cq.cfg
@@ -67,12 +67,12 @@ builders { name: "ios_dbg_simulator_ninja" } builders { name: "ios_dbg_simulator_gn" - experiment_percentage: 10 + experiment_percentage: 100 } builders { name: "ios_rel_device_ninja" } builders { name: "ios_rel_device_gn" - experiment_percentage: 10 + experiment_percentage: 100 } builders { name: "mac_chromium_compile_dbg_ng" } builders { name: "mac_chromium_gn_rel" }
diff --git a/ios/OWNERS b/ios/OWNERS index 7672731..7a862dd 100644 --- a/ios/OWNERS +++ b/ios/OWNERS
@@ -1,4 +1,5 @@ droger@chromium.org +eugenebut@chromium.org noyau@chromium.org rohitrao@chromium.org sdefresne@chromium.org
diff --git a/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm b/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm index e7c9cd1..34909fb 100644 --- a/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm +++ b/ios/chrome/browser/browser_state/browser_state_keyed_service_factories.mm
@@ -11,7 +11,6 @@ #include "ios/chrome/browser/bookmarks/bookmark_model_factory.h" #include "ios/chrome/browser/bookmarks/startup_task_runner_service_factory.h" #include "ios/chrome/browser/content_settings/cookie_settings_factory.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h" #include "ios/chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "ios/chrome/browser/favicon/favicon_service_factory.h" #include "ios/chrome/browser/favicon/ios_chrome_favicon_loader_factory.h" @@ -76,7 +75,6 @@ ios::TopSitesFactory::GetInstance(); ios::WebDataServiceFactory::GetInstance(); ios::WebHistoryServiceFactory::GetInstance(); - IOSChromeDataReductionProxySettingsFactory::GetInstance(); IOSChromeGCMProfileServiceFactory::GetInstance(); IOSChromeLargeIconCacheFactory::GetInstance(); IOSChromeLargeIconServiceFactory::GetInstance();
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.h b/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.h index c9449ea9..28f7e77 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.h +++ b/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.h
@@ -14,10 +14,6 @@ class JsonPrefStore; -namespace data_reduction_proxy { -class DataReductionProxyNetworkDelegate; -} - namespace ios { class ChromeBrowserState; } @@ -131,8 +127,7 @@ void ClearNetworkingHistorySinceOnIOThread(base::Time time, const base::Closure& completion); - mutable scoped_ptr<data_reduction_proxy::DataReductionProxyNetworkDelegate> - network_delegate_; + mutable scoped_ptr<IOSChromeNetworkDelegate> network_delegate_; // Lazy initialization params. mutable scoped_ptr<LazyParams> lazy_params_;
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.mm b/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.mm index cd064ef..82ea94a 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.mm +++ b/ios/chrome/browser/browser_state/chrome_browser_state_impl_io_data.mm
@@ -15,9 +15,6 @@ #include "base/threading/sequenced_worker_pool.h" #include "base/threading/worker_pool.h" #include "components/cookie_config/cookie_store_util.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" -#include "components/data_reduction_proxy/core/browser/data_store_impl.h" #include "components/net_log/chrome_net_log.h" #include "components/prefs/json_pref_store.h" #include "components/prefs/pref_filter.h" @@ -25,9 +22,6 @@ #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/chrome_constants.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h" #include "ios/chrome/browser/ios_chrome_io_thread.h" #include "ios/chrome/browser/net/cookie_util.h" #include "ios/chrome/browser/net/http_server_properties_manager_factory.h" @@ -165,11 +159,6 @@ if (io_data_->http_server_properties_manager_) io_data_->http_server_properties_manager_->ShutdownOnPrefThread(); - // io_data_->data_reduction_proxy_io_data() might be NULL if Init() was - // never called. - if (io_data_->data_reduction_proxy_io_data()) - io_data_->data_reduction_proxy_io_data()->ShutdownOnUIThread(); - io_data_->ShutdownOnUIThread(GetAllContextGetters()); } @@ -197,32 +186,11 @@ io_data_->InitializeMetricsEnabledStateOnUIThread(); - // TODO(tbansal): Move this to IO thread once the data reduction proxy - // params are unified into a single object. - bool enable_quic_for_data_reduction_proxy = - IOSChromeIOThread::ShouldEnableQuicForDataReductionProxy(); - - io_data_->set_data_reduction_proxy_io_data( - CreateIOSChromeDataReductionProxyIOData( - GetApplicationContext()->GetIOSChromeIOThread()->net_log(), - browser_state_->GetPrefs(), - web::WebThread::GetTaskRunnerForThread(web::WebThread::IO), - web::WebThread::GetTaskRunnerForThread(web::WebThread::UI), - enable_quic_for_data_reduction_proxy)); - base::SequencedWorkerPool* pool = web::WebThread::GetBlockingPool(); scoped_refptr<base::SequencedTaskRunner> db_task_runner = pool->GetSequencedTaskRunnerWithShutdownBehavior( pool->GetSequenceToken(), base::SequencedWorkerPool::SKIP_ON_SHUTDOWN); - scoped_ptr<data_reduction_proxy::DataStore> store( - new data_reduction_proxy::DataStoreImpl(profile_path)); - IOSChromeDataReductionProxySettingsFactory::GetForBrowserState(browser_state_) - ->InitDataReductionProxySettings( - io_data_->data_reduction_proxy_io_data(), browser_state_->GetPrefs(), - browser_state_->GetRequestContext(), std::move(store), - web::WebThread::GetTaskRunnerForThread(web::WebThread::UI), - db_task_runner); } scoped_refptr<IOSChromeURLRequestContextGetter> @@ -356,8 +324,7 @@ main_context->set_net_log(io_thread->net_log()); - network_delegate_ = data_reduction_proxy_io_data()->CreateNetworkDelegate( - std::move(chrome_network_delegate), true); + network_delegate_ = std::move(chrome_network_delegate); main_context->set_network_delegate(network_delegate_.get()); @@ -426,12 +393,9 @@ new net::URLRequestJobFactoryImpl()); InstallProtocolHandlers(main_job_factory.get(), protocol_handlers); - // The data reduction proxy interceptor should be as close to the network as - // possible. + // TODO(crbug.com/592012): Delete request_interceptor and its handling if + // it's not needed in the future. URLRequestInterceptorScopedVector request_interceptors; - request_interceptors.insert( - request_interceptors.begin(), - data_reduction_proxy_io_data()->CreateInterceptor().release()); main_job_factory_ = SetUpJobFactoryDefaults(std::move(main_job_factory), std::move(request_interceptors), main_context->network_delegate()); @@ -475,12 +439,9 @@ scoped_ptr<net::URLRequestJobFactoryImpl> job_factory( new net::URLRequestJobFactoryImpl()); - // The data reduction proxy interceptor should be as close to the network as - // possible. + // TODO(crbug.com/592012): Delete request_interceptor and its handling if + // it's not needed in the future. URLRequestInterceptorScopedVector request_interceptors; - request_interceptors.insert( - request_interceptors.begin(), - data_reduction_proxy_io_data()->CreateInterceptor().release()); scoped_ptr<net::URLRequestJobFactory> top_job_factory(SetUpJobFactoryDefaults( std::move(job_factory), std::move(request_interceptors), main_context->network_delegate()));
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_io_data.cc b/ios/chrome/browser/browser_state/chrome_browser_state_io_data.cc index b9d5b88..56f3eba 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_io_data.cc +++ b/ios/chrome/browser/browser_state/chrome_browser_state_io_data.cc
@@ -27,7 +27,6 @@ #include "components/content_settings/core/browser/content_settings_provider.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h" #include "components/metrics/metrics_pref_names.h" #include "components/net_log/chrome_net_log.h" #include "components/prefs/pref_service.h" @@ -301,17 +300,6 @@ return enable_metrics_.GetValue(); } -bool ChromeBrowserStateIOData::IsDataReductionProxyEnabled() const { - return data_reduction_proxy_io_data() && - data_reduction_proxy_io_data()->IsEnabled(); -} - -void ChromeBrowserStateIOData::set_data_reduction_proxy_io_data( - scoped_ptr<data_reduction_proxy::DataReductionProxyIOData> - data_reduction_proxy_io_data) const { - data_reduction_proxy_io_data_ = std::move(data_reduction_proxy_io_data); -} - base::WeakPtr<net::HttpServerProperties> ChromeBrowserStateIOData::http_server_properties() const { return http_server_properties_->GetWeakPtr(); @@ -470,8 +458,6 @@ params.socket_performance_watcher_factory = io_thread->globals()->network_quality_estimator.get(); } - if (data_reduction_proxy_io_data_.get()) - params.proxy_delegate = data_reduction_proxy_io_data_->proxy_delegate(); return scoped_ptr<net::HttpNetworkSession>( new net::HttpNetworkSession(params));
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_io_data.h b/ios/chrome/browser/browser_state/chrome_browser_state_io_data.h index 837cf9b..3e31231e 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_io_data.h +++ b/ios/chrome/browser/browser_state/chrome_browser_state_io_data.h
@@ -36,10 +36,6 @@ class CookieSettings; } -namespace data_reduction_proxy { -class DataReductionProxyIOData; -} - namespace ios { class ChromeBrowserState; enum class ChromeBrowserStateType; @@ -128,13 +124,6 @@ // thread, and should only be called from there. bool GetMetricsEnabledStateOnIOThread() const; - bool IsDataReductionProxyEnabled() const; - - data_reduction_proxy::DataReductionProxyIOData* data_reduction_proxy_io_data() - const { - return data_reduction_proxy_io_data_.get(); - } - protected: // A URLRequestContext for apps that owns its cookie store and HTTP factory, // to ensure they are deleted. @@ -204,10 +193,6 @@ // the channel_id_service_ member and transfers ownership to the base class. void set_channel_id_service(net::ChannelIDService* channel_id_service) const; - void set_data_reduction_proxy_io_data( - scoped_ptr<data_reduction_proxy::DataReductionProxyIOData> - data_reduction_proxy_io_data) const; - net::ProxyService* proxy_service() const { return proxy_service_.get(); } base::WeakPtr<net::HttpServerProperties> http_server_properties() const; @@ -293,9 +278,6 @@ // Pointed to by URLRequestContext. mutable scoped_ptr<net::ChannelIDService> channel_id_service_; - mutable scoped_ptr<data_reduction_proxy::DataReductionProxyIOData> - data_reduction_proxy_io_data_; - mutable scoped_ptr<net::ProxyService> proxy_service_; mutable scoped_ptr<net::TransportSecurityState> transport_security_state_; mutable scoped_ptr<net::CTVerifier> cert_transparency_verifier_;
diff --git a/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc b/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc index 1320299..443935e 100644 --- a/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc +++ b/ios/chrome/browser/browser_state/chrome_browser_state_manager_impl.cc
@@ -28,8 +28,6 @@ #include "ios/chrome/browser/browser_state_metrics/browser_state_metrics.h" #include "ios/chrome/browser/chrome_constants.h" #include "ios/chrome/browser/chrome_paths.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h" #include "ios/chrome/browser/invalidation/ios_chrome_profile_invalidation_provider_factory.h" #include "ios/chrome/browser/passwords/ios_chrome_password_manager_setting_migrator_service_factory.h" #include "ios/chrome/browser/pref_names.h" @@ -203,10 +201,6 @@ void ChromeBrowserStateManagerImpl::DoFinalInitForServices( ios::ChromeBrowserState* browser_state) { - // Activate data reduction proxy. This creates a request context and makes a - // URL request to check if the data reduction proxy server is reachable. - IOSChromeDataReductionProxySettingsFactory::GetForBrowserState(browser_state) - ->MaybeActivateDataReductionProxy(true); ios::GaiaCookieManagerServiceFactory::GetForBrowserState(browser_state) ->Init(); ios::AccountConsistencyServiceFactory::GetForBrowserState(browser_state);
diff --git a/ios/chrome/browser/browsing_data/ios_chrome_browsing_data_remover.mm b/ios/chrome/browser/browsing_data/ios_chrome_browsing_data_remover.mm index 5ee25fd..c7f6990 100644 --- a/ios/chrome/browser/browsing_data/ios_chrome_browsing_data_remover.mm +++ b/ios/chrome/browser/browsing_data/ios_chrome_browsing_data_remover.mm
@@ -16,9 +16,6 @@ #include "base/metrics/user_metrics.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" #include "components/history/core/browser/history_service.h" #include "components/keyed_service/core/service_access_type.h" #include "components/omnibox/browser/omnibox_pref_names.h" @@ -29,8 +26,6 @@ #include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/autofill/personal_data_manager_factory.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h" #include "ios/chrome/browser/history/history_service_factory.h" #include "ios/chrome/browser/history/web_history_service_factory.h" #include "ios/chrome/browser/ios_chrome_io_thread.h" @@ -236,22 +231,6 @@ data_manager->Refresh(); } - data_reduction_proxy::DataReductionProxySettings* - data_reduction_proxy_settings = - IOSChromeDataReductionProxySettingsFactory::GetForBrowserState( - browser_state_); - - // |data_reduction_proxy_settings| is null if |browser_state_| is off the - // record. - if (data_reduction_proxy_settings) { - data_reduction_proxy::DataReductionProxyService* - data_reduction_proxy_service = - data_reduction_proxy_settings->data_reduction_proxy_service(); - if (data_reduction_proxy_service) { - data_reduction_proxy_service->compression_stats() - ->DeleteBrowsingHistory(delete_begin_, delete_end_); - } - } } if (remove_mask & REMOVE_COOKIES) {
diff --git a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.h b/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.h deleted file mode 100644 index 2007a0b..0000000 --- a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_IO_DATA_H_ -#define IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_IO_DATA_H_ - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" - -class PrefService; - -namespace base { -class SingleThreadTaskRunner; -} - -namespace data_reduction_proxy { -class DataReductionProxyIOData; -} - -namespace net { -class NetLog; -} - -// Constructs DataReductionProxyIOData suitable for use by Chrome on iOS. -scoped_ptr<data_reduction_proxy::DataReductionProxyIOData> -CreateIOSChromeDataReductionProxyIOData( - net::NetLog* net_log, - PrefService* prefs, - const scoped_refptr<base::SingleThreadTaskRunner>& io_thread_runner, - const scoped_refptr<base::SingleThreadTaskRunner>& ui_thread_runner, - bool enable_quic); - -#endif // IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_IO_DATA_H_
diff --git a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.mm b/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.mm deleted file mode 100644 index e3309784..0000000 --- a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.mm +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.h" - -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h" -#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" -#include "components/prefs/pref_service.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h" -#include "ios/chrome/browser/pref_names.h" -#include "ios/web/public/web_client.h" - -using data_reduction_proxy::DataReductionProxyParams; - -scoped_ptr<data_reduction_proxy::DataReductionProxyIOData> -CreateIOSChromeDataReductionProxyIOData( - net::NetLog* net_log, - PrefService* prefs, - const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner, - const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner, - bool enable_quic) { - DCHECK(net_log); - DCHECK(prefs); - - int flags = DataReductionProxyParams::kAllowed | - DataReductionProxyParams::kFallbackAllowed; - if (data_reduction_proxy::params::IsIncludedInPromoFieldTrial()) - flags |= DataReductionProxyParams::kPromoAllowed; - if (data_reduction_proxy::params::IsIncludedInHoldbackFieldTrial()) - flags |= DataReductionProxyParams::kHoldback; - - bool enabled = - prefs->GetBoolean(prefs::kDataSaverEnabled) || - data_reduction_proxy::params::ShouldForceEnableDataReductionProxy(); - scoped_ptr<data_reduction_proxy::DataReductionProxyIOData> - data_reduction_proxy_io_data( - new data_reduction_proxy::DataReductionProxyIOData( - IOSChromeDataReductionProxySettings::GetClient(), flags, net_log, - io_task_runner, ui_task_runner, enabled, enable_quic, - web::GetWebClient()->GetUserAgent(false))); - - return data_reduction_proxy_io_data; -}
diff --git a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.cc b/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.cc deleted file mode 100644 index 658baf6..0000000 --- a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.cc +++ /dev/null
@@ -1,213 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h" - -#include <string> -#include <utility> - -#include "base/base64.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/metrics/histogram_macros.h" -#include "base/strings/string_util.h" -#include "base/time/time.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" -#include "components/data_reduction_proxy/core/browser/data_store.h" -#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" -#include "components/prefs/pref_service.h" -#include "components/prefs/scoped_user_pref_update.h" -#include "components/proxy_config/proxy_config_pref_names.h" -#include "components/proxy_config/proxy_prefs.h" -#include "ios/chrome/browser/metrics/ios_chrome_metrics_service_accessor.h" -#include "ios/chrome/browser/pref_names.h" -#include "net/base/host_port_pair.h" -#include "net/proxy/proxy_config.h" -#include "net/proxy/proxy_list.h" -#include "net/proxy/proxy_server.h" -#include "net/url_request/url_request_context_getter.h" - -namespace { - -// Assume that any proxy host ending with this suffix is a Data Reduction Proxy. -const char kDataReductionProxyDefaultHostSuffix[] = ".googlezip.net"; - -// Searches |proxy_list| for any Data Reduction Proxies, even if they don't -// match a currently configured Data Reduction Proxy. -bool ContainsDataReductionProxyDefaultHostSuffix( - const net::ProxyList& proxy_list) { - for (const net::ProxyServer& proxy : proxy_list.GetAll()) { - if (proxy.is_valid() && !proxy.is_direct() && - base::EndsWith(proxy.host_port_pair().host(), - kDataReductionProxyDefaultHostSuffix, - base::CompareCase::SENSITIVE)) { - return true; - } - } - return false; -} - -// Searches |proxy_rules| for any Data Reduction Proxies, even if they don't -// match a currently configured Data Reduction Proxy. -bool ContainsDataReductionProxyDefaultHostSuffix( - const net::ProxyConfig::ProxyRules& proxy_rules) { - return ContainsDataReductionProxyDefaultHostSuffix( - proxy_rules.proxies_for_http) || - ContainsDataReductionProxyDefaultHostSuffix( - proxy_rules.proxies_for_https); -} - -// Extract the embedded PAC script from the given |pac_url|, and store the -// extracted script in |pac_script|. Returns true if extraction was successful, -// otherwise returns false. |pac_script| must not be NULL. -bool GetEmbeddedPacScript(const std::string& pac_url, std::string* pac_script) { - DCHECK(pac_script); - const std::string kPacURLPrefix = - "data:application/x-ns-proxy-autoconfig;base64,"; - return base::StartsWith(pac_url, kPacURLPrefix, - base::CompareCase::SENSITIVE) && - base::Base64Decode(pac_url.substr(kPacURLPrefix.size()), pac_script); -} - -} // namespace - -// The Data Reduction Proxy has been turned into a "best effort" proxy, -// meaning it is used only if the effective proxy configuration resolves to -// DIRECT for a URL. It no longer can be a ProxyConfig in the proxy preference -// hierarchy. This method removes the Data Reduction Proxy configuration from -// prefs, if present. |proxy_pref_name| is the name of the proxy pref. -void IOSChromeDataReductionProxySettings:: - MigrateDataReductionProxyOffProxyPrefs(PrefService* prefs) { - ProxyPrefMigrationResult proxy_pref_status = - MigrateDataReductionProxyOffProxyPrefsHelper(prefs); - UMA_HISTOGRAM_ENUMERATION( - "DataReductionProxy.ProxyPrefMigrationResult", proxy_pref_status, - IOSChromeDataReductionProxySettings::PROXY_PREF_MAX); -} - -IOSChromeDataReductionProxySettings::ProxyPrefMigrationResult -IOSChromeDataReductionProxySettings:: - MigrateDataReductionProxyOffProxyPrefsHelper(PrefService* prefs) { - base::DictionaryValue* dict = (base::DictionaryValue*)prefs->GetUserPrefValue( - proxy_config::prefs::kProxy); - if (!dict) - return PROXY_PREF_NOT_CLEARED; - - // Clear empty "proxy" dictionary created by a bug. See http://crbug/448172. - if (dict->empty()) { - prefs->ClearPref(proxy_config::prefs::kProxy); - return PROXY_PREF_CLEARED_EMPTY; - } - - std::string mode; - if (!dict->GetString("mode", &mode)) - return PROXY_PREF_NOT_CLEARED; - // Clear "system" proxy entry since this is the default. This entry was - // created by bug (http://crbug/448172). - if (ProxyModeToString(ProxyPrefs::MODE_SYSTEM) == mode) { - prefs->ClearPref(proxy_config::prefs::kProxy); - return PROXY_PREF_CLEARED_MODE_SYSTEM; - } - - // From M36 to M40, the DRP was configured using MODE_FIXED_SERVERS in the - // proxy pref. - if (ProxyModeToString(ProxyPrefs::MODE_FIXED_SERVERS) == mode) { - std::string proxy_server; - if (!dict->GetString("server", &proxy_server)) - return PROXY_PREF_NOT_CLEARED; - net::ProxyConfig::ProxyRules proxy_rules; - proxy_rules.ParseFromString(proxy_server); - // Clear the proxy pref if it matches a currently configured Data Reduction - // Proxy, or if the proxy host ends with ".googlezip.net", in order to - // ensure that any DRP in the pref is cleared even if the DRP configuration - // was changed. See http://crbug.com/476610. - ProxyPrefMigrationResult rv; - if (Config()->ContainsDataReductionProxy(proxy_rules)) - rv = PROXY_PREF_CLEARED_DRP; - else if (ContainsDataReductionProxyDefaultHostSuffix(proxy_rules)) - rv = PROXY_PREF_CLEARED_GOOGLEZIP; - else - return PROXY_PREF_NOT_CLEARED; - - prefs->ClearPref(proxy_config::prefs::kProxy); - return rv; - } - - // Before M35, the DRP was configured using a PAC script base64 encoded into a - // PAC url. - if (ProxyModeToString(ProxyPrefs::MODE_PAC_SCRIPT) == mode) { - std::string pac_url; - std::string pac_script; - if (!dict->GetString("pac_url", &pac_url) || - !GetEmbeddedPacScript(pac_url, &pac_script)) { - return PROXY_PREF_NOT_CLEARED; - } - - // In M35 and earlier, the way of specifying the DRP in a PAC script would - // always include the port number after the host even if the port number - // could be implied, so searching for ".googlezip.net:" in the PAC script - // indicates whether there's a proxy in that PAC script with a host of the - // form "*.googlezip.net". - if (pac_script.find(".googlezip.net:") == std::string::npos) - return PROXY_PREF_NOT_CLEARED; - - prefs->ClearPref(proxy_config::prefs::kProxy); - return PROXY_PREF_CLEARED_PAC_GOOGLEZIP; - } - - return PROXY_PREF_NOT_CLEARED; -} - -IOSChromeDataReductionProxySettings::IOSChromeDataReductionProxySettings() - : data_reduction_proxy::DataReductionProxySettings() {} - -IOSChromeDataReductionProxySettings::~IOSChromeDataReductionProxySettings() {} - -void IOSChromeDataReductionProxySettings::Shutdown() { - data_reduction_proxy::DataReductionProxyService* service = - data_reduction_proxy_service(); - if (service) - service->Shutdown(); -} - -void IOSChromeDataReductionProxySettings::InitDataReductionProxySettings( - data_reduction_proxy::DataReductionProxyIOData* io_data, - PrefService* profile_prefs, - net::URLRequestContextGetter* request_context_getter, - scoped_ptr<data_reduction_proxy::DataStore> store, - const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner, - const scoped_refptr<base::SequencedTaskRunner>& db_task_runner) { - // On mobile we write Data Reduction Proxy prefs directly to the pref service. - // On desktop we store Data Reduction Proxy prefs in memory, writing to disk - // every 60 minutes and on termination. Shutdown hooks must be added for - // Android and iOS in order for non-zero delays to be supported. - // (http://crbug.com/408264) - base::TimeDelta commit_delay = base::TimeDelta(); - - scoped_ptr<data_reduction_proxy::DataReductionProxyService> service = - make_scoped_ptr(new data_reduction_proxy::DataReductionProxyService( - this, profile_prefs, request_context_getter, std::move(store), - ui_task_runner, io_data->io_task_runner(), db_task_runner, - commit_delay)); - data_reduction_proxy::DataReductionProxySettings:: - InitDataReductionProxySettings(prefs::kDataSaverEnabled, profile_prefs, - io_data, std::move(service)); - io_data->SetDataReductionProxyService( - data_reduction_proxy_service()->GetWeakPtr()); - - data_reduction_proxy::DataReductionProxySettings:: - SetCallbackToRegisterSyntheticFieldTrial(base::Bind( - &IOSChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial)); - // TODO(bengr): Remove after M46. See http://crbug.com/445599. - MigrateDataReductionProxyOffProxyPrefs(profile_prefs); -} - -// static -data_reduction_proxy::Client IOSChromeDataReductionProxySettings::GetClient() { - return data_reduction_proxy::Client::CHROME_IOS; -}
diff --git a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h b/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h deleted file mode 100644 index 29303b5f..0000000 --- a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_SETTINGS_H_ -#define IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_SETTINGS_H_ - -#include "base/macros.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_request_options.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" -#include "components/keyed_service/core/keyed_service.h" - -class PrefService; - -namespace base { -class SequencedTaskRunner; -class SingleThreadTaskRunner; -} - -namespace data_reduction_proxy { -class DataReductionProxyIOData; -class DataStore; -} - -namespace net { -class URLRequestContextGetter; -} - -class PrefService; - -// Data reduction proxy settings class suitable for use with a Chrome browser. -// It is keyed to a browser context. -class IOSChromeDataReductionProxySettings - : public data_reduction_proxy::DataReductionProxySettings, - public KeyedService { - public: - // Enum values that can be reported for the - // DataReductionProxy.ProxyPrefMigrationResult histogram. These values must be - // kept in sync with their counterparts in histograms.xml. Visible here for - // testing purposes. - enum ProxyPrefMigrationResult { - PROXY_PREF_NOT_CLEARED = 0, - PROXY_PREF_CLEARED_EMPTY, - PROXY_PREF_CLEARED_MODE_SYSTEM, - PROXY_PREF_CLEARED_DRP, - PROXY_PREF_CLEARED_GOOGLEZIP, - PROXY_PREF_CLEARED_PAC_GOOGLEZIP, - PROXY_PREF_MAX - }; - - // Constructs a settings object. Construction and destruction must happen on - // the UI thread. - IOSChromeDataReductionProxySettings(); - - // Destructs the settings object. - ~IOSChromeDataReductionProxySettings() override; - - // Overrides KeyedService::Shutdown: - void Shutdown() override; - - // Initialize the settings object with the given io_data, prefs services, - // request context getter, data store, ui task runner, and db task runner. - void InitDataReductionProxySettings( - data_reduction_proxy::DataReductionProxyIOData* io_data, - PrefService* profile_prefs, - net::URLRequestContextGetter* request_context_getter, - scoped_ptr<data_reduction_proxy::DataStore> store, - const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner, - const scoped_refptr<base::SequencedTaskRunner>& db_task_runner); - - // Gets the client type for the data reduction proxy. - static data_reduction_proxy::Client GetClient(); - - // Public for testing. - void MigrateDataReductionProxyOffProxyPrefs(PrefService* prefs); - - private: - // Helper method for migrating the Data Reduction Proxy away from using the - // proxy pref. Returns the ProxyPrefMigrationResult value indicating the - // migration action taken. - ProxyPrefMigrationResult MigrateDataReductionProxyOffProxyPrefsHelper( - PrefService* prefs); - - DISALLOW_COPY_AND_ASSIGN(IOSChromeDataReductionProxySettings); -}; - -#endif // IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_SETTINGS_H_
diff --git a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.cc b/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.cc deleted file mode 100644 index 3dc4691..0000000 --- a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h" - -#include "base/memory/singleton.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h" - -// static -IOSChromeDataReductionProxySettings* -IOSChromeDataReductionProxySettingsFactory::GetForBrowserState( - ios::ChromeBrowserState* browser_state) { - return static_cast<IOSChromeDataReductionProxySettings*>( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -IOSChromeDataReductionProxySettingsFactory* -IOSChromeDataReductionProxySettingsFactory::GetInstance() { - return base::Singleton<IOSChromeDataReductionProxySettingsFactory>::get(); -} - -IOSChromeDataReductionProxySettingsFactory:: - IOSChromeDataReductionProxySettingsFactory() - : BrowserStateKeyedServiceFactory( - "DataReductionProxySettings", - BrowserStateDependencyManager::GetInstance()) {} - -IOSChromeDataReductionProxySettingsFactory:: - ~IOSChromeDataReductionProxySettingsFactory() {} - -scoped_ptr<KeyedService> -IOSChromeDataReductionProxySettingsFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - return make_scoped_ptr(new IOSChromeDataReductionProxySettings); -}
diff --git a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h b/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h deleted file mode 100644 index 53dba9c..0000000 --- a/ios/chrome/browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_SETTINGS_FACTORY_H_ -#define IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_SETTINGS_FACTORY_H_ - -#include "base/macros.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class IOSChromeDataReductionProxySettings; - -namespace base { -template <typename T> -struct DefaultSingletonTraits; -} - -namespace ios { -class ChromeBrowserState; -} - -// Constucts a DataReductionProxySettings object suitable for use with a -// Chrome browser. -class IOSChromeDataReductionProxySettingsFactory - : public BrowserStateKeyedServiceFactory { - public: - // Returns a settings object for the given |browser_state|. - static IOSChromeDataReductionProxySettings* GetForBrowserState( - ios::ChromeBrowserState* browser_state); - - // Returns an instance of this factory. - static IOSChromeDataReductionProxySettingsFactory* GetInstance(); - - private: - friend struct base::DefaultSingletonTraits< - IOSChromeDataReductionProxySettingsFactory>; - - IOSChromeDataReductionProxySettingsFactory(); - ~IOSChromeDataReductionProxySettingsFactory() override; - - // BrowserStateKeyedServiceFactory: - scoped_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* context) const override; - - DISALLOW_COPY_AND_ASSIGN(IOSChromeDataReductionProxySettingsFactory); -}; - -#endif // IOS_CHROME_BROWSER_DATA_REDUCTION_PROXY_IOS_CHROME_DATA_REDUCTION_PROXY_SETTINGS_FACTORY_H_
diff --git a/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.cc b/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.cc index 211f2591..cb480c27 100644 --- a/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.cc +++ b/ios/chrome/browser/metrics/ios_chrome_metrics_service_client.cc
@@ -36,6 +36,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_status_metrics_provider.h" +#include "components/sync_driver/device_count_metrics_provider.h" #include "components/variations/variations_associated_data.h" #include "components/version_info/version_info.h" #include "ios/chrome/browser/application_context.h" @@ -44,6 +45,7 @@ #include "ios/chrome/browser/metrics/ios_chrome_stability_metrics_provider.h" #include "ios/chrome/browser/metrics/mobile_session_shutdown_metrics_provider.h" #include "ios/chrome/browser/signin/ios_chrome_signin_status_metrics_provider_delegate.h" +#include "ios/chrome/browser/sync/ios_chrome_sync_client.h" #include "ios/chrome/browser/tab_parenting_global_observer.h" #include "ios/chrome/browser/ui/browser_otr_state.h" #include "ios/chrome/common/channel_info.h" @@ -254,6 +256,11 @@ metrics_service_->RegisterMetricsProvider( scoped_ptr<metrics::MetricsProvider>( new MobileSessionShutdownMetricsProvider(metrics_service_.get()))); + + metrics_service_->RegisterMetricsProvider( + scoped_ptr<metrics::MetricsProvider>( + new sync_driver::DeviceCountMetricsProvider( + base::Bind(&IOSChromeSyncClient::GetDeviceInfoTrackers)))); } void IOSChromeMetricsServiceClient::OnInitTaskGotDriveMetrics() {
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index 3bcb2bb..300c0ec 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -6,7 +6,6 @@ #include "components/autofill/core/browser/autofill_manager.h" #include "components/content_settings/core/browser/host_content_settings_map.h" -#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h" #include "components/dom_distiller/core/distilled_page_prefs.h" #include "components/flags_ui/pref_service_flags_storage.h" #include "components/gcm_driver/gcm_channel_status_syncer.h" @@ -70,8 +69,6 @@ [OmniboxGeolocationLocalState registerLocalState:registry]; [MemoryDebuggerManager registerLocalState:registry]; - data_reduction_proxy::RegisterPrefs(registry); - registry->RegisterBooleanPref(prefs::kBrowsingDataMigrationHasBeenPossible, false); @@ -80,7 +77,6 @@ void RegisterBrowserStatePrefs(user_prefs::PrefRegistrySyncable* registry) { autofill::AutofillManager::RegisterProfilePrefs(registry); - data_reduction_proxy::RegisterSyncableProfilePrefs(registry); dom_distiller::DistilledPagePrefs::RegisterProfilePrefs(registry); FirstRun::RegisterProfilePrefs(registry); gcm::GCMChannelStatusSyncer::RegisterProfilePrefs(registry);
diff --git a/ios/chrome/browser/sync/ios_chrome_sync_client.h b/ios/chrome/browser/sync/ios_chrome_sync_client.h index a398c71d..f8a31df 100644 --- a/ios/chrome/browser/sync/ios_chrome_sync_client.h +++ b/ios/chrome/browser/sync/ios_chrome_sync_client.h
@@ -5,6 +5,8 @@ #ifndef IOS_CHROME_BROWSER_SYNC_IOS_CHROME_SYNC_CLIENT_H__ #define IOS_CHROME_BROWSER_SYNC_IOS_CHROME_SYNC_CLIENT_H__ +#include <vector> + #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/sync_driver/sync_client.h" @@ -22,6 +24,7 @@ } namespace sync_driver { +class DeviceInfoTracker; class SyncApiComponentFactory; class SyncService; } @@ -58,9 +61,11 @@ void SetSyncApiComponentFactoryForTesting( scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory); - private: - void ClearBrowsingData(base::Time start, base::Time end); + // Iterates over browser states and returns any trackers that can be found. + static void GetDeviceInfoTrackers( + std::vector<const sync_driver::DeviceInfoTracker*>* trackers); + private: ios::ChromeBrowserState* const browser_state_; // The sync api component factory in use by this client.
diff --git a/ios/chrome/browser/sync/ios_chrome_sync_client.mm b/ios/chrome/browser/sync/ios_chrome_sync_client.mm index 89007d3..cabc122 100644 --- a/ios/chrome/browser/sync/ios_chrome_sync_client.mm +++ b/ios/chrome/browser/sync/ios_chrome_sync_client.mm
@@ -37,9 +37,11 @@ #include "components/sync_sessions/sync_sessions_client.h" #include "components/sync_sessions/synced_window_delegates_getter.h" #include "components/syncable_prefs/pref_service_syncable.h" +#include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/autofill/personal_data_manager_factory.h" #include "ios/chrome/browser/bookmarks/bookmark_model_factory.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" +#include "ios/chrome/browser/browser_state/chrome_browser_state_manager.h" #include "ios/chrome/browser/chrome_url_constants.h" #include "ios/chrome/browser/dom_distiller/dom_distiller_service_factory.h" #include "ios/chrome/browser/favicon/favicon_service_factory.h" @@ -382,3 +384,24 @@ scoped_ptr<sync_driver::SyncApiComponentFactory> component_factory) { component_factory_ = std::move(component_factory); } + +// static +void IOSChromeSyncClient::GetDeviceInfoTrackers( + std::vector<const sync_driver::DeviceInfoTracker*>* trackers) { + DCHECK(trackers); + std::vector<ios::ChromeBrowserState*> browser_state_list = + GetApplicationContext() + ->GetChromeBrowserStateManager() + ->GetLoadedBrowserStates(); + for (ios::ChromeBrowserState* browser_state : browser_state_list) { + ProfileSyncService* profile_sync_service = + IOSChromeProfileSyncServiceFactory::GetForBrowserState(browser_state); + if (profile_sync_service != nullptr) { + const sync_driver::DeviceInfoTracker* tracker = + profile_sync_service->GetDeviceInfoTracker(); + if (tracker != nullptr) { + trackers->push_back(tracker); + } + } + } +}
diff --git a/ios/chrome/browser/ui/commands/ios_command_ids.h b/ios/chrome/browser/ui/commands/ios_command_ids.h index 0614a49..293fa65 100644 --- a/ios/chrome/browser/ui/commands/ios_command_ids.h +++ b/ios/chrome/browser/ui/commands/ios_command_ids.h
@@ -66,7 +66,6 @@ #define IDC_PRELOAD_VOICE_SEARCH 40937 #define IDC_SHOW_BACK_HISTORY 40938 #define IDC_SHOW_FORWARD_HISTORY 40939 -#define IDC_SHOW_PROXY_SETTINGS 40940 #define IDC_CLOSE_SETTINGS_AND_OPEN_NEW_INCOGNITO_TAB 40942 #define IDC_SHOW_ACCOUNTS_SETTINGS 40943 #define IDC_CLOSE_SETTINGS 40944
diff --git a/ios/chrome/ios_chrome.gyp b/ios/chrome/ios_chrome.gyp index 5b09f3a..c117524 100644 --- a/ios/chrome/ios_chrome.gyp +++ b/ios/chrome/ios_chrome.gyp
@@ -58,8 +58,6 @@ '../../components/components.gyp:cookie_config', '../../components/components.gyp:crash_core_browser', '../../components/components.gyp:crash_core_common', - '../../components/components.gyp:data_reduction_proxy_core_browser', - '../../components/components.gyp:data_reduction_proxy_core_common', '../../components/components.gyp:dom_distiller_core', '../../components/components.gyp:dom_distiller_ios', '../../components/components.gyp:favicon_base', @@ -256,12 +254,6 @@ 'browser/crash_report/crash_report_user_application_state.mm', 'browser/crash_report/crash_upload_list.cc', 'browser/crash_report/crash_upload_list.h', - 'browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.h', - 'browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_io_data.mm', - 'browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.cc', - 'browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings.h', - 'browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.cc', - 'browser/data_reduction_proxy/ios_chrome_data_reduction_proxy_settings_factory.h', 'browser/dom_distiller/distiller_viewer.cc', 'browser/dom_distiller/distiller_viewer.h', 'browser/dom_distiller/dom_distiller_service_factory.cc',
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 8efa1cf..cf8b14c 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -447,7 +447,7 @@ ] } -js_compile_bundle("web_bundle_ui") { +js_compile_bundle("web_bundle") { visibility = [ ":js_resources" ] closure_entry_point = "__crWeb.webBundle" @@ -456,37 +456,15 @@ "web_state/js/resources/common.js", "web_state/js/resources/console.js", "web_state/js/resources/core.js", - "web_state/js/resources/core_dynamic_ui.js", "web_state/js/resources/dialog_overrides.js", "web_state/js/resources/message.js", - "web_state/js/resources/message_dynamic_ui.js", - "web_state/js/resources/web_bundle_ui.js", - "web_state/js/resources/window_open_ui.js", - ] -} - -js_compile_bundle("web_bundle_wk") { - visibility = [ ":js_resources" ] - closure_entry_point = "__crWeb.webBundle" - - sources = [ - "web_state/js/resources/base.js", - "web_state/js/resources/common.js", - "web_state/js/resources/console.js", - "web_state/js/resources/core.js", - "web_state/js/resources/core_dynamic_wk.js", - "web_state/js/resources/dialog_overrides.js", - "web_state/js/resources/message.js", - "web_state/js/resources/message_dynamic_wk.js", - "web_state/js/resources/web_bundle_wk.js", - "web_state/js/resources/window_open_wk.js", + "web_state/js/resources/web_bundle.js", ] } js_compile_checked("js_resources") { deps = [ - ":web_bundle_ui", - ":web_bundle_wk", + ":web_bundle", ] sources = [
diff --git a/ios/web/ios_web.gyp b/ios/web/ios_web.gyp index 54ccb70..97c4e9c 100644 --- a/ios/web/ios_web.gyp +++ b/ios/web/ios_web.gyp
@@ -349,8 +349,8 @@ ], }, { - # GN version: //ios/web:web_bundle_ui - 'target_name': 'ios_web_js_bundle_ui', + # GN version: //ios/web:web_bundle + 'target_name': 'ios_web_js_bundle', 'type': 'none', 'variables': { 'closure_entry_point': '__crWeb.webBundle', @@ -359,51 +359,17 @@ 'web_state/js/resources/common.js', 'web_state/js/resources/console.js', 'web_state/js/resources/core.js', - 'web_state/js/resources/core_dynamic_ui.js', 'web_state/js/resources/dialog_overrides.js', 'web_state/js/resources/message.js', - 'web_state/js/resources/message_dynamic_ui.js', - 'web_state/js/resources/web_bundle_ui.js', - 'web_state/js/resources/window_open_ui.js', + 'web_state/js/resources/web_bundle.js', ], }, 'sources': [ - 'web_state/js/resources/web_bundle_ui.js', + 'web_state/js/resources/web_bundle.js', ], 'link_settings': { 'mac_bundle_resources': [ - '<(SHARED_INTERMEDIATE_DIR)/web_bundle_ui.js', - ], - }, - 'includes': [ - 'js_compile_bundle.gypi' - ], - }, - { - # GN version: //ios/web:web_bundle_wk - 'target_name': 'ios_web_js_bundle_wk', - 'type': 'none', - 'variables': { - 'closure_entry_point': '__crWeb.webBundle', - 'js_bundle_files': [ - 'web_state/js/resources/base.js', - 'web_state/js/resources/common.js', - 'web_state/js/resources/console.js', - 'web_state/js/resources/core.js', - 'web_state/js/resources/core_dynamic_wk.js', - 'web_state/js/resources/dialog_overrides.js', - 'web_state/js/resources/message.js', - 'web_state/js/resources/message_dynamic_wk.js', - 'web_state/js/resources/web_bundle_wk.js', - 'web_state/js/resources/window_open_wk.js', - ], - }, - 'sources': [ - 'web_state/js/resources/web_bundle_wk.js', - ], - 'link_settings': { - 'mac_bundle_resources': [ - '<(SHARED_INTERMEDIATE_DIR)/web_bundle_wk.js', + '<(SHARED_INTERMEDIATE_DIR)/web_bundle.js', ], }, 'includes': [ @@ -415,8 +381,7 @@ 'target_name': 'js_resources', 'type': 'none', 'dependencies': [ - 'ios_web_js_bundle_ui', - 'ios_web_js_bundle_wk', + 'ios_web_js_bundle', ], 'sources': [ 'web_state/js/resources/post_request.js',
diff --git a/ios/web/public/web_state/ui/crw_web_delegate.h b/ios/web/public/web_state/ui/crw_web_delegate.h index 5bf73c79..9fc1050a 100644 --- a/ios/web/public/web_state/ui/crw_web_delegate.h +++ b/ios/web/public/web_state/ui/crw_web_delegate.h
@@ -35,26 +35,6 @@ // Callback for -presentSSLError:forSSLStatus:onUrl:recoverable:callback: typedef void (^SSLErrorCallback)(BOOL); -// Interface to perform cross window scripting on CRWWebController. -@protocol CRWWebControllerScripting - -// Loads the HTML into the page. -- (void)loadHTML:(NSString*)html; - -// Loads HTML in the page and presents it as if it was originating from the -// URL itself. Should be used only in specific cases, where the injected html -// is guaranteed to be some derived representation of the original content. -- (void)loadHTMLForCurrentURL:(NSString*)html; - -// Stops loading the page. -- (void)stopLoading; - -// TODO(eugenebut): rename -[CRWWebController close] method to avoid confusion. -// Asks the delegate to be closed. -- (void)orderClose; - -@end - // Methods implemented by the delegate of the CRWWebController. @protocol CRWWebDelegate<NSObject> @@ -234,10 +214,6 @@ // policy is set via -[CRWWebController setPageDialogsOpenPolicy:] method). - (void)webControllerDidSuppressDialog:(CRWWebController*)webController; -// Called to get CRWWebController of a child window by name. -- (id<CRWWebControllerScripting>)webController:(CRWWebController*)webController - scriptingInterfaceForWindowNamed:(NSString*)windowName; - // Called to retrieve the height of any header that is overlaying on top of the // web view. This can be used to implement, for e.g. a toolbar that changes // height dynamically. Returning a non-zero height affects the visible frame
diff --git a/ios/web/test/web_test.h b/ios/web/test/web_test.h index d7a369b..df2ac4f 100644 --- a/ios/web/test/web_test.h +++ b/ios/web/test/web_test.h
@@ -104,13 +104,6 @@ NSString* CreateLoadCheck(); }; -#pragma mark - - -// A test fixtures thats creates a CRWWKWebViewWebController for testing. -// TODO(crbug.com/589563): Remove this typedef, clients should use -// |WebTestWithWebController|. -typedef WebTestWithWebController WebTestWithWKWebViewWebController; - } // namespace web #endif // IOS_WEB_TEST_WEB_TEST_H_
diff --git a/ios/web/web_state/js/crw_js_post_request_loader_unittest.mm b/ios/web/web_state/js/crw_js_post_request_loader_unittest.mm index aa6a4d0..0e4b5455 100644 --- a/ios/web/web_state/js/crw_js_post_request_loader_unittest.mm +++ b/ios/web/web_state/js/crw_js_post_request_loader_unittest.mm
@@ -35,9 +35,13 @@ "};"; // Tests that the POST request is correctly executed through XMLHttpRequest. -TEST_F(CRWJSPOSTRequestLoaderTest, LoadsCorrectHTML) { - CR_TEST_REQUIRES_WK_WEB_VIEW(); - +// TODO(crbug.com/592034): This test is flaky on device. +#if TARGET_IPHONE_SIMULATOR +#define MAYBE_LoadsCorrectHTML LoadsCorrectHTML +#else +#define MAYBE_LoadsCorrectHTML FLAKY_LoadsCorrectHTML +#endif +TEST_F(CRWJSPOSTRequestLoaderTest, MAYBE_LoadsCorrectHTML) { // Set up necessary objects. scoped_nsobject<CRWJSPOSTRequestLoader> loader( [[CRWJSPOSTRequestLoader alloc] init]);
diff --git a/ios/web/web_state/js/page_script_util.mm b/ios/web/web_state/js/page_script_util.mm index 78d1a0bd..fec9fcd 100644 --- a/ios/web/web_state/js/page_script_util.mm +++ b/ios/web/web_state/js/page_script_util.mm
@@ -12,21 +12,6 @@ namespace web { -namespace { -// Returns an autoreleased string containing the JavaScript to be injected into -// the web view as early as possible. Does not include embedder's script. -NSString* GetWebEarlyPageScript(WebViewType web_view_type) { - switch (web_view_type) { - case UI_WEB_VIEW_TYPE: - return GetPageScript(@"web_bundle_ui"); - case WK_WEB_VIEW_TYPE: - return GetPageScript(@"web_bundle_wk"); - } - NOTREACHED(); - return nil; -} -} // namespace - NSString* GetPageScript(NSString* script_file_name) { DCHECK(script_file_name); NSString* path = @@ -58,7 +43,7 @@ // prevents multiple injections into the same page. NSString* kScriptTemplate = @"if (typeof __gCrWeb !== 'object') { %@; %@ }"; return [NSString stringWithFormat:kScriptTemplate, - GetWebEarlyPageScript(web_view_type), + GetPageScript(@"web_bundle"), embedder_page_script]; }
diff --git a/ios/web/web_state/js/resources/core.js b/ios/web/web_state/js/resources/core.js index 862b83e..c2bb6cb 100644 --- a/ios/web/web_state/js/resources/core.js +++ b/ios/web/web_state/js/resources/core.js
@@ -11,18 +11,25 @@ goog.provide('__crWeb.core'); goog.require('__crWeb.common'); -goog.require('__crWeb.coreDynamic'); goog.require('__crWeb.message'); -/** - * The Chrome object is populated in an anonymous object defined at - * initialization to prevent polluting the global namespace. - */ - /* Beginning of anonymous object. */ (function() { __gCrWeb['core'] = {}; + /** + * Handles document load completion tasks. Invoked from + * [WKNavigationDelegate webView:didFinishNavigation:], when document load is + * complete. + */ + __gCrWeb.didFinishNavigation = function() { + // Send the favicons to the browser. + __gCrWeb.sendFaviconsToHost(); + // Add placeholders for plugin content. + if (__gCrWeb.common.updatePluginPlaceholders()) + __gCrWeb.message.invokeOnHost({'command': 'addPluginPlaceholders'}); + } + // JavaScript errors are logged on the main application side. The handler is // added ASAP to catch any errors in startup. Note this does not appear to // work in iOS < 5. @@ -464,8 +471,6 @@ invokeOnHost_({'command': 'window.hashchange'}); }); - __gCrWeb.core_dynamic.addEventListeners(); - // Returns if a frame with |name| is found in |currentWindow|. // Note frame.name is undefined for cross domain frames. var hasFrame_ = function(currentWindow, name) { @@ -580,10 +585,10 @@ * the window-level overrides can be applied as soon as possible. */ __gCrWeb.core.documentInject = function() { - // Perform web view specific operations requiring document.body presence. - // If necessary returns and waits for document to be present. - if (!__gCrWeb.core_dynamic.documentInject()) - return; + // Flush the message queue. + if (__gCrWeb.message) { + __gCrWeb.message.invokeQueues(); + } document.addEventListener('click', function(evt) { var node = getTargetLink_(evt.target); @@ -619,14 +624,6 @@ return; if (isInternaLink_(node)) { - if (evt['defaultPrevented']) - return; - // Internal link. The web view will handle navigation, but register - // the anchor for UIWebView to start the progress indicator ASAP and - // notify web controller as soon as possible of impending navigation. - if (__gCrWeb.core_dynamic.handleInternalClickEvent) { - __gCrWeb.core_dynamic.handleInternalClickEvent(node); - } return; } else { // Resets the external request if it has been canceled, otherwise @@ -661,10 +658,6 @@ addFormEventListeners_(); - // Handle or wait for and handle document load completion, if applicable. - if (__gCrWeb.core_dynamic.handleDocumentLoaded) - __gCrWeb.core_dynamic.handleDocumentLoaded(); - return true; };
diff --git a/ios/web/web_state/js/resources/core_dynamic_ui.js b/ios/web/web_state/js/resources/core_dynamic_ui.js deleted file mode 100644 index dc65cad..0000000 --- a/ios/web/web_state/js/resources/core_dynamic_ui.js +++ /dev/null
@@ -1,151 +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. - -// Scripts that are conceptually part of core.js, but have UIWebView-specific -// details/behaviors. - -goog.provide('__crWeb.coreDynamic'); - -goog.require('__crWeb.common'); -goog.require('__crWeb.message'); - -/** - * Namespace for this module. - */ -__gCrWeb.core_dynamic = {}; - -/* Beginning of anonymous object. */ -(function() { - /** - * Resets common.JSONStringify to a clean copy. This can be called to ensure - * that its copy is not of an override injected earlier by the page. This - * must be called after document.body is present. - */ - var resetJsonStringify_ = function() { - var frame = document.createElement('iframe'); - // crwebnull protocol returns NO immediately to reject the load attempt. - // A new frame is still created with an independent window object. - frame.src = 'crwebnull://'; - document.body.appendChild(frame); - // One some occasions the contentWindow is not available, or the JSON object - // is not available. It is not clear why, but this defense still has value - // when it can be applied. - if (frame.contentWindow && frame.contentWindow.JSON) { - // Refresh original stringify object from new window reference (if - // available) in case the originally retained version was not the native - // version. - __gCrWeb.common.JSONStringify = frame.contentWindow.JSON.stringify; - } - document.body.removeChild(frame); - }; - - /** - * Adds UIWebView specific event listeners. - */ - __gCrWeb.core_dynamic.addEventListeners = function() { - window.addEventListener('unload', function(evt) { - // In the case of a newly-created UIWebView, the URL starts as - // about:blank, the window.unload event fires, and then the URL changes. - // However, at this point the window object is *not* reset. After this, - // when the page changes for any reason the window object *is* reset. - // For this reason, we do not report the window.unload event from the - // default page to the first URL. - // This is sent as an immediate command because if the message arrives - // after the page change has taken effect, false positive security errors - // can occur. - if (!document._defaultPage) - __gCrWeb.message.invokeOnHostImmediate({'command': 'window.unload'}); - }); - }; - - /** - * Applies UIWebView specific document-level overrides. These overrides - * require the document body to be present; therefore the method sets event - * listeners and timers to retry upon document body load if document body is - * not yet present. Returns false if on default page or document is not - * present. - */ - __gCrWeb.core_dynamic.documentInject = function() { - // The default page gets the injections to the window object, but not the - // document object. On the first occasion the page changes (from the default - // about:blank) the window.unload event fires but the window object does not - // actually reset. However by the time the DOMContentLoaded event fires the - // document object will have been reset (to a non-default page). - if (document && document['_defaultPage']) { - window.addEventListener('DOMContentLoaded', __gCrWeb.core.documentInject); - return false; - } - if (!document || !document.body) { - // Either the document or document body is not yet available... retest in - // 1 / 4 of a second. - window.setTimeout(__gCrWeb.core.documentInject, 250); - return false; - } - - // Try to guarantee a clean copy of common.JSONStringify. - resetJsonStringify_(); - - // Flush the message queue and send document.present message, if load has - // not been aborted. - if (!document._cancelled) { - if (__gCrWeb.message) { - __gCrWeb.message.invokeQueues(); - } - __gCrWeb.message.invokeOnHost({'command': 'document.present'}); - } - - // Add event listener for title changes. - var lastSeenTitle = document.title; - document.addEventListener('DOMSubtreeModified', function(evt) { - if (document.title !== lastSeenTitle) { - lastSeenTitle = document.title; - __gCrWeb.message.invokeOnHost({'command': 'document.retitled'}); - } - }); - - return true; - }; - - /** - * Notifies client and handles post-document load tasks when document has - * finished loading. - */ - __gCrWeb.core_dynamic.handleDocumentLoaded = function() { - var invokeOnHost_ = __gCrWeb.message.invokeOnHost; - var loaded_ = function() { - invokeOnHost_({'command': 'document.loaded'}); - // Send the favicons to the browser. - __gCrWeb.sendFaviconsToHost(); - // Add placeholders for plugin content. - if (__gCrWeb.common.updatePluginPlaceholders()) - __gCrWeb.message.invokeOnHost({'command': 'addPluginPlaceholders'}); - }; - - if (document.readyState === 'loaded' || document.readyState === 'complete') - loaded_(); - else - window.addEventListener('load', loaded_); - } - - - /** - * Sends anchor.click message. - */ - __gCrWeb.core_dynamic.handleInternalClickEvent = function(node) { - __gCrWeb.message.invokeOnHost({'command': 'anchor.click', - 'href': node.href}); - } - - /** - * Exits Fullscreen video by calling webkitExitFullScreen on every video - * element. - */ - __gCrWeb['exitFullscreenVideo'] = function() { - var videos = document.getElementsByTagName('video'); - var videosLength = videos.length; - for (var i = 0; i < videosLength; ++i) { - videos[i].webkitExitFullScreen(); - } - }; -}());
diff --git a/ios/web/web_state/js/resources/core_dynamic_wk.js b/ios/web/web_state/js/resources/core_dynamic_wk.js deleted file mode 100644 index 9694da0..0000000 --- a/ios/web/web_state/js/resources/core_dynamic_wk.js +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Scripts that are conceptually part of core.js, but have WKWebView-specific -// details/behaviors. - -goog.provide('__crWeb.coreDynamic'); - -/** - * Namespace for this module. - */ -__gCrWeb.core_dynamic = {}; - -/* Beginning of anonymous object. */ -(function() { - /** - * Adds WKWebView specific event listeners. - */ - __gCrWeb.core_dynamic.addEventListeners = function() { - // So far there are no WKWebView specific event listeners. - }; - - /** - * Applies WKWebView specific document-level overrides. Script injection for - * WKWebView always happens after the document is presented; therefore, there - * is no need to provide for invoking documentInject at a later time. - */ - __gCrWeb.core_dynamic.documentInject = function() { - // Flush the message queue. - if (__gCrWeb.message) { - __gCrWeb.message.invokeQueues(); - } - return true; - }; - - /** - * Handles document load completion tasks. Invoked from - * [WKNavigationDelegate webView:didFinishNavigation:], when document load is - * complete. - */ - __gCrWeb.didFinishNavigation = function() { - // Send the favicons to the browser. - __gCrWeb.sendFaviconsToHost(); - // Add placeholders for plugin content. - if (__gCrWeb.common.updatePluginPlaceholders()) - __gCrWeb.message.invokeOnHost({'command': 'addPluginPlaceholders'}); - } -}());
diff --git a/ios/web/web_state/js/resources/dialog_overrides.js b/ios/web/web_state/js/resources/dialog_overrides.js index 0f264c9..cd9d984 100644 --- a/ios/web/web_state/js/resources/dialog_overrides.js +++ b/ios/web/web_state/js/resources/dialog_overrides.js
@@ -5,9 +5,6 @@ goog.provide('__crWeb.dialogOverrides'); goog.require('__crWeb.core'); -// window.open override for dialog suppression must be performed after the rest -// of window.open overrides which are done in __crWeb.windowOpen module. -goog.require('__crWeb.windowOpen'); // Namespace for this module. __gCrWeb.dialogOverrides = {};
diff --git a/ios/web/web_state/js/resources/message.js b/ios/web/web_state/js/resources/message.js index c9fa557..e57133a 100644 --- a/ios/web/web_state/js/resources/message.js +++ b/ios/web/web_state/js/resources/message.js
@@ -7,7 +7,6 @@ goog.provide('__crWeb.message'); goog.require('__crWeb.common'); -goog.require('__crWeb.messageDynamic'); /** * Namespace for this module. @@ -111,7 +110,16 @@ var originalObjectToJSON = Object.prototype.toJSON; if (originalObjectToJSON) delete Object.prototype.toJSON; - __gCrWeb.message_dynamic.sendQueue(queueObject); + + queueObject.queue.forEach(function(command) { + var stringifiedMessage = __gCrWeb.common.JSONStringify({ + "crwCommand": command, + "crwWindowId": __gCrWeb.windowId + }); + window.webkit.messageHandlers[queueObject.scheme].postMessage( + stringifiedMessage); + }); + queueObject.reset(); if (originalObjectToJSON) { // Restore Object.prototype.toJSON to prevent from breaking any
diff --git a/ios/web/web_state/js/resources/message_dynamic_ui.js b/ios/web/web_state/js/resources/message_dynamic_ui.js deleted file mode 100644 index 4209b622..0000000 --- a/ios/web/web_state/js/resources/message_dynamic_ui.js +++ /dev/null
@@ -1,62 +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. - -// Scripts for the message handler for use with UIWebView. - -goog.provide('__crWeb.messageDynamic'); - -goog.require('__crWeb.common'); - -/** - * Namespace for this module. - */ -__gCrWeb.message_dynamic = {}; - -/* Beginning of anonymous object. */ -(function() { - /** - * Returns true if sending the message queue should be delayed. - */ - function pageRequiresDelayedSend() { - // The Apple mobile password recovery page does not interact well with - // iframes, so on pages with the 'iforgot.apple.com' domain, delay sending - // the queue. - return window.location.origin === "https://iforgot.apple.com"; - } - - /** - * Sends queued commands to the Objective-C side. - * @param {Object} queueObject Queue object containing messages to send. - */ - __gCrWeb.message_dynamic.sendQueue = function(queueObject) { - var send = function() { - // The technique requires the document to be present. If it is not, the - // messages will be sent once the document object is created. - if (!document || !document.body) { - // This happens in rare occasions early in the page cycle. It is - // possible to create a body element indirectly here, but it has side - // effects such as blocking page redirection. The safest solution is to - // try again in 1/10th of a second. - window.setTimeout(__gCrWeb.message.invokeQueues, 100); - return; - } - - var frame = document.createElement('iframe'); - frame.style.display = 'none'; - frame.src = queueObject.scheme + '://' + __gCrWeb.windowId + '#' + - encodeURIComponent(__gCrWeb.common.JSONStringify(queueObject.queue)); - queueObject.reset(); - document.body.appendChild(frame); - document.body.removeChild(frame); - }; - - // Some pages do not interact well with iframes. On those pages, delay - // sending the queue. - if (pageRequiresDelayedSend()) { - window.requestAnimationFrame(send); - } else { - send(); - } - }; -}());
diff --git a/ios/web/web_state/js/resources/message_dynamic_wk.js b/ios/web/web_state/js/resources/message_dynamic_wk.js deleted file mode 100644 index 9b6fc469..0000000 --- a/ios/web/web_state/js/resources/message_dynamic_wk.js +++ /dev/null
@@ -1,31 +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. - -// Scripts for the message handler for use with WKWebView. - -goog.provide('__crWeb.messageDynamic'); - -/** - * Namespace for this module. - */ -__gCrWeb.message_dynamic = {}; - -/* Beginning of anonymous object. */ -(function() { - /** - * Sends queued commands to the Objective-C side. - * @param {Object} queueObject Queue object containing messages to send. - */ - __gCrWeb.message_dynamic.sendQueue = function(queueObject) { - queueObject.queue.forEach(function(command) { - var stringifiedMessage = __gCrWeb.common.JSONStringify({ - "crwCommand": command, - "crwWindowId": __gCrWeb.windowId - }); - window.webkit.messageHandlers[queueObject.scheme].postMessage( - stringifiedMessage); - }); - queueObject.reset(); - }; -}());
diff --git a/ios/web/web_state/js/resources/web_bundle_wk.js b/ios/web/web_state/js/resources/web_bundle.js similarity index 100% rename from ios/web/web_state/js/resources/web_bundle_wk.js rename to ios/web/web_state/js/resources/web_bundle.js
diff --git a/ios/web/web_state/js/resources/web_bundle_ui.js b/ios/web/web_state/js/resources/web_bundle_ui.js deleted file mode 100644 index 821ab69d..0000000 --- a/ios/web/web_state/js/resources/web_bundle_ui.js +++ /dev/null
@@ -1,11 +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. - -// Set of scripts required by web layer backed up by UIWebView. -goog.provide('__crWeb.webBundle'); - -goog.require('__crWeb.console'); -goog.require('__crWeb.core'); -goog.require('__crWeb.dialogOverrides'); -goog.require('__crWeb.windowOpen');
diff --git a/ios/web/web_state/js/resources/window_open_ui.js b/ios/web/web_state/js/resources/window_open_ui.js deleted file mode 100644 index 7eb89cc..0000000 --- a/ios/web/web_state/js/resources/window_open_ui.js +++ /dev/null
@@ -1,247 +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. - -// Scripts that are conceptually part of core.js, but have UIWebView-specific -// details/behaviors. - -goog.provide('__crWeb.windowOpen'); - -goog.require('__crWeb.core'); - -// Namespace for this module. -__gCrWeb.windowOpen = {}; - -// Beginning of anonymous object. -(function() { - // Preserve a reference to the original window.open method. - __gCrWeb['originalWindowOpen'] = window.open; - - // Object used to keep track of all windows opened from this window. - var openedWindows = {}; - - /** - * Checks if a child window exists with the given name and if so, sets its - * closed property to true and removes it from |openedWindows|. - * @param {String} windowName The name of the window to mark as closed. - */ - __gCrWeb['windowClosed'] = function(windowName) { - if (openedWindows.hasOwnProperty(windowName)) { - openedWindows[windowName].closed = true; - delete openedWindows[windowName]; - } - }; - - function invokeOnHost_(command) { - __gCrWeb.message.invokeOnHost(command); - }; - - var invokeNotImplementedOnHost_ = function(methodName) { - invokeOnHost_({'command': 'window.error', - 'message': methodName + ' is not implemented'}); - }; - - // Define Object watch/unwatch functions to detect assignments to - // certain object properties. Handles defineProperty case only because - // this code runs in UIWebView (i.e. Safari). - var objectWatch = function(obj, prop, handler) { - var val = obj[prop]; - if (delete obj[prop]) { - Object['defineProperty'](obj, prop, { - 'get': function() { - return val; - }, - 'set': function(newVal) { - return val = handler.call(obj, prop, val, newVal); - } - }); - } - }; - - /** - * Creates and returns a window proxy used to represent the window object and - * intercept calls made on it. - * @param {String} target The name of the window. - * @return {Object} A window proxy object for intercepting window methods. - * @private - */ - var createWindowProxy_ = function(target) { - // Create return window object. - // 'name' is always the original supplied name. - var windowProxy = {name: target}; - - // Define window object methods. - windowProxy.alert = function() { - invokeNotImplementedOnHost_('windowProxy.alert'); - }; - - windowProxy.blur = function() { - invokeNotImplementedOnHost_('windowProxy.blur'); - }; - - windowProxy.clearInterval = function() { - invokeNotImplementedOnHost_('windowProxy.clearInterval'); - }; - - windowProxy.clearTimeout = function() { - invokeNotImplementedOnHost_('windowProxy.clearTimeout'); - }; - - windowProxy.close = function() { - invokeOnHost_({'command': 'window.close', - 'target': target}); - }; - - windowProxy.confirm = function() { - invokeNotImplementedOnHost_('windowProxy.confirm'); - }; - - windowProxy.createPopup = function() { - invokeNotImplementedOnHost_('windowProxy.createPopup'); - }; - - windowProxy.focus = function() { - // Noop as the opened window always gets focus. - }; - - windowProxy.moveBy = function() { - invokeNotImplementedOnHost_('windowProxy.moveBy'); - }; - - windowProxy.moveTo = function() { - invokeNotImplementedOnHost_('windowProxy.moveTo'); - }; - - windowProxy.stop = function() { - invokeOnHost_({'command': 'window.stop', - 'target': target}); - }; - - windowProxy.open = function() { - invokeNotImplementedOnHost_('windowProxy.open'); - }; - - windowProxy.print = function() { - invokeNotImplementedOnHost_('windowProxy.print'); - }; - - windowProxy.prompt = function() { - invokeNotImplementedOnHost_('windowProxy.prompt'); - }; - - windowProxy.resizeBy = function() { - invokeNotImplementedOnHost_('windowProxy.resizeBy'); - }; - - windowProxy.resizeTo = function() { - invokeNotImplementedOnHost_('windowProxy.resizeTo'); - }; - - windowProxy.scroll = function() { - invokeNotImplementedOnHost_('windowProxy.scroll'); - }; - - windowProxy.scrollBy = function() { - invokeNotImplementedOnHost_('windowProxy.scrollBy'); - }; - - windowProxy.scrollTo = function() { - invokeNotImplementedOnHost_('windowProxy.scrollTo'); - }; - - windowProxy.setInterval = function() { - invokeNotImplementedOnHost_('windowProxy.setInterval'); - }; - - windowProxy.setTimeout = function() { - invokeNotImplementedOnHost_('windowProxy.setTimeout'); - }; - - // Define window object properties. - // The current window. - windowProxy.self = windowProxy; - // The topmost browser window. - windowProxy.top = windowProxy; - - // Provide proxy document which supplies one method, document.write(). - windowProxy.document = {}; - windowProxy.document.title = ''; - windowProxy.document.write = function(html) { - invokeOnHost_({'command': 'window.document.write', - 'html': html, - 'target': target}); - }; - - windowProxy.document.open = function() { - // The open() method should open an output stream to collect the output - // from any document.write() or document.writeln() methods. - invokeNotImplementedOnHost_('windowProxy.document.open'); - }; - - windowProxy.document.close = function() { - // The close() method should close the output stream previously opened - // with the document.open() method, and displays the collected data in - // this process. - invokeNotImplementedOnHost_('windowProxy.document.close'); - }; - - windowProxy.location = {}; - windowProxy.location.assign = function(url) { - windowProxy.location = url; - }; - // Watch assignments to window.location and window.location.href. - // Invoke equivalent method in ObjC code. - var onWindowProxyLocationChange = function(prop, oldVal, newVal) { - invokeOnHost_({'command': 'window.location', - 'value': __gCrWeb['getFullyQualifiedURL'](newVal), - 'target': target}); - return newVal; - }; - objectWatch(windowProxy, 'location', onWindowProxyLocationChange); - objectWatch(windowProxy.location, 'href', onWindowProxyLocationChange); - windowProxy.closed = false; - - return windowProxy; - }; - - // Intercept window.open calls. - window.open = function(url, target, features) { - if (target == '_parent' || target == '_self' || target == '_top') { - return __gCrWeb['originalWindowOpen'].call(window, url, target, features); - } - - // Because of the difficulty of returning data from JS->ObjC calls, in the - // event of a blank window name the JS side chooses a pseudo-GUID to - // use as the window name which is passed to ObjC and mapped to the real - // Tab there. - var isTargetBlank = (typeof target == 'undefined' || target == '_blank' || - target == '' || target == null); - if (isTargetBlank) { - target = '' + Date.now() + '-' + Math.random(); - } - - if (typeof(url) == 'undefined') { - // W3C recommended behavior. - url = 'about:blank'; - } - - invokeOnHost_({ - 'command': 'window.open', - 'target': target, - 'url': url, - 'referrerPolicy': __gCrWeb.getPageReferrerPolicy() - }); - - // Create a new |windowProxy| if none already exists with |target| as its - // name. - var windowProxy; - if (openedWindows.hasOwnProperty(target)) { - windowProxy = openedWindows[target]; - } else { - windowProxy = createWindowProxy_(target); - openedWindows[target] = windowProxy; - } - return windowProxy; - }; - -}()); // End of anonymous object
diff --git a/ios/web/web_state/js/resources/window_open_wk.js b/ios/web/web_state/js/resources/window_open_wk.js deleted file mode 100644 index 7ff3420..0000000 --- a/ios/web/web_state/js/resources/window_open_wk.js +++ /dev/null
@@ -1,9 +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. - -goog.provide('__crWeb.windowOpen'); - -// WKWebView natively supports window.open so there is no need to install -// JavaScript-based fix. This file is required by __crWeb.dialogOverrides -// module to support UIWebView.
diff --git a/ios/web/web_state/ui/crw_web_controller.h b/ios/web/web_state/ui/crw_web_controller.h index 34ea9ee4..f4eb810 100644 --- a/ios/web/web_state/ui/crw_web_controller.h +++ b/ios/web/web_state/ui/crw_web_controller.h
@@ -79,7 +79,6 @@ @interface CRWWebController : NSObject<CRWJSInjectionEvaluator, CRWRequestTrackerDelegate, CRWTouchTrackingDelegate, - CRWWebControllerScripting, UIGestureRecognizerDelegate> // Whether or not a UIWebView is allowed to exist in this CRWWebController. @@ -184,12 +183,19 @@ // Loads the URL indicated by current session state. - (void)loadCurrentURL; -// Loads the HTML into the page. -- (void)loadHTML:(NSString*)html; + // Loads HTML in the page and presents it as if it was originating from an // application specific URL. - (void)loadHTML:(NSString*)HTML forAppSpecificURL:(const GURL&)URL; +// Loads HTML in the page and presents it as if it was originating from the +// URL itself. Should be used only in specific cases, where the injected html +// is guaranteed to be some derived representation of the original content. +- (void)loadHTMLForCurrentURL:(NSString*)HTML; + +// Stops loading the page. +- (void)stopLoading; + // Causes the page to start loading immediately if there is a pending load; // normally if the web view has been paged out for memory reasons, loads are // started lazily the next time the view is displayed. This can be called to
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index cf38e96..4cd999c 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -3741,16 +3741,6 @@ } } -#pragma mark CRWWebControllerScripting Methods - -- (void)loadHTML:(NSString*)html { - [self loadHTML:html forURL:GURL(url::kAboutBlankURL)]; -} - -- (void)loadHTMLForCurrentURL:(NSString*)html { - [self loadHTML:html forURL:self.currentURL]; -} - - (void)loadHTML:(NSString*)html forURL:(const GURL&)url { // Remove the transient content view. [self clearTransientContentView]; @@ -3766,6 +3756,10 @@ [self loadHTML:HTML forURL:URL]; } +- (void)loadHTMLForCurrentURL:(NSString*)HTML { + [self loadHTML:HTML forURL:self.currentURL]; +} + - (void)stopLoading { web::RecordAction(UserMetricsAction("Stop")); // Discard the pending and transient entried before notifying the tab model @@ -3780,12 +3774,6 @@ } } -- (void)orderClose { - if (self.sessionController.openedByDOM) { - [_delegate webPageOrderedClose]; - } -} - #pragma mark - #pragma mark Testing-Only Methods
diff --git a/ios/web/web_state/ui/crw_web_controller_unittest.mm b/ios/web/web_state/ui/crw_web_controller_unittest.mm index 0c67d13c..92b8bed0 100644 --- a/ios/web/web_state/ui/crw_web_controller_unittest.mm +++ b/ios/web/web_state/ui/crw_web_controller_unittest.mm
@@ -262,12 +262,6 @@ referrer:web::Referrer() transition:ui::PAGE_TRANSITION_TYPED rendererInitiated:NO]; - // Set up child CRWWebController. - mockChildWebController_.reset([[OCMockObject - mockForProtocol:@protocol(CRWWebControllerScripting)] retain]); - [[[mockDelegate_ stub] andReturn:mockChildWebController_.get()] - webController:webController_ - scriptingInterfaceForWindowNamed:@"http://www.google.com/#newtab"]; } void TearDown() override {
diff --git a/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm b/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm index b209e197..d5f2340c8 100644 --- a/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm +++ b/ios/web/web_state/ui/crw_wk_web_view_web_controller.mm
@@ -2005,7 +2005,9 @@ } - (void)webViewDidClose:(WKWebView*)webView { - [self orderClose]; + if (self.sessionController.openedByDOM) { + [self.delegate webPageOrderedClose]; + } } - (void)webView:(WKWebView*)webView
diff --git a/ipc/ipc_message_macros.h b/ipc/ipc_message_macros.h index a573265b..6126b59 100644 --- a/ipc/ipc_message_macros.h +++ b/ipc/ipc_message_macros.h
@@ -402,8 +402,7 @@ } // This corresponds to an enum value from IPCMessageStart. -#define IPC_MESSAGE_CLASS(message) \ - IPC_MESSAGE_ID_CLASS(message.type()) +#define IPC_MESSAGE_CLASS(message) IPC_MESSAGE_ID_CLASS((message).type()) // Deprecated legacy macro names. // TODO(mdempsky): Replace uses with generic names.
diff --git a/ipc/ipc_message_start.h b/ipc/ipc_message_start.h index 6ceb4dc..17c704b 100644 --- a/ipc/ipc_message_start.h +++ b/ipc/ipc_message_start.h
@@ -11,6 +11,7 @@ enum IPCMessageStart { AutomationMsgStart = 0, FrameMsgStart, + PageMsgStart, ViewMsgStart, InputMsgStart, PluginMsgStart,
diff --git a/mash/browser_driver/browser_driver_application_delegate.cc b/mash/browser_driver/browser_driver_application_delegate.cc index e5ea59a..1e14d16 100644 --- a/mash/browser_driver/browser_driver_application_delegate.cc +++ b/mash/browser_driver/browser_driver_application_delegate.cc
@@ -52,8 +52,8 @@ void BrowserDriverApplicationDelegate::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { connector_ = connector; AddAccelerators(); }
diff --git a/mash/browser_driver/browser_driver_application_delegate.h b/mash/browser_driver/browser_driver_application_delegate.h index cbe63cf9..03d67d38 100644 --- a/mash/browser_driver/browser_driver_application_delegate.h +++ b/mash/browser_driver/browser_driver_application_delegate.h
@@ -28,7 +28,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // mus::mojom::AcceleratorHandler:
diff --git a/mash/example/views_examples/views_examples_application_delegate.cc b/mash/example/views_examples/views_examples_application_delegate.cc index 1c4c2001..b3b87e9 100644 --- a/mash/example/views_examples/views_examples_application_delegate.cc +++ b/mash/example/views_examples/views_examples_application_delegate.cc
@@ -18,8 +18,8 @@ void ViewsExamplesApplicationDelegate::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak"));
diff --git a/mash/example/views_examples/views_examples_application_delegate.h b/mash/example/views_examples/views_examples_application_delegate.h index e7d9eec0..cb1ab50c 100644 --- a/mash/example/views_examples/views_examples_application_delegate.h +++ b/mash/example/views_examples/views_examples_application_delegate.h
@@ -22,7 +22,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; mojo::TracingImpl tracing_;
diff --git a/mash/example/window_type_launcher/window_type_launcher.cc b/mash/example/window_type_launcher/window_type_launcher.cc index d4fdc69..141bb3f 100644 --- a/mash/example/window_type_launcher/window_type_launcher.cc +++ b/mash/example/window_type_launcher/window_type_launcher.cc
@@ -357,7 +357,8 @@ void WindowTypeLauncher::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, + uint32_t id) { aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector);
diff --git a/mash/example/window_type_launcher/window_type_launcher.h b/mash/example/window_type_launcher/window_type_launcher.h index b162db7..c5bad8a 100644 --- a/mash/example/window_type_launcher/window_type_launcher.h +++ b/mash/example/window_type_launcher/window_type_launcher.h
@@ -21,7 +21,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; scoped_ptr<views::AuraInit> aura_init_;
diff --git a/mash/init/init.cc b/mash/init/init.cc index f8e1d6b..c7197dd 100644 --- a/mash/init/init.cc +++ b/mash/init/init.cc
@@ -16,14 +16,14 @@ Init::~Init() {} void Init::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, uint32_t id) { connector_ = connector; mus_connection_ = connector_->Connect("mojo:mus"); StartWindowManager(); StartLogin(); } -void Init::LoginAs(uint32_t user_id) { +void Init::LoginAs(const mojo::String& user_id) { connections_["mojo:mash_login"].reset(); connections_["mojo:desktop_wm"].reset(); mojo::Connector::ConnectParams params("mojo:mash_shell"); @@ -37,7 +37,7 @@ void Init::StartWindowManager() { mojo::Connector::ConnectParams params("mojo:desktop_wm"); - params.set_user_id(2); + params.set_user_id("2"); StartRestartableService( ¶ms, base::Bind(&Init::StartWindowManager, base::Unretained(this))); @@ -45,7 +45,7 @@ void Init::StartLogin() { mojo::Connector::ConnectParams params("mojo:mash_login"); - params.set_user_id(2); + params.set_user_id("2"); StartRestartableService( ¶ms, base::Bind(&Init::StartLogin, base::Unretained(this))); @@ -58,8 +58,7 @@ scoped_ptr<mojo::Connection> connection = connector_->Connect(params); // Note: |connection| may be null if we've lost our connection to the shell. if (connection) { - connection->SetRemoteInterfaceProviderConnectionErrorHandler( - restart_callback); + connection->SetConnectionLostClosure(restart_callback); connection->AddInterface<mojom::Login>(this); connections_[params->name()] = std::move(connection); }
diff --git a/mash/init/init.h b/mash/init/init.h index 10a8a0e..812967a 100644 --- a/mash/init/init.h +++ b/mash/init/init.h
@@ -32,10 +32,10 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; // mojom::Login: - void LoginAs(uint32_t user_id) override; + void LoginAs(const mojo::String& user_id) override; // mojo::InterfaceFactory<mojom::Login>: void Create(mojo::Connection* connection,
diff --git a/mash/init/public/interfaces/login.mojom b/mash/init/public/interfaces/login.mojom index 3ea6f10c..8c99e47 100644 --- a/mash/init/public/interfaces/login.mojom +++ b/mash/init/public/interfaces/login.mojom
@@ -5,6 +5,6 @@ module mash.init.mojom; interface Login { - LoginAs(uint32 user_id); + LoginAs(string user_id); };
diff --git a/mash/login/login.cc b/mash/login/login.cc index e301b3f..2e26b4a 100644 --- a/mash/login/login.cc +++ b/mash/login/login.cc
@@ -72,9 +72,9 @@ // Login... mojo::Connector::ConnectParams params("mojo:mash_shell"); if (sender == login_button_1_) { - login_->login()->LoginAs(3); + login_->login()->LoginAs("3"); } else if (sender == login_button_2_) { - login_->login()->LoginAs(4); + login_->login()->LoginAs("4"); } else { NOTREACHED(); } @@ -94,7 +94,7 @@ Login::~Login() {} void Login::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, uint32_t id) { tracing_.Initialize(connector, url); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak"));
diff --git a/mash/login/login.h b/mash/login/login.h index 2a70b1ab..53fcbf6 100644 --- a/mash/login/login.h +++ b/mash/login/login.h
@@ -30,7 +30,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; mojo::TracingImpl tracing_;
diff --git a/mash/quick_launch/quick_launch_application.cc b/mash/quick_launch/quick_launch_application.cc index d378d9e..d00baf3 100644 --- a/mash/quick_launch/quick_launch_application.cc +++ b/mash/quick_launch/quick_launch_application.cc
@@ -90,8 +90,8 @@ void QuickLaunchApplication::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak"));
diff --git a/mash/quick_launch/quick_launch_application.h b/mash/quick_launch/quick_launch_application.h index c95f2a2c..8fbd6508 100644 --- a/mash/quick_launch/quick_launch_application.h +++ b/mash/quick_launch/quick_launch_application.h
@@ -26,8 +26,8 @@ // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) override; + const std::string& user_id, + uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; mojo::TracingImpl tracing_;
diff --git a/mash/screenlock/screenlock.cc b/mash/screenlock/screenlock.cc index e3bd2292..42f2b04 100644 --- a/mash/screenlock/screenlock.cc +++ b/mash/screenlock/screenlock.cc
@@ -76,7 +76,7 @@ Screenlock::~Screenlock() {} void Screenlock::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, uint32_t id) { tracing_.Initialize(connector, url); mash::shell::mojom::ShellPtr mash_shell;
diff --git a/mash/screenlock/screenlock.h b/mash/screenlock/screenlock.h index e87995f8..e6c0611 100644 --- a/mash/screenlock/screenlock.h +++ b/mash/screenlock/screenlock.h
@@ -30,7 +30,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; // mash::shell::mojom::ScreenlockStateListener: void ScreenlockStateChanged(bool locked) override;
diff --git a/mash/shell/shell_application_delegate.cc b/mash/shell/shell_application_delegate.cc index c46f0e26..ff472e79 100644 --- a/mash/shell/shell_application_delegate.cc +++ b/mash/shell/shell_application_delegate.cc
@@ -19,8 +19,8 @@ void ShellApplicationDelegate::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { connector_ = connector; StartBrowserDriver(); StartWindowManager(); @@ -114,8 +114,7 @@ scoped_ptr<mojo::Connection> connection = connector_->Connect(url); // Note: |connection| may be null if we've lost our connection to the shell. if (connection) { - connection->SetRemoteInterfaceProviderConnectionErrorHandler( - restart_callback); + connection->SetConnectionLostClosure(restart_callback); connection->AddInterface<mojom::Shell>(this); connections_[url] = std::move(connection); }
diff --git a/mash/shell/shell_application_delegate.h b/mash/shell/shell_application_delegate.h index a429f34a..99b24eda 100644 --- a/mash/shell/shell_application_delegate.h +++ b/mash/shell/shell_application_delegate.h
@@ -34,7 +34,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // mash::shell::mojom::Shell:
diff --git a/mash/task_viewer/task_viewer.cc b/mash/task_viewer/task_viewer.cc index 15176d73..e3af3da 100644 --- a/mash/task_viewer/task_viewer.cc +++ b/mash/task_viewer/task_viewer.cc
@@ -17,7 +17,7 @@ #include "mojo/services/package_manager/public/interfaces/catalog.mojom.h" #include "mojo/shell/public/cpp/connection.h" #include "mojo/shell/public/cpp/connector.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/shell.mojom.h" #include "ui/base/models/table_model.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button.h" @@ -260,18 +260,19 @@ void TaskViewer::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) { + const std::string& user_id, + uint32_t id) { tracing_.Initialize(connector, url); aura_init_.reset(new views::AuraInit(connector, "views_mus_resources.pak")); views::WindowManagerConnection::Create(connector); - mojo::shell::mojom::ApplicationManagerPtr application_manager; - connector->ConnectToInterface("mojo:shell", &application_manager); + mojo::shell::mojom::ShellPtr shell; + connector->ConnectToInterface("mojo:shell", &shell); mojo::shell::mojom::InstanceListenerPtr listener; mojo::shell::mojom::InstanceListenerRequest request = GetProxy(&listener); - application_manager->AddInstanceListener(std::move(listener)); + shell->AddInstanceListener(std::move(listener)); package_manager::mojom::CatalogPtr catalog; connector->ConnectToInterface("mojo:package_manager", &catalog);
diff --git a/mash/task_viewer/task_viewer.h b/mash/task_viewer/task_viewer.h index 5de6028..0a696cd 100644 --- a/mash/task_viewer/task_viewer.h +++ b/mash/task_viewer/task_viewer.h
@@ -28,7 +28,7 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; mojo::TracingImpl tracing_; scoped_ptr<views::AuraInit> aura_init_;
diff --git a/mash/wm/BUILD.gn b/mash/wm/BUILD.gn index bc62208..935186ca 100644 --- a/mash/wm/BUILD.gn +++ b/mash/wm/BUILD.gn
@@ -70,7 +70,7 @@ deps = [ "//base", - "//components/mus/common", + "//components/mus/common:mus_common", "//components/mus/public/cpp", "//components/mus/public/interfaces", "//mash/shell/public/interfaces",
diff --git a/mash/wm/window_manager_application.cc b/mash/wm/window_manager_application.cc index 8a60bb0..6511c94 100644 --- a/mash/wm/window_manager_application.cc +++ b/mash/wm/window_manager_application.cc
@@ -105,8 +105,8 @@ void WindowManagerApplication::Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) { + const std::string& user_id, + uint32_t id) { connector_ = connector; tracing_.Initialize(connector, url);
diff --git a/mash/wm/window_manager_application.h b/mash/wm/window_manager_application.h index b10c1e4..0eedaab 100644 --- a/mash/wm/window_manager_application.h +++ b/mash/wm/window_manager_application.h
@@ -84,7 +84,7 @@ // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(mojo::Connection* connection) override; // InterfaceFactory<mash::wm::mojom::UserWindowController>:
diff --git a/media/BUILD.gn b/media/BUILD.gn index 0c2674d0..01d09d1 100644 --- a/media/BUILD.gn +++ b/media/BUILD.gn
@@ -163,6 +163,8 @@ "filters/opus_audio_decoder.h", "filters/opus_constants.cc", "filters/opus_constants.h", + "filters/pipeline_controller.cc", + "filters/pipeline_controller.h", "filters/source_buffer_range.cc", "filters/source_buffer_range.h", "filters/source_buffer_stream.cc", @@ -554,6 +556,7 @@ "filters/h264_parser_unittest.cc", "filters/ivf_parser_unittest.cc", "filters/jpeg_parser_unittest.cc", + "filters/pipeline_controller_unittest.cc", "filters/source_buffer_stream_unittest.cc", "filters/video_cadence_estimator_unittest.cc", "filters/video_decoder_selector_unittest.cc",
diff --git a/media/audio/mac/audio_low_latency_input_mac.cc b/media/audio/mac/audio_low_latency_input_mac.cc index 131ff72..1aa4ae4 100644 --- a/media/audio/mac/audio_low_latency_input_mac.cc +++ b/media/audio/mac/audio_low_latency_input_mac.cc
@@ -560,6 +560,16 @@ // selected set of the |device_property_changes_map_| map. Add UMA stats // if valuable data is found. AddDevicePropertyChangesToUMA(false); + // Log whether call to Start() was deferred or not. To be compared with + // Media.Audio.InputStartWasDeferredMac which logs the same value but only + // when input audio fails to start. + UMA_HISTOGRAM_BOOLEAN("Media.Audio.InputStartWasDeferredAudioWorkedMac", + start_was_deferred_); + // Log if a change of I/O buffer size was required. To be compared with + // Media.Audio.InputBufferSizeWasChangedMac which logs the same value but + // only when input audio fails to start. + UMA_HISTOGRAM_BOOLEAN("Media.Audio.InputBufferSizeWasChangedAudioWorkedMac", + buffer_size_was_changed_); // TODO(henrika): possibly add more values here... } // Inform the audio manager that we have been closed. This will cause our
diff --git a/media/base/android/audio_decoder_job.cc b/media/base/android/audio_decoder_job.cc index dd1fa53..f0baca4 100644 --- a/media/base/android/audio_decoder_job.cc +++ b/media/base/android/audio_decoder_job.cc
@@ -105,9 +105,16 @@ render_output = render_output && (size != 0u); bool is_audio_underrun = false; if (render_output) { - int64_t head_position = + bool postpone = false; + int64_t head_position; + MediaCodecStatus status = (static_cast<AudioCodecBridge*>(media_codec_bridge_.get())) - ->PlayOutputBuffer(output_buffer_index, size, offset); + ->PlayOutputBuffer(output_buffer_index, size, offset, postpone, + &head_position); + // TODO(timav,watk): This CHECK maintains the behavior of this call before + // we started catching CodecException and returning it as MEDIA_CODEC_ERROR. + // It needs to be handled some other way. http://crbug.com/585978 + CHECK_EQ(status, MEDIA_CODEC_OK); base::TimeTicks current_time = base::TimeTicks::Now(); @@ -191,7 +198,12 @@ DCHECK(media_codec_bridge_); int old_sampling_rate = output_sampling_rate_; - output_sampling_rate_ = media_codec_bridge_->GetOutputSamplingRate(); + MediaCodecStatus status = + media_codec_bridge_->GetOutputSamplingRate(&output_sampling_rate_); + // TODO(timav,watk): This CHECK maintains the behavior of this call before + // we started catching CodecException and returning it as MEDIA_CODEC_ERROR. + // It needs to be handled some other way. http://crbug.com/585978 + CHECK_EQ(status, MEDIA_CODEC_OK); if (output_sampling_rate_ != old_sampling_rate) ResetTimestampHelper(); }
diff --git a/media/base/android/audio_media_codec_decoder.cc b/media/base/android/audio_media_codec_decoder.cc index e148de4..5654e7ca 100644 --- a/media/base/android/audio_media_codec_decoder.cc +++ b/media/base/android/audio_media_codec_decoder.cc
@@ -175,8 +175,9 @@ DCHECK(media_codec_bridge_); int old_sampling_rate = output_sampling_rate_; - output_sampling_rate_ = media_codec_bridge_->GetOutputSamplingRate(); - if (output_sampling_rate_ != old_sampling_rate) + MediaCodecStatus status = + media_codec_bridge_->GetOutputSamplingRate(&output_sampling_rate_); + if (status != MEDIA_CODEC_OK || output_sampling_rate_ != old_sampling_rate) ResetTimestampHelper(); } @@ -201,8 +202,13 @@ const bool postpone = (render_mode == kRenderAfterPreroll); - int64_t head_position = - audio_codec->PlayOutputBuffer(buffer_index, size, offset, postpone); + int64_t head_position; + MediaCodecStatus status = audio_codec->PlayOutputBuffer( + buffer_index, size, offset, postpone, &head_position); + // TODO(timav,watk): This CHECK maintains the behavior of this call before + // we started catching CodecException and returning it as MEDIA_CODEC_ERROR. + // It needs to be handled some other way. http://crbug.com/585978 + CHECK_EQ(status, MEDIA_CODEC_OK); base::TimeTicks current_time = base::TimeTicks::Now();
diff --git a/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java b/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java index 8af3111..daf1234 100644 --- a/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java +++ b/media/base/android/java/src/org/chromium/media/MediaCodecBridge.java
@@ -143,6 +143,48 @@ } } + /** A wrapper around a MediaFormat. */ + @MainDex + private static class GetOutputFormatResult { + private final int mStatus; + // May be null if mStatus is not MEDIA_CODEC_OK. + private final MediaFormat mFormat; + + private GetOutputFormatResult(int status, MediaFormat format) { + mStatus = status; + mFormat = format; + } + + private boolean formatHasCropValues() { + return mFormat.containsKey(KEY_CROP_RIGHT) && mFormat.containsKey(KEY_CROP_LEFT) + && mFormat.containsKey(KEY_CROP_BOTTOM) && mFormat.containsKey(KEY_CROP_TOP); + } + + @CalledByNative("GetOutputFormatResult") + private int status() { + return mStatus; + } + + @CalledByNative("GetOutputFormatResult") + private int width() { + return formatHasCropValues() + ? mFormat.getInteger(KEY_CROP_RIGHT) - mFormat.getInteger(KEY_CROP_LEFT) + 1 + : mFormat.getInteger(MediaFormat.KEY_WIDTH); + } + + @CalledByNative("GetOutputFormatResult") + private int height() { + return formatHasCropValues() + ? mFormat.getInteger(KEY_CROP_BOTTOM) - mFormat.getInteger(KEY_CROP_TOP) + 1 + : mFormat.getInteger(MediaFormat.KEY_HEIGHT); + } + + @CalledByNative("GetOutputFormatResult") + private int sampleRate() { + return mFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE); + } + } + private MediaCodecBridge( MediaCodec mediaCodec, String mime, boolean adaptivePlaybackSupported) { assert mediaCodec != null; @@ -255,45 +297,43 @@ } } - private boolean outputFormatHasCropValues(MediaFormat format) { - return format.containsKey(KEY_CROP_RIGHT) && format.containsKey(KEY_CROP_LEFT) - && format.containsKey(KEY_CROP_BOTTOM) && format.containsKey(KEY_CROP_TOP); - } - @CalledByNative - private int getOutputHeight() { - MediaFormat format = mMediaCodec.getOutputFormat(); - return outputFormatHasCropValues(format) - ? format.getInteger(KEY_CROP_BOTTOM) - format.getInteger(KEY_CROP_TOP) + 1 - : format.getInteger(MediaFormat.KEY_HEIGHT); + private GetOutputFormatResult getOutputFormat() { + MediaFormat format = null; + int status = MEDIA_CODEC_OK; + try { + format = mMediaCodec.getOutputFormat(); + } catch (IllegalStateException e) { + Log.e(TAG, "Failed to get output format", e); + status = MEDIA_CODEC_ERROR; + } + return new GetOutputFormatResult(status, format); } - @CalledByNative - private int getOutputWidth() { - MediaFormat format = mMediaCodec.getOutputFormat(); - return outputFormatHasCropValues(format) - ? format.getInteger(KEY_CROP_RIGHT) - format.getInteger(KEY_CROP_LEFT) + 1 - : format.getInteger(MediaFormat.KEY_WIDTH); - } - - @CalledByNative - private int getOutputSamplingRate() { - MediaFormat format = mMediaCodec.getOutputFormat(); - return format.getInteger(MediaFormat.KEY_SAMPLE_RATE); - } - + /** Returns null if MediaCodec throws IllegalStateException. */ @CalledByNative private ByteBuffer getInputBuffer(int index) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { - return mMediaCodec.getInputBuffer(index); + try { + return mMediaCodec.getInputBuffer(index); + } catch (IllegalStateException e) { + Log.e(TAG, "Failed to get input buffer", e); + return null; + } } return mInputBuffers[index]; } + /** Returns null if MediaCodec throws IllegalStateException. */ @CalledByNative private ByteBuffer getOutputBuffer(int index) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) { - return mMediaCodec.getOutputBuffer(index); + try { + return mMediaCodec.getOutputBuffer(index); + } catch (IllegalStateException e) { + Log.e(TAG, "Failed to get output buffer", e); + return null; + } } return mOutputBuffers[index]; }
diff --git a/media/base/android/media_codec_bridge.cc b/media/base/android/media_codec_bridge.cc index 8cb598f..833d51e 100644 --- a/media/base/android/media_codec_bridge.cc +++ b/media/base/android/media_codec_bridge.cc
@@ -47,7 +47,10 @@ size_t size) { uint8_t* dst = nullptr; size_t capacity = 0; - GetInputBuffer(index, &dst, &capacity); + if (GetInputBuffer(index, &dst, &capacity) != MEDIA_CODEC_OK) { + LOG(ERROR) << "GetInputBuffer failed"; + return false; + } CHECK(dst); if (size > capacity) {
diff --git a/media/base/android/media_codec_bridge.h b/media/base/android/media_codec_bridge.h index 1486231..25d61f97 100644 --- a/media/base/android/media_codec_bridge.h +++ b/media/base/android/media_codec_bridge.h
@@ -17,6 +17,7 @@ #include "base/time/time.h" #include "media/base/android/media_codec_util.h" #include "media/base/media_export.h" +#include "ui/gfx/geometry/size.h" namespace media { @@ -49,7 +50,7 @@ // DequeueInputBuffer() and DequeueOutputBuffer() become invalid. // Please note that this clears all the inputs in the media codec. In other // words, there will be no outputs until new input is provided. - // Returns MEDIA_CODEC_ERROR if an unexpected error happens, or Media_CODEC_OK + // Returns MEDIA_CODEC_ERROR if an unexpected error happens, or MEDIA_CODEC_OK // otherwise. virtual MediaCodecStatus Reset() = 0; @@ -64,13 +65,15 @@ // instance -> StartAudio/Video() is recommended. virtual void Stop() = 0; - // Used for getting output format. This is valid after DequeueInputBuffer() - // returns a format change by returning INFO_OUTPUT_FORMAT_CHANGED - virtual void GetOutputFormat(int* width, int* height) = 0; + // Used for getting the output size. This is valid after DequeueInputBuffer() + // returns a format change by returning INFO_OUTPUT_FORMAT_CHANGED. + // Returns MEDIA_CODEC_ERROR if an error occurs, or MEDIA_CODEC_OK otherwise. + virtual MediaCodecStatus GetOutputSize(gfx::Size* size) = 0; // Used for checking for new sampling rate after DequeueInputBuffer() returns // INFO_OUTPUT_FORMAT_CHANGED - virtual int GetOutputSamplingRate() = 0; + // Returns MEDIA_CODEC_ERROR if an error occurs, or MEDIA_CODEC_OK otherwise. + virtual MediaCodecStatus GetOutputSamplingRate(int* sampling_rate) = 0; // Submits a byte array to the given input buffer. Call this after getting an // available buffer from DequeueInputBuffer(). If |data| is NULL, assume the @@ -144,17 +147,18 @@ virtual void ReleaseOutputBuffer(int index, bool render) = 0; // Returns an input buffer's base pointer and capacity. - virtual void GetInputBuffer(int input_buffer_index, - uint8_t** data, - size_t* capacity) = 0; + virtual MediaCodecStatus GetInputBuffer(int input_buffer_index, + uint8_t** data, + size_t* capacity) = 0; // Copy |num| bytes from output buffer |index|'s |offset| into the memory - // region pointed to by |*dst|. To avoid overflows, the size of both source + // region pointed to by |dst|. To avoid overflows, the size of both source // and destination must be at least |num| bytes, and should not overlap. - virtual void CopyFromOutputBuffer(int index, - size_t offset, - void* dst, - size_t num) = 0; + // Returns MEDIA_CODEC_ERROR if an error occurs, or MEDIA_CODEC_OK otherwise. + virtual MediaCodecStatus CopyFromOutputBuffer(int index, + size_t offset, + void* dst, + size_t num) = 0; protected: MediaCodecBridge();
diff --git a/media/base/android/ndk_media_codec_bridge.cc b/media/base/android/ndk_media_codec_bridge.cc index b811445b..3a66db6 100644 --- a/media/base/android/ndk_media_codec_bridge.cc +++ b/media/base/android/ndk_media_codec_bridge.cc
@@ -67,7 +67,7 @@ AMediaCodec_stop(media_codec_.get()); } -void NdkMediaCodecBridge::GetOutputFormat(int* width, int* height) { +MediaCodecStatus NdkMediaCodecBridge::GetOutputSize(gfx::Size* size) { AMediaFormat* format = AMediaCodec_getOutputFormat(media_codec_.get()); int left, right, bottom, top; bool has_left = AMediaFormat_getInt32(format, kMediaFormatKeyCropLeft, &left); @@ -76,22 +76,26 @@ bool has_bottom = AMediaFormat_getInt32(format, kMediaFormatKeyCropBottom, &bottom); bool has_top = AMediaFormat_getInt32(format, kMediaFormatKeyCropTop, &top); + int width, height; if (has_left && has_right && has_bottom && has_top) { // Use crop size as it is more accurate. right and bottom are inclusive. - *width = right - left + 1; - *height = top - bottom + 1; + width = right - left + 1; + height = top - bottom + 1; } else { - AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, width); - AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, height); + AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &width); + AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &height); } + size->SetSize(width, height); + return MEDIA_CODEC_OK; } -int NdkMediaCodecBridge::GetOutputSamplingRate() { +MediaCodecStatus NdkMediaCodecBridge::GetOutputSamplingRate( + int* sampling_rate) { AMediaFormat* format = AMediaCodec_getOutputFormat(media_codec_.get()); - int sample_rate = 0; - AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, &sample_rate); - DCHECK(sample_rate != 0); - return sample_rate; + *sampling_rate = 0; + AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, sampling_rate); + DCHECK_NE(*sampling_rate, 0); + return MEDIA_CODEC_OK; } MediaCodecStatus NdkMediaCodecBridge::QueueInputBuffer( @@ -213,22 +217,24 @@ AMediaCodec_releaseOutputBuffer(media_codec_.get(), index, render); } -void NdkMediaCodecBridge::GetInputBuffer(int input_buffer_index, - uint8_t** data, - size_t* capacity) { +MediaCodecStatus NdkMediaCodecBridge::GetInputBuffer(int input_buffer_index, + uint8_t** data, + size_t* capacity) { *data = AMediaCodec_getInputBuffer(media_codec_.get(), input_buffer_index, capacity); + return MEDIA_CODEC_OK; } -void NdkMediaCodecBridge::CopyFromOutputBuffer(int index, - size_t offset, - void* dst, - size_t num) { +MediaCodecStatus NdkMediaCodecBridge::CopyFromOutputBuffer(int index, + size_t offset, + void* dst, + size_t num) { size_t capacity; const uint8_t* src_data = AMediaCodec_getOutputBuffer(media_codec_.get(), index, &capacity); CHECK_GE(capacity, offset + num); memcpy(dst, src_data + offset, num); + return MEDIA_CODEC_OK; } } // namespace media
diff --git a/media/base/android/ndk_media_codec_bridge.h b/media/base/android/ndk_media_codec_bridge.h index 7621eff..d7f2b10 100644 --- a/media/base/android/ndk_media_codec_bridge.h +++ b/media/base/android/ndk_media_codec_bridge.h
@@ -14,6 +14,7 @@ #include "base/time/time.h" #include "media/base/android/media_codec_bridge.h" #include "media/base/media_export.h" +#include "ui/gfx/geometry/size.h" namespace media { @@ -25,8 +26,8 @@ MediaCodecStatus Reset() override; bool Start() override; void Stop() override; - void GetOutputFormat(int* width, int* height) override; - int GetOutputSamplingRate() override; + MediaCodecStatus GetOutputSize(gfx::Size* size) override; + MediaCodecStatus GetOutputSamplingRate(int* sampling_rate) override; MediaCodecStatus QueueInputBuffer( int index, const uint8_t* data, @@ -53,13 +54,13 @@ bool* end_of_stream, bool* key_frame) override; void ReleaseOutputBuffer(int index, bool render) override; - void GetInputBuffer(int input_buffer_index, - uint8_t** data, - size_t* capacity) override; - void CopyFromOutputBuffer(int index, - size_t offset, - void* dst, - size_t num) override; + MediaCodecStatus GetInputBuffer(int input_buffer_index, + uint8_t** data, + size_t* capacity) override; + MediaCodecStatus CopyFromOutputBuffer(int index, + size_t offset, + void* dst, + size_t num) override; protected: NdkMediaCodecBridge(const std::string& mime,
diff --git a/media/base/android/sdk_media_codec_bridge.cc b/media/base/android/sdk_media_codec_bridge.cc index 6278216..fdda989d 100644 --- a/media/base/android/sdk_media_codec_bridge.cc +++ b/media/base/android/sdk_media_codec_bridge.cc
@@ -112,17 +112,29 @@ Java_MediaCodecBridge_stop(env, j_media_codec_.obj()); } -void SdkMediaCodecBridge::GetOutputFormat(int* width, int* height) { +MediaCodecStatus SdkMediaCodecBridge::GetOutputSize(gfx::Size* size) { JNIEnv* env = AttachCurrentThread(); - - *width = Java_MediaCodecBridge_getOutputWidth(env, j_media_codec_.obj()); - *height = Java_MediaCodecBridge_getOutputHeight(env, j_media_codec_.obj()); + ScopedJavaLocalRef<jobject> result = + Java_MediaCodecBridge_getOutputFormat(env, j_media_codec_.obj()); + MediaCodecStatus status = static_cast<MediaCodecStatus>( + Java_GetOutputFormatResult_status(env, result.obj())); + if (status == MEDIA_CODEC_OK) { + size->SetSize(Java_GetOutputFormatResult_width(env, result.obj()), + Java_GetOutputFormatResult_height(env, result.obj())); + } + return status; } -int SdkMediaCodecBridge::GetOutputSamplingRate() { +MediaCodecStatus SdkMediaCodecBridge::GetOutputSamplingRate( + int* sampling_rate) { JNIEnv* env = AttachCurrentThread(); - - return Java_MediaCodecBridge_getOutputSamplingRate(env, j_media_codec_.obj()); + ScopedJavaLocalRef<jobject> result = + Java_MediaCodecBridge_getOutputFormat(env, j_media_codec_.obj()); + MediaCodecStatus status = static_cast<MediaCodecStatus>( + Java_GetOutputFormatResult_status(env, result.obj())); + if (status == MEDIA_CODEC_OK) + *sampling_rate = Java_GetOutputFormatResult_sampleRate(env, result.obj()); + return status; } MediaCodecStatus SdkMediaCodecBridge::QueueInputBuffer( @@ -274,39 +286,52 @@ render); } -void SdkMediaCodecBridge::GetInputBuffer(int input_buffer_index, - uint8_t** data, - size_t* capacity) { +MediaCodecStatus SdkMediaCodecBridge::GetInputBuffer(int input_buffer_index, + uint8_t** data, + size_t* capacity) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> j_buffer(Java_MediaCodecBridge_getInputBuffer( env, j_media_codec_.obj(), input_buffer_index)); + if (j_buffer.is_null()) + return MEDIA_CODEC_ERROR; + *data = static_cast<uint8_t*>(env->GetDirectBufferAddress(j_buffer.obj())); *capacity = base::checked_cast<size_t>(env->GetDirectBufferCapacity(j_buffer.obj())); + return MEDIA_CODEC_OK; } -void SdkMediaCodecBridge::CopyFromOutputBuffer(int index, - size_t offset, - void* dst, - size_t num) { +MediaCodecStatus SdkMediaCodecBridge::CopyFromOutputBuffer(int index, + size_t offset, + void* dst, + size_t num) { void* src_data = nullptr; - const size_t src_capacity = GetOutputBufferAddress(index, offset, &src_data); - CHECK_GE(src_capacity, num); - memcpy(dst, src_data, num); + size_t src_capacity = 0; + MediaCodecStatus status = + GetOutputBufferAddress(index, offset, &src_data, &src_capacity); + if (status == MEDIA_CODEC_OK) { + CHECK_GE(src_capacity, num); + memcpy(dst, src_data, num); + } + return status; } -size_t SdkMediaCodecBridge::GetOutputBufferAddress(int index, - size_t offset, - void** addr) { +MediaCodecStatus SdkMediaCodecBridge::GetOutputBufferAddress(int index, + size_t offset, + void** addr, + size_t* capacity) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> j_buffer( Java_MediaCodecBridge_getOutputBuffer(env, j_media_codec_.obj(), index)); + if (j_buffer.is_null()) + return MEDIA_CODEC_ERROR; const size_t total_capacity = env->GetDirectBufferCapacity(j_buffer.obj()); CHECK_GE(total_capacity, offset); *addr = reinterpret_cast<uint8_t*>(env->GetDirectBufferAddress(j_buffer.obj())) + offset; - return total_capacity - offset; + *capacity = total_capacity - offset; + return MEDIA_CODEC_OK; } // static @@ -528,23 +553,30 @@ return true; } -int64_t AudioCodecBridge::PlayOutputBuffer(int index, - size_t size, - size_t offset, - bool postpone) { +MediaCodecStatus AudioCodecBridge::PlayOutputBuffer(int index, + size_t size, + size_t offset, + bool postpone, + int64_t* playback_pos) { DCHECK_LE(0, index); int numBytes = base::checked_cast<int>(size); void* buffer = nullptr; - int capacity = GetOutputBufferAddress(index, offset, &buffer); - numBytes = std::min(capacity, numBytes); + size_t capacity = 0; + MediaCodecStatus status = + GetOutputBufferAddress(index, offset, &buffer, &capacity); + if (status == MEDIA_CODEC_ERROR) + return status; + + numBytes = std::min(base::checked_cast<int>(capacity), numBytes); CHECK_GE(numBytes, 0); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jbyteArray> byte_array = base::android::ToJavaByteArray( env, static_cast<uint8_t*>(buffer), numBytes); - return Java_MediaCodecBridge_playOutputBuffer(env, media_codec(), - byte_array.obj(), postpone); + *playback_pos = Java_MediaCodecBridge_playOutputBuffer( + env, media_codec(), byte_array.obj(), postpone); + return status; } void AudioCodecBridge::SetVolume(double volume) {
diff --git a/media/base/android/sdk_media_codec_bridge.h b/media/base/android/sdk_media_codec_bridge.h index bf072b41..e23400d 100644 --- a/media/base/android/sdk_media_codec_bridge.h +++ b/media/base/android/sdk_media_codec_bridge.h
@@ -32,8 +32,8 @@ MediaCodecStatus Reset() override; bool Start() override; void Stop() override; - void GetOutputFormat(int* width, int* height) override; - int GetOutputSamplingRate() override; + MediaCodecStatus GetOutputSize(gfx::Size* size) override; + MediaCodecStatus GetOutputSamplingRate(int* sampling_rate) override; MediaCodecStatus QueueInputBuffer( int index, const uint8_t* data, @@ -60,13 +60,13 @@ bool* end_of_stream, bool* key_frame) override; void ReleaseOutputBuffer(int index, bool render) override; - void GetInputBuffer(int input_buffer_index, - uint8_t** data, - size_t* capacity) override; - void CopyFromOutputBuffer(int index, - size_t offset, - void* dst, - size_t num) override; + MediaCodecStatus GetInputBuffer(int input_buffer_index, + uint8_t** data, + size_t* capacity) override; + MediaCodecStatus CopyFromOutputBuffer(int index, + size_t offset, + void* dst, + size_t num) override; static bool RegisterSdkMediaCodecBridge(JNIEnv* env); @@ -76,9 +76,13 @@ MediaCodecDirection direction); // Called to get the buffer address given the output buffer index and offset. - // This function returns the size of available data to read and |addr| is the - // pointer to the address to read. - size_t GetOutputBufferAddress(int index, size_t offset, void** addr); + // The size of available data to read is written to |*capacity| and the + // address to read from is written to |*addr|. + // Returns MEDIA_CODEC_ERROR if a error occurs, or MEDIA_CODEC_OK otherwise. + MediaCodecStatus GetOutputBufferAddress(int index, + size_t offset, + void** addr, + size_t* capacity); jobject media_codec() { return j_media_codec_.obj(); } MediaCodecDirection direction_; @@ -125,15 +129,17 @@ // Plays the output buffer right away or save for later playback if |postpone| // is set to true. This call must be called after DequeueOutputBuffer() and // before ReleaseOutputBuffer. The data is extracted from the output buffers - // using |index|, |size| and |offset|. Returns the playback head position - // expressed in frames. + // using |index|, |size| and |offset|. The playback head position in frames is + // output in |*playback_pos|. // When |postpone| is set to true, the next PlayOutputBuffer() should have // postpone == false, and it will play two buffers: the postponed one and // the one identified by |index|. - int64_t PlayOutputBuffer(int index, - size_t size, - size_t offset, - bool postpone = false); + // Returns MEDIA_CODEC_ERROR if an error occurs, or MEDIA_CODEC_OK otherwise. + MediaCodecStatus PlayOutputBuffer(int index, + size_t size, + size_t offset, + bool postpone, + int64_t* playback_pos); // Set the volume of the audio output. void SetVolume(double volume);
diff --git a/media/base/android/video_decoder_job.cc b/media/base/android/video_decoder_job.cc index fa49ab3..3e3123c 100644 --- a/media/base/android/video_decoder_job.cc +++ b/media/base/android/video_decoder_job.cc
@@ -151,7 +151,7 @@ return false; int prev_output_width = output_width_; int prev_output_height = output_height_; - // See b/18224769. The values reported from MediaCodecBridge::GetOutputFormat + // See b/18224769. The values reported from MediaCodecBridge::GetOutputSize // correspond to the actual video frame size, but this is not necessarily the // size that should be output. output_width_ = config_width_;
diff --git a/media/base/android/video_media_codec_decoder.cc b/media/base/android/video_media_codec_decoder.cc index 6fdd3ca..e9a30583 100644 --- a/media/base/android/video_media_codec_decoder.cc +++ b/media/base/android/video_media_codec_decoder.cc
@@ -210,7 +210,7 @@ gfx::Size prev_size = video_size_; - // See b/18224769. The values reported from MediaCodecBridge::GetOutputFormat + // See b/18224769. The values reported from MediaCodecBridge::GetOutputSize // correspond to the actual video frame size, but this is not necessarily the // size that should be output. video_size_ = configs_.video_size;
diff --git a/media/base/demuxer.h b/media/base/demuxer.h index afacdf30..7e1dbc8 100644 --- a/media/base/demuxer.h +++ b/media/base/demuxer.h
@@ -22,6 +22,7 @@ namespace media { class TextTrackConfig; +class MediaTracks; class MEDIA_EXPORT DemuxerHost { public: @@ -64,6 +65,11 @@ const std::vector<uint8_t>& init_data)> EncryptedMediaInitDataCB; + // Notifies demuxer clients that media track configuration has been updated + // (e.g. the inital stream metadata has been parsed successfully, or a new + // init segment has been parsed successfully in MSE case). + typedef base::Callback<void(scoped_ptr<MediaTracks>)> MediaTracksUpdatedCB; + Demuxer(); ~Demuxer() override;
diff --git a/media/base/demuxer_perftest.cc b/media/base/demuxer_perftest.cc index 7d8a10ba..6703222 100644 --- a/media/base/demuxer_perftest.cc +++ b/media/base/demuxer_perftest.cc
@@ -14,6 +14,7 @@ #include "build/build_config.h" #include "media/base/media.h" #include "media/base/media_log.h" +#include "media/base/media_tracks.h" #include "media/base/test_data_util.h" #include "media/base/timestamp_constants.h" #include "media/filters/ffmpeg_demuxer.h" @@ -54,6 +55,10 @@ VLOG(0) << "File is encrypted."; } +static void OnMediaTracksUpdated(scoped_ptr<MediaTracks> tracks) { + VLOG(0) << "Got media tracks info, tracks = " << tracks->tracks().size(); +} + typedef std::vector<media::DemuxerStream* > Streams; // Simulates playback reading requirements by reading from each stream @@ -183,8 +188,11 @@ Demuxer::EncryptedMediaInitDataCB encrypted_media_init_data_cb = base::Bind(&OnEncryptedMediaInitData); + Demuxer::MediaTracksUpdatedCB tracks_updated_cb = + base::Bind(&OnMediaTracksUpdated); FFmpegDemuxer demuxer(message_loop.task_runner(), &data_source, - encrypted_media_init_data_cb, new MediaLog()); + encrypted_media_init_data_cb, tracks_updated_cb, + new MediaLog()); demuxer.Initialize(&demuxer_host, base::Bind(&QuitLoopWithStatus, &message_loop),
diff --git a/media/base/mock_filters.cc b/media/base/mock_filters.cc index 86b882c..1c783bd 100644 --- a/media/base/mock_filters.cc +++ b/media/base/mock_filters.cc
@@ -14,6 +14,31 @@ namespace media { +MockPipeline::MockPipeline() {} + +MockPipeline::~MockPipeline() {} + +void MockPipeline::Start(Demuxer* demuxer, + scoped_ptr<Renderer> renderer, + const base::Closure& ended_cb, + const PipelineStatusCB& error_cb, + const PipelineStatusCB& seek_cb, + const PipelineMetadataCB& metadata_cb, + const BufferingStateCB& buffering_state_cb, + const base::Closure& duration_change_cb, + const AddTextTrackCB& add_text_track_cb, + const base::Closure& waiting_for_decryption_key_cb) { + Start(demuxer, &renderer, ended_cb, error_cb, seek_cb, metadata_cb, + buffering_state_cb, duration_change_cb, add_text_track_cb, + waiting_for_decryption_key_cb); +} + +void MockPipeline::Resume(scoped_ptr<Renderer> renderer, + base::TimeDelta timestamp, + const PipelineStatusCB& seek_cb) { + Resume(&renderer, timestamp, seek_cb); +} + MockDemuxer::MockDemuxer() {} MockDemuxer::~MockDemuxer() {}
diff --git a/media/base/mock_filters.h b/media/base/mock_filters.h index 368a542..482f159 100644 --- a/media/base/mock_filters.h +++ b/media/base/mock_filters.h
@@ -18,6 +18,7 @@ #include "media/base/decoder_buffer.h" #include "media/base/decryptor.h" #include "media/base/demuxer.h" +#include "media/base/pipeline.h" #include "media/base/pipeline_status.h" #include "media/base/renderer.h" #include "media/base/text_track.h" @@ -30,6 +31,72 @@ namespace media { +class MockPipeline : public Pipeline { + public: + MockPipeline(); + virtual ~MockPipeline(); + + // Note: Start() and Resume() declarations are not actually overrides; they + // take scoped_ptr* instead of scoped_ptr so that they can be mock methods. + // Private stubs for Start() and Resume() implement the actual Pipeline + // interface by forwarding to these mock methods. + MOCK_METHOD10(Start, + void(Demuxer*, + scoped_ptr<Renderer>*, + const base::Closure&, + const PipelineStatusCB&, + const PipelineStatusCB&, + const PipelineMetadataCB&, + const BufferingStateCB&, + const base::Closure&, + const AddTextTrackCB&, + const base::Closure&)); + MOCK_METHOD1(Stop, void(const base::Closure&)); + MOCK_METHOD2(Seek, void(base::TimeDelta, const PipelineStatusCB&)); + MOCK_METHOD1(Suspend, void(const PipelineStatusCB&)); + MOCK_METHOD3(Resume, + void(scoped_ptr<Renderer>*, + base::TimeDelta, + const PipelineStatusCB&)); + + // TODO(sandersd): This should automatically return true between Start() and + // Stop(). (Or better, remove it from the interface entirely.) + MOCK_CONST_METHOD0(IsRunning, bool()); + + // TODO(sandersd): These should be regular getters/setters. + MOCK_CONST_METHOD0(GetPlaybackRate, double()); + MOCK_METHOD1(SetPlaybackRate, void(double)); + MOCK_CONST_METHOD0(GetVolume, float()); + MOCK_METHOD1(SetVolume, void(float)); + + // TODO(sandersd): These should probably have setters too. + MOCK_CONST_METHOD0(GetMediaTime, base::TimeDelta()); + MOCK_CONST_METHOD0(GetBufferedTimeRanges, Ranges<base::TimeDelta>()); + MOCK_CONST_METHOD0(GetMediaDuration, base::TimeDelta()); + MOCK_METHOD0(DidLoadingProgress, bool()); + MOCK_CONST_METHOD0(GetStatistics, PipelineStatistics()); + + MOCK_METHOD2(SetCdm, void(CdmContext*, const CdmAttachedCB&)); + + private: + // Forwarding stubs (see comment above). + void Start(Demuxer* demuxer, + scoped_ptr<Renderer> renderer, + const base::Closure& ended_cb, + const PipelineStatusCB& error_cb, + const PipelineStatusCB& seek_cb, + const PipelineMetadataCB& metadata_cb, + const BufferingStateCB& buffering_state_cb, + const base::Closure& duration_change_cb, + const AddTextTrackCB& add_text_track_cb, + const base::Closure& waiting_for_decryption_key_cb) override; + void Resume(scoped_ptr<Renderer> renderer, + base::TimeDelta timestamp, + const PipelineStatusCB& seek_cb) override; + + DISALLOW_COPY_AND_ASSIGN(MockPipeline); +}; + class MockDemuxer : public Demuxer { public: MockDemuxer();
diff --git a/media/base/pipeline_impl.cc b/media/base/pipeline_impl.cc index 085e549..8be32f4 100644 --- a/media/base/pipeline_impl.cc +++ b/media/base/pipeline_impl.cc
@@ -503,7 +503,6 @@ void PipelineImpl::OnBufferedTimeRangesChanged( const Ranges<base::TimeDelta>& ranges) { - DCHECK(IsRunning()); base::AutoLock auto_lock(lock_); buffered_time_ranges_ = ranges; did_loading_progress_ = true;
diff --git a/media/base/pipeline_impl.h b/media/base/pipeline_impl.h index a4a4757..8a55ed72 100644 --- a/media/base/pipeline_impl.h +++ b/media/base/pipeline_impl.h
@@ -113,10 +113,8 @@ const CdmAttachedCB& cdm_attached_cb) override; private: - FRIEND_TEST_ALL_PREFIXES(PipelineImplTest, GetBufferedTimeRanges); - FRIEND_TEST_ALL_PREFIXES(PipelineImplTest, EndedCallback); - FRIEND_TEST_ALL_PREFIXES(PipelineImplTest, AudioStreamShorterThanVideo); friend class MediaLog; + friend class PipelineImplTest; // Pipeline states, as described above. enum State {
diff --git a/media/base/pipeline_impl_unittest.cc b/media/base/pipeline_impl_unittest.cc index 33e7a16..def4963 100644 --- a/media/base/pipeline_impl_unittest.cc +++ b/media/base/pipeline_impl_unittest.cc
@@ -342,6 +342,19 @@ done_cb.Run(std::move(text_track)); } + void RunBufferedTimeRangesTest(const base::TimeDelta duration) { + EXPECT_EQ(0u, pipeline_->GetBufferedTimeRanges().size()); + EXPECT_FALSE(pipeline_->DidLoadingProgress()); + Ranges<base::TimeDelta> ranges; + ranges.Add(base::TimeDelta(), duration); + pipeline_->OnBufferedTimeRangesChanged(ranges); + EXPECT_TRUE(pipeline_->DidLoadingProgress()); + EXPECT_FALSE(pipeline_->DidLoadingProgress()); + EXPECT_EQ(1u, pipeline_->GetBufferedTimeRanges().size()); + EXPECT_EQ(base::TimeDelta(), pipeline_->GetBufferedTimeRanges().start(0)); + EXPECT_EQ(duration, pipeline_->GetBufferedTimeRanges().end(0)); + } + // Fixture members. StrictMock<CallbackHelper> callbacks_; base::SimpleTestTickClock test_tick_clock_; @@ -649,18 +662,7 @@ SetRendererExpectations(); StartPipelineAndExpect(PIPELINE_OK); - - EXPECT_EQ(0u, pipeline_->GetBufferedTimeRanges().size()); - - EXPECT_FALSE(pipeline_->DidLoadingProgress()); - Ranges<base::TimeDelta> ranges; - ranges.Add(base::TimeDelta(), kDuration / 8); - pipeline_->OnBufferedTimeRangesChanged(ranges); - EXPECT_TRUE(pipeline_->DidLoadingProgress()); - EXPECT_FALSE(pipeline_->DidLoadingProgress()); - EXPECT_EQ(1u, pipeline_->GetBufferedTimeRanges().size()); - EXPECT_EQ(base::TimeDelta(), pipeline_->GetBufferedTimeRanges().start(0)); - EXPECT_EQ(kDuration / 8, pipeline_->GetBufferedTimeRanges().end(0)); + RunBufferedTimeRangesTest(kDuration / 8); base::TimeDelta kSeekTime = kDuration / 2; ExpectSeek(kSeekTime, false); @@ -669,6 +671,23 @@ EXPECT_FALSE(pipeline_->DidLoadingProgress()); } +TEST_F(PipelineImplTest, BufferedTimeRangesCanChangeAfterStop) { + EXPECT_CALL(*demuxer_, Initialize(_, _, _)) + .WillOnce(PostCallback<1>(PIPELINE_OK)); + EXPECT_CALL(*demuxer_, Stop()); + + EXPECT_CALL(callbacks_, OnStart(_)); + StartPipeline(); + + EXPECT_CALL(callbacks_, OnStop()); + pipeline_->Stop( + base::Bind(&CallbackHelper::OnStop, base::Unretained(&callbacks_))); + message_loop_.RunUntilIdle(); + + RunBufferedTimeRangesTest(base::TimeDelta::FromSeconds(5)); + DestroyPipeline(); +} + TEST_F(PipelineImplTest, EndedCallback) { CreateAudioStream(); CreateVideoStream();
diff --git a/media/base/video_frame.cc b/media/base/video_frame.cc index b1092e8..ea7370b 100644 --- a/media/base/video_frame.cc +++ b/media/base/video_frame.cc
@@ -36,17 +36,6 @@ return value & ~(alignment - 1); } -static std::string ConfigToString(const VideoPixelFormat format, - const VideoFrame::StorageType storage_type, - const gfx::Size& coded_size, - const gfx::Rect& visible_rect, - const gfx::Size& natural_size) { - return base::StringPrintf( - "format:%s coded_size:%s visible_rect:%s natural_size:%s", - VideoPixelFormatToString(format).c_str(), coded_size.ToString().c_str(), - visible_rect.ToString().c_str(), natural_size.ToString().c_str()); -} - static std::string StorageTypeToString( const VideoFrame::StorageType storage_type) { switch (storage_type) { @@ -70,19 +59,14 @@ #endif case VideoFrame::STORAGE_GPU_MEMORY_BUFFERS: return "GPU_MEMORY_BUFFERS"; + case VideoFrame::STORAGE_MOJO_SHARED_BUFFER: + return "MOJO_SHARED_BUFFER"; } NOTREACHED() << "Invalid StorageType provided: " << storage_type; return "INVALID"; } -// Returns true if |plane| is a valid plane index for the given |format|. -static bool IsValidPlane(size_t plane, VideoPixelFormat format) { - DCHECK_LE(VideoFrame::NumPlanes(format), - static_cast<size_t>(VideoFrame::kMaxPlanes)); - return (plane < VideoFrame::NumPlanes(format)); -} - // Returns true if |frame| is accesible mapped in the VideoFrame memory space. // static static bool IsStorageTypeMappable(VideoFrame::StorageType storage_type) { @@ -95,109 +79,8 @@ (storage_type == VideoFrame::STORAGE_UNOWNED_MEMORY || storage_type == VideoFrame::STORAGE_OWNED_MEMORY || storage_type == VideoFrame::STORAGE_SHMEM || - storage_type == VideoFrame::STORAGE_GPU_MEMORY_BUFFERS); -} - -// Returns the pixel size per element for given |plane| and |format|. E.g. 2x2 -// for the U-plane in PIXEL_FORMAT_I420. -static gfx::Size SampleSize(VideoPixelFormat format, size_t plane) { - DCHECK(IsValidPlane(plane, format)); - - switch (plane) { - case VideoFrame::kYPlane: - case VideoFrame::kAPlane: - return gfx::Size(1, 1); - - case VideoFrame::kUPlane: // and VideoFrame::kUVPlane: - case VideoFrame::kVPlane: - switch (format) { - case PIXEL_FORMAT_YV24: - case PIXEL_FORMAT_YUV444P9: - case PIXEL_FORMAT_YUV444P10: - return gfx::Size(1, 1); - - case PIXEL_FORMAT_YV16: - case PIXEL_FORMAT_YUV422P9: - case PIXEL_FORMAT_YUV422P10: - return gfx::Size(2, 1); - - case PIXEL_FORMAT_YV12: - case PIXEL_FORMAT_I420: - case PIXEL_FORMAT_YV12A: - case PIXEL_FORMAT_NV12: - case PIXEL_FORMAT_NV21: - case PIXEL_FORMAT_MT21: - case PIXEL_FORMAT_YUV420P9: - case PIXEL_FORMAT_YUV420P10: - return gfx::Size(2, 2); - - case PIXEL_FORMAT_UNKNOWN: - case PIXEL_FORMAT_UYVY: - case PIXEL_FORMAT_YUY2: - case PIXEL_FORMAT_ARGB: - case PIXEL_FORMAT_XRGB: - case PIXEL_FORMAT_RGB24: - case PIXEL_FORMAT_RGB32: - case PIXEL_FORMAT_MJPEG: - break; - } - } - NOTREACHED(); - return gfx::Size(); -} - -// Return the alignment for the whole frame, calculated as the max of the -// alignment for each individual plane. -static gfx::Size CommonAlignment(VideoPixelFormat format) { - int max_sample_width = 0; - int max_sample_height = 0; - for (size_t plane = 0; plane < VideoFrame::NumPlanes(format); ++plane) { - const gfx::Size sample_size = SampleSize(format, plane); - max_sample_width = std::max(max_sample_width, sample_size.width()); - max_sample_height = std::max(max_sample_height, sample_size.height()); - } - return gfx::Size(max_sample_width, max_sample_height); -} - -// Returns the number of bytes per element for given |plane| and |format|. -static int BytesPerElement(VideoPixelFormat format, size_t plane) { - DCHECK(IsValidPlane(plane, format)); - switch (format) { - case PIXEL_FORMAT_ARGB: - case PIXEL_FORMAT_XRGB: - case PIXEL_FORMAT_RGB32: - return 4; - case PIXEL_FORMAT_RGB24: - return 3; - case PIXEL_FORMAT_UYVY: - case PIXEL_FORMAT_YUY2: - case PIXEL_FORMAT_YUV420P9: - case PIXEL_FORMAT_YUV422P9: - case PIXEL_FORMAT_YUV444P9: - case PIXEL_FORMAT_YUV420P10: - case PIXEL_FORMAT_YUV422P10: - case PIXEL_FORMAT_YUV444P10: - return 2; - case PIXEL_FORMAT_NV12: - case PIXEL_FORMAT_NV21: - case PIXEL_FORMAT_MT21: { - static const int bytes_per_element[] = {1, 2}; - DCHECK_LT(plane, arraysize(bytes_per_element)); - return bytes_per_element[plane]; - } - case PIXEL_FORMAT_YV12: - case PIXEL_FORMAT_I420: - case PIXEL_FORMAT_YV16: - case PIXEL_FORMAT_YV12A: - case PIXEL_FORMAT_YV24: - return 1; - case PIXEL_FORMAT_MJPEG: - return 0; - case PIXEL_FORMAT_UNKNOWN: - break; - } - NOTREACHED(); - return 0; + storage_type == VideoFrame::STORAGE_GPU_MEMORY_BUFFERS || + storage_type == VideoFrame::STORAGE_MOJO_SHARED_BUFFER); } // static @@ -877,12 +760,9 @@ return "end of stream"; std::ostringstream s; - s << "format: " << VideoPixelFormatToString(format_) - << " storage_type: " << StorageTypeToString(storage_type_) - << " coded_size: " << coded_size_.ToString() - << " visible_rect: " << visible_rect_.ToString() - << " natural_size: " << natural_size_.ToString() - << " timestamp: " << timestamp_.InMicroseconds(); + s << ConfigToString(format_, storage_type_, coded_size_, visible_rect_, + natural_size_) + << " timestamp:" << timestamp_.InMicroseconds(); return s.str(); } @@ -958,6 +838,65 @@ memset(&data_, 0, sizeof(data_)); } +VideoFrame::~VideoFrame() { + if (!mailbox_holders_release_cb_.is_null()) { + gpu::SyncToken release_sync_token; + { + // To ensure that changes to |release_sync_token_| are visible on this + // thread (imply a memory barrier). + base::AutoLock locker(release_sync_token_lock_); + release_sync_token = release_sync_token_; + } + base::ResetAndReturn(&mailbox_holders_release_cb_).Run(release_sync_token); + } + + for (auto& callback : done_callbacks_) + base::ResetAndReturn(&callback).Run(); +} + +// static +std::string VideoFrame::ConfigToString(const VideoPixelFormat format, + const StorageType storage_type, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size) { + return base::StringPrintf( + "format:%s storage_type:%s coded_size:%s visible_rect:%s natural_size:%s", + VideoPixelFormatToString(format).c_str(), + StorageTypeToString(storage_type).c_str(), coded_size.ToString().c_str(), + visible_rect.ToString().c_str(), natural_size.ToString().c_str()); +} + +// static +bool VideoFrame::IsValidPlane(size_t plane, VideoPixelFormat format) { + DCHECK_LE(NumPlanes(format), static_cast<size_t>(kMaxPlanes)); + return (plane < NumPlanes(format)); +} + +// static +gfx::Size VideoFrame::DetermineAlignedSize(VideoPixelFormat format, + const gfx::Size& dimensions) { + const gfx::Size alignment = CommonAlignment(format); + const gfx::Size adjusted = + gfx::Size(RoundUp(dimensions.width(), alignment.width()), + RoundUp(dimensions.height(), alignment.height())); + DCHECK((adjusted.width() % alignment.width() == 0) && + (adjusted.height() % alignment.height() == 0)); + return adjusted; +} + +void VideoFrame::set_data(size_t plane, uint8_t* ptr) { + DCHECK(IsValidPlane(plane, format_)); + DCHECK(ptr); + data_[plane] = ptr; +} + +void VideoFrame::set_stride(size_t plane, int stride) { + DCHECK(IsValidPlane(plane, format_)); + DCHECK_GT(stride, 0); + strides_[plane] = stride; +} + VideoFrame::VideoFrame(VideoPixelFormat format, StorageType storage_type, const gfx::Size& coded_size, @@ -995,22 +934,6 @@ mailbox_holders_release_cb_ = mailbox_holder_release_cb; } -VideoFrame::~VideoFrame() { - if (!mailbox_holders_release_cb_.is_null()) { - gpu::SyncToken release_sync_token; - { - // To ensure that changes to |release_sync_token_| are visible on this - // thread (imply a memory barrier). - base::AutoLock locker(release_sync_token_lock_); - release_sync_token = release_sync_token_; - } - base::ResetAndReturn(&mailbox_holders_release_cb_).Run(release_sync_token); - } - - for (auto& callback : done_callbacks_) - base::ResetAndReturn(&callback).Run(); -} - // static scoped_refptr<VideoFrame> VideoFrame::CreateFrameInternal( VideoPixelFormat format, @@ -1028,13 +951,7 @@ // ourselves), we can pad the requested |coded_size| if necessary if the // request does not line up on sample boundaries. See discussion at // http://crrev.com/1240833003 - const gfx::Size alignment = CommonAlignment(format); - const gfx::Size new_coded_size = - gfx::Size(RoundUp(coded_size.width(), alignment.width()), - RoundUp(coded_size.height(), alignment.height())); - DCHECK((new_coded_size.width() % alignment.width() == 0) && - (new_coded_size.height() % alignment.height() == 0)); - + const gfx::Size new_coded_size = DetermineAlignedSize(format, coded_size); const StorageType storage = STORAGE_OWNED_MEMORY; if (!IsValidConfig(format, storage, new_coded_size, visible_rect, natural_size)) { @@ -1050,6 +967,106 @@ return frame; } +// static +gfx::Size VideoFrame::SampleSize(VideoPixelFormat format, size_t plane) { + DCHECK(IsValidPlane(plane, format)); + + switch (plane) { + case kYPlane: + case kAPlane: + return gfx::Size(1, 1); + + case kUPlane: // and kUVPlane: + case kVPlane: + switch (format) { + case PIXEL_FORMAT_YV24: + case PIXEL_FORMAT_YUV444P9: + case PIXEL_FORMAT_YUV444P10: + return gfx::Size(1, 1); + + case PIXEL_FORMAT_YV16: + case PIXEL_FORMAT_YUV422P9: + case PIXEL_FORMAT_YUV422P10: + return gfx::Size(2, 1); + + case PIXEL_FORMAT_YV12: + case PIXEL_FORMAT_I420: + case PIXEL_FORMAT_YV12A: + case PIXEL_FORMAT_NV12: + case PIXEL_FORMAT_NV21: + case PIXEL_FORMAT_MT21: + case PIXEL_FORMAT_YUV420P9: + case PIXEL_FORMAT_YUV420P10: + return gfx::Size(2, 2); + + case PIXEL_FORMAT_UNKNOWN: + case PIXEL_FORMAT_UYVY: + case PIXEL_FORMAT_YUY2: + case PIXEL_FORMAT_ARGB: + case PIXEL_FORMAT_XRGB: + case PIXEL_FORMAT_RGB24: + case PIXEL_FORMAT_RGB32: + case PIXEL_FORMAT_MJPEG: + break; + } + } + NOTREACHED(); + return gfx::Size(); +} + +// static +int VideoFrame::BytesPerElement(VideoPixelFormat format, size_t plane) { + DCHECK(IsValidPlane(plane, format)); + switch (format) { + case PIXEL_FORMAT_ARGB: + case PIXEL_FORMAT_XRGB: + case PIXEL_FORMAT_RGB32: + return 4; + case PIXEL_FORMAT_RGB24: + return 3; + case PIXEL_FORMAT_UYVY: + case PIXEL_FORMAT_YUY2: + case PIXEL_FORMAT_YUV420P9: + case PIXEL_FORMAT_YUV422P9: + case PIXEL_FORMAT_YUV444P9: + case PIXEL_FORMAT_YUV420P10: + case PIXEL_FORMAT_YUV422P10: + case PIXEL_FORMAT_YUV444P10: + return 2; + case PIXEL_FORMAT_NV12: + case PIXEL_FORMAT_NV21: + case PIXEL_FORMAT_MT21: { + static const int bytes_per_element[] = {1, 2}; + DCHECK_LT(plane, arraysize(bytes_per_element)); + return bytes_per_element[plane]; + } + case PIXEL_FORMAT_YV12: + case PIXEL_FORMAT_I420: + case PIXEL_FORMAT_YV16: + case PIXEL_FORMAT_YV12A: + case PIXEL_FORMAT_YV24: + return 1; + case PIXEL_FORMAT_MJPEG: + return 0; + case PIXEL_FORMAT_UNKNOWN: + break; + } + NOTREACHED(); + return 0; +} + +// static +gfx::Size VideoFrame::CommonAlignment(VideoPixelFormat format) { + int max_sample_width = 0; + int max_sample_height = 0; + for (size_t plane = 0; plane < NumPlanes(format); ++plane) { + const gfx::Size sample_size = SampleSize(format, plane); + max_sample_width = std::max(max_sample_width, sample_size.width()); + max_sample_height = std::max(max_sample_height, sample_size.height()); + } + return gfx::Size(max_sample_width, max_sample_height); +} + void VideoFrame::AllocateYUV(bool zero_initialize_memory) { DCHECK_EQ(storage_type_, STORAGE_OWNED_MEMORY); static_assert(0 == kYPlane, "y plane data must be index 0");
diff --git a/media/base/video_frame.h b/media/base/video_frame.h index ad7f4c0..9538d7a 100644 --- a/media/base/video_frame.h +++ b/media/base/video_frame.h
@@ -73,7 +73,8 @@ STORAGE_HOLE = 6, #endif STORAGE_GPU_MEMORY_BUFFERS = 7, - STORAGE_LAST = STORAGE_GPU_MEMORY_BUFFERS, + STORAGE_MOJO_SHARED_BUFFER = 8, + STORAGE_LAST = STORAGE_MOJO_SHARED_BUFFER, }; // CB to be called on the mailbox backing this frame when the frame is @@ -413,28 +414,40 @@ // Returns a human-readable string describing |*this|. std::string AsHumanReadableString(); - private: + protected: friend class base::RefCountedThreadSafe<VideoFrame>; - static scoped_refptr<VideoFrame> WrapExternalStorage( - VideoPixelFormat format, - StorageType storage_type, - const gfx::Size& coded_size, - const gfx::Rect& visible_rect, - const gfx::Size& natural_size, - uint8_t* data, - size_t data_size, - base::TimeDelta timestamp, - base::SharedMemoryHandle handle, - size_t data_offset); - // Clients must use the static factory/wrapping methods to create a new frame. + // Derived classes should create their own factory/wrapping methods, and use + // this constructor to do basic initialization. VideoFrame(VideoPixelFormat format, StorageType storage_type, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp); + + virtual ~VideoFrame(); + + // Creates a summary of the configuration settings provided as parameters. + static std::string ConfigToString(const VideoPixelFormat format, + const VideoFrame::StorageType storage_type, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size); + + // Returns true if |plane| is a valid plane index for the given |format|. + static bool IsValidPlane(size_t plane, VideoPixelFormat format); + + // Returns |dimensions| adjusted to appropriate boundaries based on |format|. + static gfx::Size DetermineAlignedSize(VideoPixelFormat format, + const gfx::Size& dimensions); + + void set_data(size_t plane, uint8_t* ptr); + void set_stride(size_t plane, int stride); + + private: + // Clients must use the static factory/wrapping methods to create a new frame. VideoFrame(VideoPixelFormat format, StorageType storage_type, const gfx::Size& coded_size, @@ -451,7 +464,18 @@ const gpu::MailboxHolder(&mailbox_holders)[kMaxPlanes], const ReleaseMailboxCB& mailbox_holder_release_cb, base::TimeDelta timestamp); - virtual ~VideoFrame(); + + static scoped_refptr<VideoFrame> WrapExternalStorage( + VideoPixelFormat format, + StorageType storage_type, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size, + uint8_t* data, + size_t data_size, + base::TimeDelta timestamp, + base::SharedMemoryHandle handle, + size_t data_offset); static scoped_refptr<VideoFrame> CreateFrameInternal( VideoPixelFormat format, @@ -461,6 +485,17 @@ base::TimeDelta timestamp, bool zero_initialize_memory); + // Returns the pixel size of each subsample for a given |plane| and |format|. + // E.g. 2x2 for the U-plane in PIXEL_FORMAT_I420. + static gfx::Size SampleSize(VideoPixelFormat format, size_t plane); + + // Returns the number of bytes per element for given |plane| and |format|. + static int BytesPerElement(VideoPixelFormat format, size_t plane); + + // Return the alignment for the whole frame, calculated as the max of the + // alignment for each individual plane. + static gfx::Size CommonAlignment(VideoPixelFormat format); + void AllocateYUV(bool zero_initialize_memory); // Frame format.
diff --git a/media/blink/DEPS b/media/blink/DEPS index 374de6ec..41db62d 100644 --- a/media/blink/DEPS +++ b/media/blink/DEPS
@@ -10,4 +10,7 @@ "+net/http", "+third_party/WebKit/public/platform", "+third_party/WebKit/public/web", + + # media/mojo is not part of "media" target and should not use MEDIA_EXPORT. + "-media/base/media_export.h" ]
diff --git a/media/blink/webmediaplayer_cast_android.cc b/media/blink/webmediaplayer_cast_android.cc index 993af2c8..ec94419 100644 --- a/media/blink/webmediaplayer_cast_android.cc +++ b/media/blink/webmediaplayer_cast_android.cc
@@ -221,7 +221,7 @@ DVLOG(1) << __FUNCTION__; remote_time_at_ = base::TimeTicks::Now(); remote_time_ = current_time; - webmediaplayer_->OnPipelineSeeked(true, PIPELINE_OK); + webmediaplayer_->OnPipelineSeeked(true); } void WebMediaPlayerCast::OnMediaError(int error_type) {
diff --git a/media/blink/webmediaplayer_impl.cc b/media/blink/webmediaplayer_impl.cc index 84bcfffb..2185d931 100644 --- a/media/blink/webmediaplayer_impl.cc +++ b/media/blink/webmediaplayer_impl.cc
@@ -11,6 +11,7 @@ #include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/command_line.h" @@ -44,7 +45,6 @@ #include "media/blink/webmediasource_impl.h" #include "media/filters/chunk_demuxer.h" #include "media/filters/ffmpeg_demuxer.h" -#include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebEncryptedMediaTypes.h" #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h" #include "third_party/WebKit/public/platform/WebMediaPlayerEncryptedMediaClient.h" @@ -143,20 +143,21 @@ worker_task_runner_(params.worker_task_runner()), media_log_(params.media_log()), pipeline_(media_task_runner_, media_log_.get()), + pipeline_controller_( + &pipeline_, + base::Bind(&WebMediaPlayerImpl::CreateRenderer, + base::Unretained(this)), + base::Bind(&WebMediaPlayerImpl::OnPipelineSeeked, AsWeakPtr()), + base::Bind(&WebMediaPlayerImpl::OnPipelineSuspended, AsWeakPtr()), + base::Bind(&WebMediaPlayerImpl::OnPipelineResumed, AsWeakPtr()), + base::Bind(&WebMediaPlayerImpl::OnPipelineError, AsWeakPtr())), load_type_(LoadTypeURL), opaque_(false), playback_rate_(0.0), paused_(true), seeking_(false), - pending_suspend_(false), - pending_time_change_(false), - pending_resume_(false), - suspending_(false), - suspended_(false), - resuming_(false), pending_suspend_resume_cycle_(false), ended_(false), - pending_seek_(false), should_notify_time_changed_(false), fullscreen_(false), decoder_requires_restart_for_fullscreen_(false), @@ -230,7 +231,7 @@ data_source_->Abort(); if (chunk_demuxer_) { chunk_demuxer_->Shutdown(); - chunk_demuxer_ = NULL; + chunk_demuxer_ = nullptr; } renderer_factory_.reset(); @@ -282,9 +283,7 @@ DCHECK(main_task_runner_->BelongsToCurrentThread()); GURL gurl(url); - ReportMetrics( - load_type, gurl, - blink::WebStringToGURL(frame_->document().securityOrigin().toString())); + ReportMetrics(load_type, gurl, frame_->document().securityOrigin()); // Set subresource URL for crash reporting. base::debug::SetCrashKeyValue("subresource_url", gurl.spec()); @@ -342,21 +341,21 @@ #endif paused_ = false; - pipeline_.SetPlaybackRate(playback_rate_); + if (data_source_) data_source_->MediaIsPlaying(); media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PLAY)); if (playback_rate_ > 0) { - // Resume the player if playback was initiated in the foreground. - if (suspended_ && !resuming_ && delegate_ && !delegate_->IsHidden()) { - ScheduleResume(); - return; - } - NotifyPlaybackStarted(); + + // Resume the player if playback was initiated in the foreground. Resume() + // will do nothing if the pipeline is not suspended state, but will clear + // some internal pending state, so it should always be called. + if (delegate_ && !delegate_->IsHidden()) + pipeline_controller_.Resume(); } } @@ -375,7 +374,13 @@ #endif pipeline_.SetPlaybackRate(0.0); - UpdatePausedTime(); + + // pause() may be called after playback has ended and the HTMLMediaElement + // requires that currentTime() == duration() after ending. We want to ensure + // |paused_time_| matches currentTime() in this case or a future seek() may + // incorrectly discard what it thinks is a seek to the existing time. + paused_time_ = + ended_ ? pipeline_.GetMediaDuration() : pipeline_.GetMediaTime(); media_log_->AddEvent(media_log_->CreateEvent(MediaLogEvent::PAUSE)); @@ -391,14 +396,17 @@ void WebMediaPlayerImpl::seek(double seconds) { DVLOG(1) << __FUNCTION__ << "(" << seconds << "s)"; DCHECK(main_task_runner_->BelongsToCurrentThread()); + DoSeek(base::TimeDelta::FromSecondsD(seconds), true); +} + +void WebMediaPlayerImpl::DoSeek(base::TimeDelta time, bool time_updated) { + DCHECK(main_task_runner_->BelongsToCurrentThread()); ended_ = false; - base::TimeDelta new_seek_time = base::TimeDelta::FromSecondsD(seconds); - #if defined(OS_ANDROID) // WMPI_CAST if (isRemote()) { - cast_impl_.seek(new_seek_time); + cast_impl_.seek(time); return; } #endif @@ -407,86 +415,39 @@ if (ready_state_ > WebMediaPlayer::ReadyStateHaveMetadata) SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata); - if (seeking_ || suspended_) { - // Once resuming, it's too late to change the resume time and so the - // implementation is a little different. - bool is_suspended = suspended_ && !resuming_; - - // If we are currently seeking or resuming to |new_seek_time|, skip the - // seek (except for MSE, which always seeks). - if (!is_suspended && new_seek_time == seek_time_) { - if (chunk_demuxer_) { - // Don't suppress any redundant in-progress MSE seek. There could have - // been changes to the underlying buffers after seeking the demuxer and - // before receiving OnPipelineSeeked() for the currently in-progress - // seek. - MEDIA_LOG(DEBUG, media_log_) - << "Detected MediaSource seek to same time as in-progress seek to " - << seek_time_ << "."; - } else { - // Suppress all redundant seeks if unrestricted by media source demuxer - // API. - pending_seek_ = false; - pending_seek_time_ = base::TimeDelta(); - return; - } - } - - // If |chunk_demuxer_| is already seeking, cancel that seek and schedule the - // new one. - if (!is_suspended && chunk_demuxer_) - chunk_demuxer_->CancelPendingSeek(new_seek_time); - - // Schedule a seek once the current suspend or seek finishes. - pending_seek_ = true; - pending_seek_time_ = new_seek_time; - - // In the case of seeking while suspended, the seek is considered to have - // started immediately (but won't complete until the pipeline is resumed). - if (is_suspended) { - seeking_ = true; - seek_time_ = new_seek_time; - - // Resume the pipeline if the seek is initiated in the foreground so that - // the correct frame is displayed. - if (delegate_ && !delegate_->IsHidden()) - ScheduleResume(); - } - - return; - } - - media_log_->AddEvent(media_log_->CreateSeekEvent(seconds)); - - // Update our paused time. - // For non-MSE playbacks, in paused state ignore the seek operations to - // current time if the loading is completed and generate - // OnPipelineBufferingStateChanged event to eventually fire seeking and seeked - // events. We don't short-circuit MSE seeks in this logic because the - // underlying buffers around the seek time might have changed (or even been - // removed) since previous seek/preroll/pause action, and the pipeline might - // need to flush so the new buffers are decoded and rendered instead of the - // old ones. - if (paused_) { - if (paused_time_ != new_seek_time || chunk_demuxer_) { - paused_time_ = new_seek_time; - } else if (old_state == ReadyStateHaveEnoughData) { + // When paused, we know exactly what the current time is and can elide seeks + // to it. However, there are two cases that are not elided: + // 1) When the pipeline state is not stable. + // In this case we just let |pipeline_controller_| decide what to do, as + // it has complete information. + // 2) For MSE. + // Because the buffers may have changed between seeks, MSE seeks are + // never elided. + if (paused_ && pipeline_controller_.IsStable() && paused_time_ == time && + !chunk_demuxer_) { + // If the ready state was high enough before, we can indicate that the seek + // completed just by restoring it. Otherwise we will just wait for the real + // ready state change to eventually happen. + if (old_state == ReadyStateHaveEnoughData) { main_task_runner_->PostTask( FROM_HERE, base::Bind(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged, AsWeakPtr(), BUFFERING_HAVE_ENOUGH)); - return; } + return; } seeking_ = true; - seek_time_ = new_seek_time; + seek_time_ = time; + if (paused_) + paused_time_ = time; + pipeline_controller_.Seek(time, time_updated); - if (chunk_demuxer_) - chunk_demuxer_->StartWaitingForSeek(seek_time_); - - pipeline_.Seek(seek_time_, BIND_TO_RENDER_LOOP1( - &WebMediaPlayerImpl::OnPipelineSeeked, true)); + // Resume the pipeline if the seek is initiated in the foreground so that + // the correct frame is displayed. If the pipeline is not suspended, Resume() + // will do nothing but clear some pending state. + if (delegate_ && !delegate_->IsHidden()) + pipeline_controller_.Resume(); } void WebMediaPlayerImpl::setRate(double rate) { @@ -635,23 +596,16 @@ if (ended_) return duration(); - // We know the current seek time better than pipeline: pipeline may processing - // an earlier seek before a pending seek has been started, or it might not yet - // have the current seek time returnable via GetMediaTime(). - if (seeking()) { - return pending_seek_ ? pending_seek_time_.InSecondsF() - : seek_time_.InSecondsF(); - } + if (seeking()) + return seek_time_.InSecondsF(); #if defined(OS_ANDROID) // WMPI_CAST - if (isRemote()) { + if (isRemote()) return cast_impl_.currentTime(); - } #endif - if (paused_) { + if (paused_) return paused_time_.InSecondsF(); - } return pipeline_.GetMediaTime().InSecondsF(); } @@ -850,6 +804,14 @@ base::saturated_cast<unsigned int>(init_data.size())); } +void WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated( + scoped_ptr<MediaTracks> tracks) { + // For MSE/chunk_demuxer case the media track updates are handled by + // WebSourceBufferImpl. + DCHECK(demuxer_.get()); + DCHECK(!chunk_demuxer_); +} + void WebMediaPlayerImpl::OnWaitingForDecryptionKey() { encrypted_client_->didBlockPlaybackWaitingForKey(); @@ -884,68 +846,16 @@ set_cdm_result_.reset(); } -void WebMediaPlayerImpl::OnPipelineSeeked(bool time_changed, - PipelineStatus status) { - DVLOG(1) << __FUNCTION__ << "(" << time_changed << ", " << status << ")"; - DCHECK(main_task_runner_->BelongsToCurrentThread()); - - if (status != PIPELINE_OK) { - OnPipelineError(status); - return; - } - - // Whether or not the seek was caused by a resume, we're not suspended now. - const bool was_resuming = resuming_; - resuming_ = false; - suspended_ = false; - - // If we we're resuming into the playing state, notify the delegate. - if (was_resuming && playback_rate_ > 0 && !paused_) - NotifyPlaybackStarted(); - - // If there is a pending suspend, the seek does not complete until after the - // next resume. - if (pending_suspend_) { - pending_suspend_ = false; - pending_time_change_ = time_changed; - Suspend(); - return; - } - - // Clear seek state. Note that if the seek was caused by a resume, then - // |seek_time_| is always set but |seeking_| is only set if there was a - // pending seek at the time. +void WebMediaPlayerImpl::OnPipelineSeeked(bool time_updated) { seeking_ = false; seek_time_ = base::TimeDelta(); - - if (pending_seek_) { - double pending_seek_seconds = pending_seek_time_.InSecondsF(); - pending_seek_ = false; - pending_seek_time_ = base::TimeDelta(); - seek(pending_seek_seconds); - return; - } - - // Update our paused time. if (paused_) - UpdatePausedTime(); - - should_notify_time_changed_ = time_changed; + paused_time_ = pipeline_.GetMediaTime(); + if (time_updated) + should_notify_time_changed_ = true; } -void WebMediaPlayerImpl::OnPipelineSuspended(PipelineStatus status) { - DVLOG(1) << __FUNCTION__ << "(" << status << ")"; - DCHECK(main_task_runner_->BelongsToCurrentThread()); - - if (status != PIPELINE_OK) { - OnPipelineError(status); - return; - } - - suspending_ = false; - if (delegate_) - delegate_->PlayerGone(delegate_id_); - +void WebMediaPlayerImpl::OnPipelineSuspended() { #if defined(OS_ANDROID) if (isRemote()) { scoped_refptr<VideoFrame> frame = cast_impl_.GetCastingBanner(); @@ -955,20 +865,27 @@ } #endif - if (pending_resume_ || pending_suspend_resume_cycle_) { - pending_resume_ = false; + if (delegate_) + delegate_->PlayerGone(delegate_id_); + + if (pending_suspend_resume_cycle_) { pending_suspend_resume_cycle_ = false; - Resume(); + pipeline_controller_.Resume(); return; } } +void WebMediaPlayerImpl::OnPipelineResumed() { + if (playback_rate_ > 0 && !paused_) + NotifyPlaybackStarted(); +} + void WebMediaPlayerImpl::OnPipelineEnded() { DVLOG(1) << __FUNCTION__; DCHECK(main_task_runner_->BelongsToCurrentThread()); - // Ignore state changes until we've completed all outstanding seeks. - if (seeking_ || pending_seek_) + // Ignore state changes until we've completed all outstanding operations. + if (!pipeline_controller_.IsStable()) return; ended_ = true; @@ -1032,8 +949,9 @@ BufferingState buffering_state) { DVLOG(1) << __FUNCTION__ << "(" << buffering_state << ")"; - // Ignore buffering state changes until we've completed all outstanding seeks. - if (seeking_ || pending_seek_) + // Ignore buffering state changes until we've completed all outstanding + // operations. + if (!pipeline_controller_.IsStable()) return; // TODO(scherkus): Handle other buffering states when Pipeline starts using @@ -1107,38 +1025,7 @@ #endif if (must_suspend || (paused_ && ended_) || hasVideo()) - ScheduleSuspend(); -} - -void WebMediaPlayerImpl::ScheduleSuspend() { - if (!pipeline_.IsRunning()) - return; - - if (resuming_ || seeking_) { - pending_suspend_ = true; - return; - } - - if (pending_resume_) { - pending_resume_ = false; - return; - } - - Suspend(); -} - -void WebMediaPlayerImpl::Suspend() { - DCHECK(main_task_runner_->BelongsToCurrentThread()); - - // Since Pipeline::IsRunning() may be set on the media thread there are cases - // where two suspends might be issued concurrently. - if (suspended_) - return; - - suspended_ = true; - suspending_ = true; - pipeline_.Suspend( - BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineSuspended)); + pipeline_controller_.Suspend(); } void WebMediaPlayerImpl::OnShown() { @@ -1164,26 +1051,7 @@ #endif if (!ended_ && !paused_) - ScheduleResume(); -} - -void WebMediaPlayerImpl::ScheduleResume() { - if (!pipeline_.IsRunning()) - return; - - if (suspending_) { - pending_resume_ = true; - return; - } - - if (pending_suspend_) { - pending_suspend_ = false; - return; - } - - // Might already be resuming iff we came back from remote playback recently. - if (suspended_ && !resuming_) - Resume(); + pipeline_controller_.Resume(); } void WebMediaPlayerImpl::OnPlay() { @@ -1201,57 +1069,14 @@ setVolume(volume_); } -void WebMediaPlayerImpl::Resume() { - DCHECK(main_task_runner_->BelongsToCurrentThread()); - CHECK(suspended_); - CHECK(!resuming_); - - // If there was a time change pending when we suspended (which can happen when - // we suspend immediately after a seek), surface it after resuming. - bool time_changed = pending_time_change_; - pending_time_change_ = false; - - if (seeking_ || pending_seek_) { - if (pending_seek_) { - seek_time_ = pending_seek_time_; - pending_seek_ = false; - pending_seek_time_ = base::TimeDelta(); - } - time_changed = true; - } else { - // It is safe to call GetCurrentFrameTimestamp() because VFC is stopped - // during Suspend(). It won't be started again until after Resume() is - // called. Use the pipeline time if there's no video. - if (!data_source_ || !data_source_->IsStreaming()) { - seek_time_ = hasVideo() ? compositor_->GetCurrentFrameTimestamp() - : pipeline_.GetMediaTime(); - } else { - // Resume from zero if a resource does not support range requests; this - // avoids a painful "read-the-whole-file" seek penalty. - seek_time_ = base::TimeDelta(); - } - } - - if (chunk_demuxer_) - chunk_demuxer_->StartWaitingForSeek(seek_time_); - - resuming_ = true; - pipeline_.Resume(CreateRenderer(), seek_time_, - BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, - time_changed)); -} - void WebMediaPlayerImpl::ScheduleRestart() { - // If we're suspended but not resuming there is no need to restart because - // there is no renderer to kill. - if (!suspended_ || resuming_) { + if (!pipeline_controller_.IsSuspended()) { pending_suspend_resume_cycle_ = true; - ScheduleSuspend(); + pipeline_controller_.Suspend(); } } #if defined(OS_ANDROID) // WMPI_CAST - bool WebMediaPlayerImpl::isRemote() const { return cast_impl_.isRemote(); } @@ -1278,28 +1103,26 @@ } void WebMediaPlayerImpl::OnDisconnectedFromRemoteDevice(double t) { - paused_time_ = base::TimeDelta::FromSecondsD(t); - pending_seek_ = true; - pending_seek_time_ = paused_time_; + DoSeek(base::TimeDelta::FromSecondsD(t), false); + if (delegate_ && !delegate_->IsHidden()) + pipeline_controller_.Resume(); - ScheduleResume(); - - if (paused_time_ == pipeline_.GetMediaDuration()) { - ended_ = true; - } // We already told the delegate we're paused when remoting started. client_->playbackStateChanged(); client_->disconnectedFromRemoteDevice(); } void WebMediaPlayerImpl::SuspendForRemote() { - if (suspended_ && !suspending_) { + if (!pipeline_controller_.IsSuspended()) { + pipeline_controller_.Suspend(); + } else { + // TODO(sandersd): If PipelineController::Suspend() called |suspended_cb| + // when already suspended, we wouldn't need this case. scoped_refptr<VideoFrame> frame = cast_impl_.GetCastingBanner(); if (frame) { compositor_->PaintFrameUsingOldRenderingPath(frame); } } - ScheduleSuspend(); } gfx::Size WebMediaPlayerImpl::GetCanvasSize() const { @@ -1390,8 +1213,13 @@ DCHECK(data_source_); #if !defined(MEDIA_DISABLE_FFMPEG) + Demuxer::MediaTracksUpdatedCB media_tracks_updated_cb = + base::Bind(&WebMediaPlayerImpl::OnFFmpegMediaTracksUpdated, + base::Unretained(this)); + demuxer_.reset(new FFmpegDemuxer(media_task_runner_, data_source_.get(), - encrypted_media_init_data_cb, media_log_)); + encrypted_media_init_data_cb, + media_tracks_updated_cb, media_log_)); #else OnPipelineError(PipelineStatus::DEMUXER_ERROR_COULD_NOT_OPEN); return; @@ -1410,11 +1238,10 @@ seeking_ = true; // TODO(sandersd): On Android, defer Start() if the tab is not visible. - pipeline_.Start( - demuxer_.get(), CreateRenderer(), + bool is_streaming = (data_source_ && data_source_->IsStreaming()); + pipeline_controller_.Start( + chunk_demuxer_, demuxer_.get(), is_streaming, BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded), - BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineError), - BIND_TO_RENDER_LOOP1(&WebMediaPlayerImpl::OnPipelineSeeked, false), BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineMetadata), BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineBufferingStateChanged), BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDurationChanged), @@ -1522,17 +1349,6 @@ return video_frame; } -void WebMediaPlayerImpl::UpdatePausedTime() { - DCHECK(main_task_runner_->BelongsToCurrentThread()); - - // pause() may be called after playback has ended and the HTMLMediaElement - // requires that currentTime() == duration() after ending. We want to ensure - // |paused_time_| matches currentTime() in this case or a future seek() may - // incorrectly discard what it thinks is a seek to the existing time. - paused_time_ = - ended_ ? pipeline_.GetMediaDuration() : pipeline_.GetMediaTime(); -} - void WebMediaPlayerImpl::NotifyPlaybackStarted() { #if defined(OS_ANDROID) // WMPI_CAST // We do not tell our delegates about remote playback, because that would @@ -1541,10 +1357,13 @@ return; #endif - // Don't send delegate notifications when suspended; upon suspend we send - // PlayerGone() to the delegate -- no more notifications should be sent until - // after resume. - if (suspended_) + // NotifyPlaybackStarted() may be called by interactions while suspended, + // (play/pause in particular). Those actions won't have any effect until the + // pipeline is resumed. + // TODO(dalecurtis): Should these be dropped at the call sites instead? + // Alternatively, rename this method to include Maybe or Changed, and handle + // multiple calls safely. + if (pipeline_controller_.IsSuspended()) return; if (delegate_) { @@ -1563,10 +1382,14 @@ if (isRemote()) return; #endif - // Don't send delegate notifications when suspended; upon suspend we send - // PlayerGone() to the delegate -- no more notifications should be sent until - // after resume. - if (!suspended_ && delegate_) + + // Same as above, NotifyPlaybackPaused() may be called by interactions while + // suspended, but those actions won't have any effect until the pipeline is + // resumed. + if (pipeline_controller_.IsSuspended()) + return; + + if (delegate_) delegate_->DidPause(delegate_id_, ended_); memory_usage_reporting_timer_.Stop(); ReportMemoryUsage();
diff --git a/media/blink/webmediaplayer_impl.h b/media/blink/webmediaplayer_impl.h index ec55ca1..5ae347c 100644 --- a/media/blink/webmediaplayer_impl.h +++ b/media/blink/webmediaplayer_impl.h
@@ -18,6 +18,7 @@ #include "base/memory/weak_ptr.h" #include "base/threading/thread.h" #include "build/build_config.h" +#include "media/base/media_tracks.h" #include "media/base/pipeline_impl.h" #include "media/base/renderer_factory.h" #include "media/base/surface_manager.h" @@ -30,6 +31,7 @@ #include "media/blink/webmediaplayer_delegate.h" #include "media/blink/webmediaplayer_params.h" #include "media/blink/webmediaplayer_util.h" +#include "media/filters/pipeline_controller.h" #include "media/renderers/skcanvas_video_renderer.h" #include "third_party/WebKit/public/platform/WebAudioSourceProvider.h" #include "third_party/WebKit/public/platform/WebContentDecryptionModuleResult.h" @@ -165,16 +167,6 @@ void enteredFullscreen() override; void exitedFullscreen() override; - void OnPipelineSeeked(bool time_changed, PipelineStatus status); - void OnPipelineSuspended(PipelineStatus status); - void OnPipelineEnded(); - void OnPipelineError(PipelineStatus error); - void OnPipelineMetadata(PipelineMetadata metadata); - void OnPipelineBufferingStateChanged(BufferingState buffering_state); - void OnDemuxerOpened(); - void OnAddTextTrack(const TextTrackConfig& config, - const AddTextTrackDoneCB& done_cb); - // WebMediaPlayerDelegate::Observer implementation. void OnHidden(bool must_suspend) override; void OnShown() override; @@ -198,20 +190,24 @@ void SetDeviceScaleFactor(float scale_factor); #endif + // Called from WebMediaPlayerCast. + // TODO(hubbe): WMPI_CAST make private. + void OnPipelineSeeked(bool time_updated); + private: - // Ask for the pipeline to be suspended, will call Suspend() when ready. - // (Possibly immediately.) - void ScheduleSuspend(); + void OnPipelineSuspended(); + void OnPipelineResumed(); + void OnPipelineEnded(); + void OnPipelineError(PipelineStatus error); + void OnPipelineMetadata(PipelineMetadata metadata); + void OnPipelineBufferingStateChanged(BufferingState buffering_state); + void OnDemuxerOpened(); + void OnAddTextTrack(const TextTrackConfig& config, + const AddTextTrackDoneCB& done_cb); - // Initiate suspending the pipeline. - void Suspend(); - - // Ask for the pipeline to be resumed, will call Resume() when ready. - // (Possibly immediately.) - void ScheduleResume(); - - // Initiate resuming the pipeline. - void Resume(); + // Actually seek. Avoids causing |should_notify_time_changed_| to be set when + // |time_updated| is false. + void DoSeek(base::TimeDelta time, bool time_updated); // Ask for the renderer to be restarted (destructed and recreated). void ScheduleRestart(); @@ -261,6 +257,11 @@ void OnEncryptedMediaInitData(EmeInitDataType init_data_type, const std::vector<uint8_t>& init_data); + // Called when the FFmpegDemuxer encounters new media tracks. This is only + // invoked when using FFmpegDemuxer, since MSE/ChunkDemuxer handle media + // tracks separately in WebSourceBufferImpl. + void OnFFmpegMediaTracksUpdated(scoped_ptr<MediaTracks> tracks); + // Called when a decoder detects that the key needed to decrypt the stream // is not available. void OnWaitingForDecryptionKey(); @@ -272,10 +273,6 @@ // Called when a CDM has been attached to the |pipeline_|. void OnCdmAttached(bool success); - // Updates |paused_time_| to the current media time with consideration for the - // |ended_| state by clamping current time to duration upon |ended_|. - void UpdatePausedTime(); - // Notifies |delegate_| that playback has started or was paused; also starts // or stops the memory usage reporting timer respectively. void NotifyPlaybackStarted(); @@ -308,7 +305,11 @@ scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_; scoped_refptr<base::TaskRunner> worker_task_runner_; scoped_refptr<MediaLog> media_log_; + + // |pipeline_controller_| references |pipeline_| and therefore must be + // constructed after and destructed before |pipeline_|. PipelineImpl pipeline_; + PipelineController pipeline_controller_; // The LoadType passed in the |load_type| parameter of the load() call. LoadType load_type_; @@ -332,32 +333,16 @@ // clock can creep forward a little bit while the asynchronous // SetPlaybackRate(0) is being executed. double playback_rate_; + + // Set while paused. |paused_time_| is only valid when |paused_| is true. bool paused_; base::TimeDelta paused_time_; + + // Set when starting, seeking, and resuming (all of which require a Pipeline + // seek). |seek_time_| is only valid when |seeking_| is true. bool seeking_; - - // Set when seeking (|seeking_| is true) or resuming. base::TimeDelta seek_time_; - // Set when a suspend is required but another suspend or seek is in progress. - bool pending_suspend_; - - // Set when suspending immediately after a seek. The time change will happen - // after Resume(). - bool pending_time_change_; - - // Set when a resume is required but suspending is in progress. - bool pending_resume_; - - // Set for the entire period between suspend starting and resume completing. - bool suspending_; - - // Set while suspending to detect double-suspend. - bool suspended_; - - // Set while resuming to detect double-resume. - bool resuming_; - // Set when doing a restart (a suspend and resume in sequence) of the pipeline // in order to destruct and reinitialize the decoders. This is separate from // |pending_resume_| and |pending_suspend_| because they can be elided in @@ -369,14 +354,6 @@ // see http://crbug.com/409280 bool ended_; - // Indicates that a seek is queued after the current seek completes or, if the - // pipeline is suspended, after it resumes. Only the last queued seek will - // have any effect. - bool pending_seek_; - - // |pending_seek_time_| is meaningless when |pending_seek_| is false. - base::TimeDelta pending_seek_time_; - // Tracks whether to issue time changed notifications during buffering state // changes. bool should_notify_time_changed_;
diff --git a/media/blink/webmediaplayer_util.cc b/media/blink/webmediaplayer_util.cc index 8b4f368..05342f0b 100644 --- a/media/blink/webmediaplayer_util.cc +++ b/media/blink/webmediaplayer_util.cc
@@ -12,6 +12,7 @@ #include "base/metrics/histogram.h" #include "media/base/bind_to_current_loop.h" #include "media/base/media_client.h" +#include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebMediaPlayerEncryptedMediaClient.h" namespace media { @@ -112,7 +113,7 @@ // MediaStream as well. void ReportMetrics(blink::WebMediaPlayer::LoadType load_type, const GURL& url, - const GURL& origin_url) { + const blink::WebSecurityOrigin& security_origin) { // Report URL scheme, such as http, https, file, blob etc. UMA_HISTOGRAM_ENUMERATION("Media.URLScheme", URLScheme(url), kMaxURLScheme + 1); @@ -123,8 +124,23 @@ // Report the origin from where the media player is created. if (GetMediaClient()) { + GURL security_origin_url( + blink::WebStringToGURL(security_origin.toString())); + GetMediaClient()->RecordRapporURL( - "Media.OriginUrl." + LoadTypeToString(load_type), origin_url); + "Media.OriginUrl." + LoadTypeToString(load_type), security_origin_url); + + // For MSE, also report usage by secure/insecure origin. + if (load_type == blink::WebMediaPlayer::LoadTypeMediaSource) { + blink::WebString error_message; + if (security_origin.isPotentiallyTrustworthy(error_message)) { + GetMediaClient()->RecordRapporURL("Media.OriginUrl.MSE.Secure", + security_origin_url); + } else { + GetMediaClient()->RecordRapporURL("Media.OriginUrl.MSE.Insecure", + security_origin_url); + } + } } }
diff --git a/media/blink/webmediaplayer_util.h b/media/blink/webmediaplayer_util.h index cb5c69b..bb8c049 100644 --- a/media/blink/webmediaplayer_util.h +++ b/media/blink/webmediaplayer_util.h
@@ -13,6 +13,7 @@ #include "media/blink/media_blink_export.h" #include "third_party/WebKit/public/platform/WebEncryptedMediaTypes.h" #include "third_party/WebKit/public/platform/WebMediaPlayer.h" +#include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebSetSinkIdCallbacks.h" #include "third_party/WebKit/public/platform/WebTimeRange.h" #include "url/gurl.h" @@ -26,9 +27,10 @@ PipelineErrorToNetworkState(PipelineStatus error); // Report various metrics to UMA and RAPPOR. -void MEDIA_BLINK_EXPORT ReportMetrics(blink::WebMediaPlayer::LoadType load_type, - const GURL& url, - const GURL& origin_url); +void MEDIA_BLINK_EXPORT +ReportMetrics(blink::WebMediaPlayer::LoadType load_type, + const GURL& url, + const blink::WebSecurityOrigin& security_origin); // Record a RAPPOR metric for the origin of an HLS playback. void MEDIA_BLINK_EXPORT RecordOriginOfHLSPlayback(const GURL& origin_url);
diff --git a/media/blink/websourcebuffer_impl.cc b/media/blink/websourcebuffer_impl.cc index ea09bde..6b08b131 100644 --- a/media/blink/websourcebuffer_impl.cc +++ b/media/blink/websourcebuffer_impl.cc
@@ -46,6 +46,9 @@ client_(NULL), append_window_end_(kInfiniteDuration()) { DCHECK(demuxer_); + demuxer_->SetTracksWatcher( + id, base::Bind(&WebSourceBufferImpl::InitSegmentReceived, + base::Unretained(this))); } WebSourceBufferImpl::~WebSourceBufferImpl() { @@ -99,11 +102,8 @@ unsigned length, double* timestamp_offset) { base::TimeDelta old_offset = timestamp_offset_; - demuxer_->AppendData(id_, data, length, - append_window_start_, append_window_end_, - ×tamp_offset_, - base::Bind(&WebSourceBufferImpl::InitSegmentReceived, - base::Unretained(this))); + demuxer_->AppendData(id_, data, length, append_window_start_, + append_window_end_, ×tamp_offset_); // Coded frame processing may update the timestamp offset. If the caller // provides a non-NULL |timestamp_offset| and frame processing changes the @@ -159,7 +159,7 @@ client_ = NULL; } -void WebSourceBufferImpl::InitSegmentReceived(const MediaTracks& tracks) { +void WebSourceBufferImpl::InitSegmentReceived(scoped_ptr<MediaTracks> tracks) { DVLOG(1) << __FUNCTION__; // TODO(servolk): Implement passing MediaTrack info to blink level. // https://crbug.com/249428
diff --git a/media/blink/websourcebuffer_impl.h b/media/blink/websourcebuffer_impl.h index 1dc54e6..b9b44049 100644 --- a/media/blink/websourcebuffer_impl.h +++ b/media/blink/websourcebuffer_impl.h
@@ -11,6 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/memory/scoped_ptr.h" #include "base/time/time.h" #include "third_party/WebKit/public/platform/WebSourceBuffer.h" @@ -43,7 +44,7 @@ private: // Demuxer callback handler to process an initialization segment received // during an append() call. - void InitSegmentReceived(const MediaTracks& tracks); + void InitSegmentReceived(scoped_ptr<MediaTracks> tracks); std::string id_; ChunkDemuxer* demuxer_; // Owned by WebMediaPlayerImpl.
diff --git a/media/filters/android/media_codec_audio_decoder.cc b/media/filters/android/media_codec_audio_decoder.cc index f23452a4..aa559cf 100644 --- a/media/filters/android/media_codec_audio_decoder.cc +++ b/media/filters/android/media_codec_audio_decoder.cc
@@ -507,9 +507,13 @@ // Copy data into AudioBuffer. CHECK_LE(out.size, audio_buffer->data_size()); - media_codec_->CopyFromOutputBuffer(out.buf_index, out.offset, - audio_buffer->channel_data()[0], - audio_buffer->data_size()); + MediaCodecStatus status = media_codec_->CopyFromOutputBuffer( + out.buf_index, out.offset, audio_buffer->channel_data()[0], + audio_buffer->data_size()); + // TODO(timav,watk): This CHECK maintains the behavior of this call before + // we started catching CodecException and returning it as MEDIA_CODEC_ERROR. + // It needs to be handled some other way. http://crbug.com/585978 + CHECK_EQ(status, MEDIA_CODEC_OK); // Release MediaCodec output buffer. media_codec_->ReleaseOutputBuffer(out.buf_index, false); @@ -521,9 +525,14 @@ void MediaCodecAudioDecoder::OnOutputFormatChanged() { DVLOG(2) << __FUNCTION__; - // We do not support the change of sampling rate on the fly - int new_sampling_rate = media_codec_->GetOutputSamplingRate(); - if (new_sampling_rate != config_.samples_per_second()) { + int new_sampling_rate; + MediaCodecStatus status = + media_codec_->GetOutputSamplingRate(&new_sampling_rate); + if (status != MEDIA_CODEC_OK) { + DVLOG(0) << "GetOutputSamplingRate failed."; + SetState(STATE_ERROR); + } else if (new_sampling_rate != config_.samples_per_second()) { + // We do not support the change of sampling rate on the fly DVLOG(0) << "Sampling rate change is not supported by" << GetDisplayName() << " (detected change " << config_.samples_per_second() << "->" << new_sampling_rate << ")";
diff --git a/media/filters/chunk_demuxer.cc b/media/filters/chunk_demuxer.cc index e931c3fd..40daf24 100644 --- a/media/filters/chunk_demuxer.cc +++ b/media/filters/chunk_demuxer.cc
@@ -549,6 +549,14 @@ return kOk; } +void ChunkDemuxer::SetTracksWatcher( + const std::string& id, + const MediaTracksUpdatedCB& tracks_updated_cb) { + base::AutoLock auto_lock(lock_); + CHECK(IsValidId(id)); + source_state_map_[id]->SetTracksWatcher(tracks_updated_cb); +} + void ChunkDemuxer::RemoveId(const std::string& id) { base::AutoLock auto_lock(lock_); CHECK(IsValidId(id)); @@ -596,19 +604,16 @@ return itr->second->EvictCodedFrames(media_time_dts, newDataSize); } -void ChunkDemuxer::AppendData( - const std::string& id, - const uint8_t* data, - size_t length, - TimeDelta append_window_start, - TimeDelta append_window_end, - TimeDelta* timestamp_offset, - const MediaSourceState::InitSegmentReceivedCB& init_segment_received_cb) { +void ChunkDemuxer::AppendData(const std::string& id, + const uint8_t* data, + size_t length, + TimeDelta append_window_start, + TimeDelta append_window_end, + TimeDelta* timestamp_offset) { DVLOG(1) << "AppendData(" << id << ", " << length << ")"; DCHECK(!id.empty()); DCHECK(timestamp_offset); - DCHECK(!init_segment_received_cb.is_null()); Ranges<TimeDelta> ranges; @@ -629,11 +634,9 @@ case INITIALIZING: case INITIALIZED: DCHECK(IsValidId(id)); - if (!source_state_map_[id]->Append(data, length, - append_window_start, + if (!source_state_map_[id]->Append(data, length, append_window_start, append_window_end, - timestamp_offset, - init_segment_received_cb)) { + timestamp_offset)) { ReportError_Locked(PIPELINE_ERROR_DECODE); return; }
diff --git a/media/filters/chunk_demuxer.h b/media/filters/chunk_demuxer.h index 2425412..73d1525 100644 --- a/media/filters/chunk_demuxer.h +++ b/media/filters/chunk_demuxer.h
@@ -221,6 +221,11 @@ Status AddId(const std::string& id, const std::string& type, std::vector<std::string>& codecs); + // Notifies a caller via |tracks_updated_cb| that the set of media tracks + // for a given |id| has changed. + void SetTracksWatcher(const std::string& id, + const MediaTracksUpdatedCB& tracks_updated_cb); + // Removed an ID & associated resources that were previously added with // AddId(). void RemoveId(const std::string& id); @@ -233,16 +238,12 @@ // |append_window_start| and |append_window_end| correspond to the MSE spec's // similarly named source buffer attributes that are used in coded frame // processing. - // |init_segment_received_cb| is run for each newly successfully parsed - // initialization segment. - void AppendData( - const std::string& id, - const uint8_t* data, - size_t length, - base::TimeDelta append_window_start, - base::TimeDelta append_window_end, - base::TimeDelta* timestamp_offset, - const MediaSourceState::InitSegmentReceivedCB& init_segment_received_cb); + void AppendData(const std::string& id, + const uint8_t* data, + size_t length, + base::TimeDelta append_window_start, + base::TimeDelta append_window_end, + base::TimeDelta* timestamp_offset); // Aborts parsing the current segment and reset the parser to a state where // it can accept a new segment.
diff --git a/media/filters/chunk_demuxer_unittest.cc b/media/filters/chunk_demuxer_unittest.cc index bd2a87e..e71751e 100644 --- a/media/filters/chunk_demuxer_unittest.cc +++ b/media/filters/chunk_demuxer_unittest.cc
@@ -263,9 +263,8 @@ ChunkDemuxerTest() : media_log_(new StrictMock<MockMediaLog>()), append_window_end_for_next_append_(kInfiniteDuration()) { - init_segment_received_cb_ = - base::Bind(&ChunkDemuxerTest::InitSegmentReceived, - base::Unretained(this)); + init_segment_received_cb_ = base::Bind( + &ChunkDemuxerTest::InitSegmentReceivedWrapper, base::Unretained(this)); CreateNewDemuxer(); } @@ -451,7 +450,12 @@ return AddId(kSourceId, HAS_AUDIO | HAS_VIDEO); } - return demuxer_->AddId(source_id, type, codecs); + ChunkDemuxer::Status status = demuxer_->AddId(source_id, type, codecs); + if (status == ChunkDemuxer::kOk) + demuxer_->SetTracksWatcher( + source_id, base::Bind(&ChunkDemuxerTest::InitSegmentReceivedWrapper, + base::Unretained(this))); + return status; } #if BUILDFLAG(ENABLE_MSE_MPEG2TS_STREAM_PARSER) @@ -460,7 +464,12 @@ std::string type = "video/mp2t"; codecs.push_back("mp4a.40.2"); codecs.push_back("avc1.640028"); - return demuxer_->AddId(source_id, type, codecs); + ChunkDemuxer::Status status = demuxer_->AddId(source_id, type, codecs); + if (status == ChunkDemuxer::kOk) + demuxer_->SetTracksWatcher( + source_id, base::Bind(&ChunkDemuxerTest::InitSegmentReceivedWrapper, + base::Unretained(this))); + return status; } #endif @@ -715,11 +724,9 @@ size_t length) { EXPECT_CALL(host_, OnBufferedTimeRangesChanged(_)).Times(AnyNumber()); - demuxer_->AppendData(source_id, data, length, - append_window_start_for_next_append_, - append_window_end_for_next_append_, - ×tamp_offset_map_[source_id], - init_segment_received_cb_); + demuxer_->AppendData( + source_id, data, length, append_window_start_for_next_append_, + append_window_end_for_next_append_, ×tamp_offset_map_[source_id]); } void AppendDataInPieces(const uint8_t* data, size_t length) { @@ -1346,7 +1353,7 @@ void(EmeInitDataType init_data_type, const std::vector<uint8_t>& init_data)); - MOCK_METHOD1(InitSegmentReceived, void(const MediaTracks&)); + MOCK_METHOD1(InitSegmentReceived, void(scoped_ptr<MediaTracks>&)); void Seek(base::TimeDelta seek_time) { demuxer_->StartWaitingForSeek(seek_time); @@ -1374,7 +1381,7 @@ scoped_refptr<StrictMock<MockMediaLog>> media_log_; scoped_ptr<ChunkDemuxer> demuxer_; - MediaSourceState::InitSegmentReceivedCB init_segment_received_cb_; + Demuxer::MediaTracksUpdatedCB init_segment_received_cb_; base::TimeDelta append_window_start_for_next_append_; base::TimeDelta append_window_end_for_next_append_; @@ -1383,6 +1390,12 @@ // operation for that source id. std::map<std::string, base::TimeDelta> timestamp_offset_map_; + public: + // A workaround for gtest mocks not allowing moving scoped_ptrs. + void InitSegmentReceivedWrapper(scoped_ptr<MediaTracks> tracks) { + InitSegmentReceived(tracks); + } + private: DISALLOW_COPY_AND_ASSIGN(ChunkDemuxerTest); }; @@ -1552,8 +1565,7 @@ demuxer_->AppendData(kSourceId, info_tracks.get(), info_tracks_size, append_window_start_for_next_append_, append_window_end_for_next_append_, - ×tamp_offset_map_[kSourceId], - init_segment_received_cb_); + ×tamp_offset_map_[kSourceId]); AppendMuxedCluster( MuxedStreamInfo(kAudioTrackNum, "46K 69K", 23), @@ -1746,8 +1758,7 @@ demuxer_->AppendData(kSourceId, info_tracks.get(), info_tracks_size, append_window_start_for_next_append_, append_window_end_for_next_append_, - ×tamp_offset_map_[kSourceId], - init_segment_received_cb_); + ×tamp_offset_map_[kSourceId]); } // Make sure Read() callbacks are dispatched with the proper data. @@ -1786,8 +1797,7 @@ demuxer_->AppendData(kSourceId, cluster_c->data(), cluster_c->size(), append_window_start_for_next_append_, append_window_end_for_next_append_, - ×tamp_offset_map_[kSourceId], - init_segment_received_cb_); + ×tamp_offset_map_[kSourceId]); } TEST_F(ChunkDemuxerTest, NonMonotonicButAboveClusterTimecode) { @@ -1814,8 +1824,7 @@ demuxer_->AppendData(kSourceId, cluster_b->data(), cluster_b->size(), append_window_start_for_next_append_, append_window_end_for_next_append_, - ×tamp_offset_map_[kSourceId], - init_segment_received_cb_); + ×tamp_offset_map_[kSourceId]); } TEST_F(ChunkDemuxerTest, BackwardsAndBeforeClusterTimecode) { @@ -1842,8 +1851,7 @@ demuxer_->AppendData(kSourceId, cluster_b->data(), cluster_b->size(), append_window_start_for_next_append_, append_window_end_for_next_append_, - ×tamp_offset_map_[kSourceId], - init_segment_received_cb_); + ×tamp_offset_map_[kSourceId]); } @@ -2332,11 +2340,9 @@ EXPECT_MEDIA_LOG(StreamParsingFailed()); uint8_t tmp = 0; - demuxer_->AppendData(kSourceId, &tmp, 1, - append_window_start_for_next_append_, + demuxer_->AppendData(kSourceId, &tmp, 1, append_window_start_for_next_append_, append_window_end_for_next_append_, - ×tamp_offset_map_[kSourceId], - init_segment_received_cb_); + ×tamp_offset_map_[kSourceId]); } TEST_F(ChunkDemuxerTest, AVHeadersWithAudioOnlyType) { @@ -2349,6 +2355,9 @@ codecs[0] = "vorbis"; ASSERT_EQ(demuxer_->AddId(kSourceId, "audio/webm", codecs), ChunkDemuxer::kOk); + demuxer_->SetTracksWatcher( + kSourceId, base::Bind(&ChunkDemuxerTest::InitSegmentReceivedWrapper, + base::Unretained(this))); // Video track is unexpected per mimetype. EXPECT_MEDIA_LOG(InitSegmentMismatchesMimeType("a video", true)); @@ -2366,6 +2375,9 @@ codecs[0] = "vp8"; ASSERT_EQ(demuxer_->AddId(kSourceId, "video/webm", codecs), ChunkDemuxer::kOk); + demuxer_->SetTracksWatcher( + kSourceId, base::Bind(&ChunkDemuxerTest::InitSegmentReceivedWrapper, + base::Unretained(this))); // Audio track is unexpected per mimetype. EXPECT_MEDIA_LOG(InitSegmentMismatchesMimeType("an audio", true)); @@ -2383,6 +2395,9 @@ codecs[1] = "vp8"; ASSERT_EQ(demuxer_->AddId(kSourceId, "video/webm", codecs), ChunkDemuxer::kOk); + demuxer_->SetTracksWatcher( + kSourceId, base::Bind(&ChunkDemuxerTest::InitSegmentReceivedWrapper, + base::Unretained(this))); // Video track is also expected per mimetype. EXPECT_MEDIA_LOG(InitSegmentMismatchesMimeType("a video", false)); @@ -2400,6 +2415,9 @@ codecs[1] = "vp8"; ASSERT_EQ(demuxer_->AddId(kSourceId, "video/webm", codecs), ChunkDemuxer::kOk); + demuxer_->SetTracksWatcher( + kSourceId, base::Bind(&ChunkDemuxerTest::InitSegmentReceivedWrapper, + base::Unretained(this))); // Audio track is also expected per mimetype. EXPECT_MEDIA_LOG(InitSegmentMismatchesMimeType("an audio", false));
diff --git a/media/filters/ffmpeg_demuxer.cc b/media/filters/ffmpeg_demuxer.cc index 20adebe9..9472e18 100644 --- a/media/filters/ffmpeg_demuxer.cc +++ b/media/filters/ffmpeg_demuxer.cc
@@ -740,6 +740,7 @@ const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, DataSource* data_source, const EncryptedMediaInitDataCB& encrypted_media_init_data_cb, + const MediaTracksUpdatedCB& media_tracks_updated_cb, const scoped_refptr<MediaLog>& media_log) : host_(NULL), task_runner_(task_runner), @@ -755,9 +756,11 @@ text_enabled_(false), duration_known_(false), encrypted_media_init_data_cb_(encrypted_media_init_data_cb), + media_tracks_updated_cb_(media_tracks_updated_cb), weak_factory_(this) { DCHECK(task_runner_.get()); DCHECK(data_source_); + DCHECK(!media_tracks_updated_cb_.is_null()); } FFmpegDemuxer::~FFmpegDemuxer() {}
diff --git a/media/filters/ffmpeg_demuxer.h b/media/filters/ffmpeg_demuxer.h index 9bad5ff..dbaaea2 100644 --- a/media/filters/ffmpeg_demuxer.h +++ b/media/filters/ffmpeg_demuxer.h
@@ -190,6 +190,7 @@ FFmpegDemuxer(const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, DataSource* data_source, const EncryptedMediaInitDataCB& encrypted_media_init_data_cb, + const MediaTracksUpdatedCB& media_tracks_updated_cb, const scoped_refptr<MediaLog>& media_log); ~FFmpegDemuxer() override; @@ -329,6 +330,8 @@ const EncryptedMediaInitDataCB encrypted_media_init_data_cb_; + const MediaTracksUpdatedCB media_tracks_updated_cb_; + // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<FFmpegDemuxer> weak_factory_;
diff --git a/media/filters/ffmpeg_demuxer_unittest.cc b/media/filters/ffmpeg_demuxer_unittest.cc index a0611e9..a6b82e22 100644 --- a/media/filters/ffmpeg_demuxer_unittest.cc +++ b/media/filters/ffmpeg_demuxer_unittest.cc
@@ -17,6 +17,7 @@ #include "base/threading/thread.h" #include "media/base/decrypt_config.h" #include "media/base/media_log.h" +#include "media/base/media_tracks.h" #include "media/base/mock_demuxer_host.h" #include "media/base/test_helpers.h" #include "media/base/timestamp_constants.h" @@ -91,9 +92,12 @@ Demuxer::EncryptedMediaInitDataCB encrypted_media_init_data_cb = base::Bind( &FFmpegDemuxerTest::OnEncryptedMediaInitData, base::Unretained(this)); + Demuxer::MediaTracksUpdatedCB tracks_updated_cb = base::Bind( + &FFmpegDemuxerTest::OnMediaTracksUpdated, base::Unretained(this)); + demuxer_.reset(new FFmpegDemuxer( message_loop_.task_runner(), data_source_.get(), - encrypted_media_init_data_cb, new MediaLog())); + encrypted_media_init_data_cb, tracks_updated_cb, new MediaLog())); } MOCK_METHOD1(CheckPoint, void(int v)); @@ -204,6 +208,8 @@ void(EmeInitDataType init_data_type, const std::vector<uint8_t>& init_data)); + void OnMediaTracksUpdated(scoped_ptr<MediaTracks> tracks) {} + // Accessor to demuxer internals. void set_duration_known(bool duration_known) { demuxer_->duration_known_ = duration_known;
diff --git a/media/filters/media_source_state.cc b/media/filters/media_source_state.cc index 8f2f87c..89d488e 100644 --- a/media/filters/media_source_state.cc +++ b/media/filters/media_source_state.cc
@@ -145,21 +145,24 @@ frame_processor_->SetGroupStartTimestampIfInSequenceMode(timestamp_offset); } -bool MediaSourceState::Append( - const uint8_t* data, - size_t length, - TimeDelta append_window_start, - TimeDelta append_window_end, - TimeDelta* timestamp_offset, - const InitSegmentReceivedCB& init_segment_received_cb) { +void MediaSourceState::SetTracksWatcher( + const Demuxer::MediaTracksUpdatedCB& tracks_updated_cb) { + DCHECK(init_segment_received_cb_.is_null()); + init_segment_received_cb_ = tracks_updated_cb; + DCHECK(!init_segment_received_cb_.is_null()); +} + +bool MediaSourceState::Append(const uint8_t* data, + size_t length, + TimeDelta append_window_start, + TimeDelta append_window_end, + TimeDelta* timestamp_offset) { + append_in_progress_ = true; DCHECK(timestamp_offset); DCHECK(!timestamp_offset_during_append_); - DCHECK(!init_segment_received_cb.is_null()); - DCHECK(init_segment_received_cb_.is_null()); append_window_start_during_append_ = append_window_start; append_window_end_during_append_ = append_window_end; timestamp_offset_during_append_ = timestamp_offset; - init_segment_received_cb_ = init_segment_received_cb; // TODO(wolenetz/acolwell): Curry and pass a NewBuffersCB here bound with // append window and timestamp offset pointer. See http://crbug.com/351454. @@ -172,7 +175,7 @@ << " append_window_end=" << append_window_end.InSecondsF(); } timestamp_offset_during_append_ = NULL; - init_segment_received_cb_.Reset(); + append_in_progress_ = false; return result; } @@ -480,7 +483,9 @@ DVLOG(1) << "OnNewConfigs(" << allow_audio << ", " << allow_video << ", " << audio_config.IsValidConfig() << ", " << video_config.IsValidConfig() << ")"; - DCHECK(!init_segment_received_cb_.is_null()); + // MSE spec allows new configs to be emitted only during Append, but not + // during Flush or parser reset operations. + CHECK(append_in_progress_); if (!audio_config.IsValidConfig() && !video_config.IsValidConfig()) { DVLOG(1) << "OnNewConfigs() : Audio & video config are not valid!"; @@ -643,8 +648,10 @@ frame_processor_->SetAllTrackBuffersNeedRandomAccessPoint(); DVLOG(1) << "OnNewConfigs() : " << (success ? "success" : "failed"); - if (success) - init_segment_received_cb_.Run(*media_tracks_); + if (success) { + DCHECK(!init_segment_received_cb_.is_null()); + init_segment_received_cb_.Run(std::move(media_tracks_)); + } return success; }
diff --git a/media/filters/media_source_state.h b/media/filters/media_source_state.h index 1197015..e6878f6 100644 --- a/media/filters/media_source_state.h +++ b/media/filters/media_source_state.h
@@ -28,8 +28,6 @@ typedef base::Callback<ChunkDemuxerStream*(DemuxerStream::Type)> CreateDemuxerStreamCB; - typedef base::Callback<void(const MediaTracks&)> InitSegmentReceivedCB; - typedef base::Callback<void(ChunkDemuxerStream*, const TextTrackConfig&)> NewTextTrackCB; @@ -52,14 +50,12 @@ // error occurred. |*timestamp_offset| is used and possibly updated by the // append. |append_window_start| and |append_window_end| correspond to the MSE // spec's similarly named source buffer attributes that are used in coded - // frame processing. |init_segment_received_cb| is run for each new fully - // parsed initialization segment. + // frame processing. bool Append(const uint8_t* data, size_t length, TimeDelta append_window_start, TimeDelta append_window_end, - TimeDelta* timestamp_offset, - const InitSegmentReceivedCB& init_segment_received_cb); + TimeDelta* timestamp_offset); // Aborts the current append sequence and resets the parser. void ResetParserState(TimeDelta append_window_start, @@ -117,6 +113,8 @@ const RangesList& activeRanges, bool ended); + void SetTracksWatcher(const Demuxer::MediaTracksUpdatedCB& tracks_updated_cb); + private: // Called by the |stream_parser_| when a new initialization segment is // encountered. @@ -195,11 +193,13 @@ StreamParser::InitCB init_cb_; // During Append(), OnNewConfigs() will trigger the initialization segment - // received algorithm. This callback is only non-NULL during the lifetime of - // an Append() call. Note, the MSE spec explicitly disallows this algorithm + // received algorithm. Note, the MSE spec explicitly disallows this algorithm // during an Abort(), since Abort() is allowed only to emit coded frames, and - // only if the parser is PARSING_MEDIA_SEGMENT (not an INIT segment). - InitSegmentReceivedCB init_segment_received_cb_; + // only if the parser is PARSING_MEDIA_SEGMENT (not an INIT segment). So we + // also have a flag here that indicates if Append is in progress and we can + // invoke this callback. + Demuxer::MediaTracksUpdatedCB init_segment_received_cb_; + bool append_in_progress_ = false; // Indicates that timestampOffset should be updated automatically during // OnNewBuffers() based on the earliest end timestamp of the buffers provided.
diff --git a/media/filters/pipeline_controller.cc b/media/filters/pipeline_controller.cc new file mode 100644 index 0000000..1e218f9 --- /dev/null +++ b/media/filters/pipeline_controller.cc
@@ -0,0 +1,268 @@ +// 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 "media/filters/pipeline_controller.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "media/base/bind_to_current_loop.h" +#include "media/filters/chunk_demuxer.h" + +namespace media { + +PipelineController::PipelineController( + Pipeline* pipeline, + const RendererFactoryCB& renderer_factory_cb, + const SeekedCB& seeked_cb, + const SuspendedCB& suspended_cb, + const ResumedCB& resumed_cb, + const PipelineStatusCB& error_cb) + : pipeline_(pipeline), + renderer_factory_cb_(renderer_factory_cb), + seeked_cb_(seeked_cb), + suspended_cb_(suspended_cb), + resumed_cb_(resumed_cb), + error_cb_(error_cb), + weak_factory_(this) { + DCHECK(pipeline_); + DCHECK(!renderer_factory_cb_.is_null()); + DCHECK(!seeked_cb_.is_null()); + DCHECK(!suspended_cb_.is_null()); + DCHECK(!resumed_cb_.is_null()); + DCHECK(!error_cb_.is_null()); +} + +PipelineController::~PipelineController() { + DCHECK(thread_checker_.CalledOnValidThread()); +} + +// TODO(sandersd): Move ChunkDemuxer API to Demuxer so that Pipeline can +// implement all of this. +// TODO(sandersd): If there is a pending suspend, don't call pipeline_.Start() +// until Resume(). +void PipelineController::Start( + ChunkDemuxer* chunk_demuxer, + Demuxer* demuxer, + bool is_streaming, + const base::Closure& ended_cb, + const PipelineMetadataCB& metadata_cb, + const BufferingStateCB& buffering_state_cb, + const base::Closure& duration_change_cb, + const AddTextTrackCB& add_text_track_cb, + const base::Closure& waiting_for_decryption_key_cb) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(state_ == State::CREATED); + + if (chunk_demuxer) + DCHECK_EQ(demuxer, chunk_demuxer); + + // Once the pipeline is started, we want to call the seeked callback but + // without a time update. + pending_seeked_cb_ = true; + state_ = State::STARTING; + + chunk_demuxer_ = chunk_demuxer; + is_streaming_ = is_streaming; + pipeline_->Start( + demuxer, renderer_factory_cb_.Run(), ended_cb, + BindToCurrentLoop(error_cb_), + BindToCurrentLoop(base::Bind(&PipelineController::OnPipelineStatus, + weak_factory_.GetWeakPtr(), State::PLAYING)), + metadata_cb, buffering_state_cb, duration_change_cb, add_text_track_cb, + waiting_for_decryption_key_cb); +} + +void PipelineController::Seek(base::TimeDelta time, bool time_updated) { + DCHECK(thread_checker_.CalledOnValidThread()); + + // It would be slightly more clear to set this in Dispatch(), but we want to + // be sure it gets updated even if the seek is elided. + if (time_updated) + pending_time_updated_ = true; + pending_seeked_cb_ = true; + + // If we are already seeking to |time|, just clear any pending seek. This does + // not apply to MSE because the underlying buffer could have been changed + // between the seek calls. + // TODO(sandersd): The underlying buffer could also have changed for + // File objects, but WMPI is also broken in that case (because it caches). + if ((state_ == State::SEEKING || state_ == State::RESUMING) && + seek_time_ == time && !chunk_demuxer_) { + pending_seek_ = false; + return; + } + + pending_seek_time_ = time; + pending_seek_ = true; + Dispatch(); +} + +// TODO(sandersd): It may be easier to use this interface if |suspended_cb_| is +// executed when Suspend() is called while already suspended. +void PipelineController::Suspend() { + DCHECK(thread_checker_.CalledOnValidThread()); + pending_resume_ = false; + if (state_ != State::SUSPENDING && state_ != State::SUSPENDED) { + pending_suspend_ = true; + Dispatch(); + } +} + +void PipelineController::Resume() { + DCHECK(thread_checker_.CalledOnValidThread()); + pending_suspend_ = false; + if (state_ == State::SUSPENDING || state_ == State::SUSPENDED) { + pending_resume_ = true; + Dispatch(); + } +} + +bool PipelineController::IsStable() { + DCHECK(thread_checker_.CalledOnValidThread()); + return (state_ == State::PLAYING); +} + +bool PipelineController::IsSuspended() { + DCHECK(thread_checker_.CalledOnValidThread()); + return (state_ == State::SUSPENDED); +} + +void PipelineController::OnPipelineStatus(State state, + PipelineStatus pipeline_status) { + DCHECK(thread_checker_.CalledOnValidThread()); + + if (pipeline_status != PIPELINE_OK) { + error_cb_.Run(pipeline_status); + return; + } + + state_ = state; + + if (state == State::PLAYING) { + // Start(), Seek(), or Resume() completed; we can be sure that + // |chunk_demuxer_| got the seek it was waiting for. + waiting_for_seek_ = false; + if (pending_resumed_cb_) { + pending_resumed_cb_ = false; + + // Warning: possibly reentrant. The state may change inside this callback. + // It must be safe to call Dispatch() twice in a row here. + resumed_cb_.Run(); + } + } else if (state == State::SUSPENDED) { + pending_resumed_cb_ = true; + + // Warning: possibly reentrant. The state may change inside this callback. + // It must be safe to call Dispatch() twice in a row here. + suspended_cb_.Run(); + } + + Dispatch(); +} + +// Note: Dispatch() may be called re-entrantly (by callbacks internally) or +// twice in a row (by OnPipelineStatus()). +void PipelineController::Dispatch() { + DCHECK(thread_checker_.CalledOnValidThread()); + + // Suspend/resume transitions take priority because seeks before a suspend + // are wasted, and seeks after can be merged into the resume operation. + if (pending_suspend_ && state_ == State::PLAYING) { + pending_suspend_ = false; + state_ = State::SUSPENDING; + pipeline_->Suspend(BindToCurrentLoop( + base::Bind(&PipelineController::OnPipelineStatus, + weak_factory_.GetWeakPtr(), State::SUSPENDED))); + return; + } + + if (pending_resume_ && state_ == State::SUSPENDED) { + // If there is a pending seek, resume to that time instead... + if (pending_seek_) { + seek_time_ = pending_seek_time_; + pending_seek_ = false; + } else { + seek_time_ = pipeline_->GetMediaTime(); + } + + // ...unless the media is streaming, in which case we resume at the start + // because seeking doesn't work well. + if (is_streaming_ && !seek_time_.is_zero()) { + seek_time_ = base::TimeDelta(); + + // In this case we want to make sure that the controls get updated + // immediately, so we don't try to hide the seek. + pending_time_updated_ = true; + } + + // Tell |chunk_demuxer_| to expect our resume. + if (chunk_demuxer_) { + DCHECK(!waiting_for_seek_); + chunk_demuxer_->StartWaitingForSeek(seek_time_); + waiting_for_seek_ = true; + } + + pending_resume_ = false; + state_ = State::RESUMING; + pipeline_->Resume(renderer_factory_cb_.Run(), seek_time_, + BindToCurrentLoop(base::Bind( + &PipelineController::OnPipelineStatus, + weak_factory_.GetWeakPtr(), State::PLAYING))); + return; + } + + // |chunk_demuxer_| supports aborting seeks. Make use of that when we have + // other pending operations. + if ((pending_seek_ || pending_suspend_) && waiting_for_seek_) { + CHECK(chunk_demuxer_); + + // If there is no pending seek, return the current seek to pending status. + if (!pending_seek_) { + pending_seek_time_ = seek_time_; + pending_seek_ = true; + } + + // CancelPendingSeek() may be reentrant, so update state first and return + // immediately. + waiting_for_seek_ = false; + chunk_demuxer_->CancelPendingSeek(pending_seek_time_); + return; + } + + // Ordinary seeking. + if (pending_seek_ && state_ == State::PLAYING) { + seek_time_ = pending_seek_time_; + + // Tell |chunk_demuxer_| to expect our seek. + if (chunk_demuxer_) { + DCHECK(!waiting_for_seek_); + waiting_for_seek_ = true; + chunk_demuxer_->StartWaitingForSeek(seek_time_); + } + + pending_seek_ = false; + state_ = State::SEEKING; + pipeline_->Seek(seek_time_, + BindToCurrentLoop(base::Bind( + &PipelineController::OnPipelineStatus, + weak_factory_.GetWeakPtr(), State::PLAYING))); + return; + } + + // If |state_| is PLAYING and we didn't trigger an operation above then we + // are in a stable state. If there is a seeked callback pending, emit it. + if (state_ == State::PLAYING) { + if (pending_seeked_cb_) { + // |seeked_cb_| may be reentrant, so update state first and return + // immediately. + pending_seeked_cb_ = false; + bool was_pending_time_updated = pending_time_updated_; + pending_time_updated_ = false; + seeked_cb_.Run(was_pending_time_updated); + return; + } + } +} + +} // namespace media
diff --git a/media/filters/pipeline_controller.h b/media/filters/pipeline_controller.h new file mode 100644 index 0000000..3491bd2 --- /dev/null +++ b/media/filters/pipeline_controller.h
@@ -0,0 +1,177 @@ +// 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 MEDIA_FILTERS_PIPELINE_CONTROLLER_H_ +#define MEDIA_FILTERS_PIPELINE_CONTROLLER_H_ + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/threading/thread_checker.h" +#include "base/time/time.h" +#include "media/base/media_export.h" +#include "media/base/pipeline.h" +#include "media/base/renderer.h" + +namespace media { + +class ChunkDemuxer; +class Demuxer; + +// PipelineController wraps a Pipeline to expose the one-at-a-time operations +// (Seek(), Suspend(), and Resume()) with a simpler API. Internally it tracks +// pending operations and dispatches them when possible. Duplicate requests +// (such as seeking twice to the same time) may be elided. +// +// TODO(sandersd): +// - Expose an operation that restarts via suspend+resume. +// - Block invalid calls after an error occurs. +class MEDIA_EXPORT PipelineController { + public: + enum class State { + CREATED, + STARTING, + PLAYING, + SEEKING, + SUSPENDING, + SUSPENDED, + RESUMING, + }; + + using RendererFactoryCB = base::Callback<scoped_ptr<Renderer>(void)>; + using SeekedCB = base::Callback<void(bool time_updated)>; + using SuspendedCB = base::Callback<void()>; + using ResumedCB = base::Callback<void()>; + + // Construct a PipelineController wrapping |pipeline_|. |pipeline_| must + // outlive the resulting PipelineController. The callbacks are: + // - |renderer_factory_cb| is called by PipelineController to create new + // renderers when starting and resuming. + // - |seeked_cb| is called upon reaching a stable state if a seek occured. + // - |suspended_cb| is called immediately after suspendeding. + // - |resumed_cb| is called immediately after resuming. + // - |error_cb| is called if any operation on |pipeline_| does not result + // in PIPELINE_OK or its error callback is called. + PipelineController(Pipeline* pipeline, + const RendererFactoryCB& renderer_factory_cb, + const SeekedCB& seeked_cb, + const SuspendedCB& suspended_cb, + const ResumedCB& resumed_cb, + const PipelineStatusCB& error_cb); + ~PipelineController(); + + // Start |pipeline_|. If provided, |chunk_demuxer| will be stored and + // StartWaitingForSeek()/CancelPendingSeek() will be issued to it as + // necessary. + // + // When |is_streaming| is true, Resume() will always start at the + // beginning of the stream, rather than attempting to seek to the current + // time. + // + // The other parameters are just passed directly to pipeline_.Start(). + void Start(ChunkDemuxer* chunk_demuxer, + Demuxer* demuxer, + bool is_streaming, + const base::Closure& ended_cb, + const PipelineMetadataCB& metadata_cb, + const BufferingStateCB& buffering_state_cb, + const base::Closure& duration_change_cb, + const AddTextTrackCB& add_text_track_cb, + const base::Closure& waiting_for_decryption_key_cb); + + // Request a seek to |time|. If |time_updated| is true, then the eventual + // |seeked_cb| callback will also have |time_updated| set to true; it + // indicates that the seek was requested by Blink and a time update is + // expected so that Blink can fire the seeked event. + void Seek(base::TimeDelta time, bool time_updated); + + // Request that |pipeline_| be suspended. This is a no-op if |pipeline_| has + // been suspended. + void Suspend(); + + // Request that |pipeline_| be resumed. This is a no-op if |pipeline_| has not + // been suspended. + void Resume(); + + // Returns true if the current state is stable. This means that |state_| is + // PLAYING and there are no pending operations. Requests are processed + // immediately when the state is stable, otherwise they are queued. + // + // Exceptions to the above: + // - Start() is processed immediately while in the CREATED state. + // - Resume() is processed immediately while in the SUSPENDED state. + bool IsStable(); + + // Returns true if |pipeline_| is suspended. + bool IsSuspended(); + + private: + // Attempts to make progress from the current state to the target state. + void Dispatch(); + + // PipelineStaus callback that also carries the target state. + void OnPipelineStatus(State state, PipelineStatus pipeline_status); + + // The Pipeline we are managing state for. + Pipeline* pipeline_ = nullptr; + + // Factory for Renderers, used for Start() and Resume(). + RendererFactoryCB renderer_factory_cb_; + + // Called after seeks (which includes Start()) upon reaching a stable state. + // Multiple seeks result in only one callback if no stable state occurs + // between them. + SeekedCB seeked_cb_; + + // Called immediately when |pipeline_| completes a suspend operation. + SuspendedCB suspended_cb_; + + // Called immediately when |pipeline_| completes a resume operation. + ResumedCB resumed_cb_; + + // Called immediately when any operation on |pipeline_| results in an error. + PipelineStatusCB error_cb_; + + // State for handling StartWaitingForSeek()/CancelPendingSeek(). + ChunkDemuxer* chunk_demuxer_ = nullptr; + bool waiting_for_seek_ = false; + + // When true, Resume() will start at time zero instead of seeking to the + // current time. + bool is_streaming_ = false; + + // Tracks the current state of |pipeline_|. + State state_ = State::CREATED; + + // Indicates that a seek has occurred. When set, a seeked callback will be + // issued at the next stable state. + bool pending_seeked_cb_ = false; + + // Indicates that time has been changed by a seek, which will be reported at + // the next seeked callback. + bool pending_time_updated_ = false; + + // Indicates that the |pipeline_| was suspended, and therefore that a resumed + // callback should be issued the next time we enter State::PLAYING. + bool pending_resumed_cb_ = false; + + // The target time of the active seek; valid while SEEKING or RESUMING. + base::TimeDelta seek_time_; + + // Target state which we will work to achieve. |pending_seek_time_| is only + // valid when |pending_seek_| is true. + bool pending_seek_ = false; + base::TimeDelta pending_seek_time_; + bool pending_suspend_ = false; + bool pending_resume_ = false; + + base::ThreadChecker thread_checker_; + base::WeakPtrFactory<PipelineController> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(PipelineController); +}; + +} // namespace media + +#endif // MEDIA_FILTERS_PIPELINE_CONTROLLER_H_
diff --git a/media/filters/pipeline_controller_unittest.cc b/media/filters/pipeline_controller_unittest.cc new file mode 100644 index 0000000..561c7b0 --- /dev/null +++ b/media/filters/pipeline_controller_unittest.cc
@@ -0,0 +1,212 @@ +// 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 "base/bind.h" +#include "base/bind_helpers.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop/message_loop.h" +#include "base/time/time.h" +#include "media/base/mock_filters.h" +#include "media/base/pipeline.h" +#include "media/filters/pipeline_controller.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::_; +using ::testing::DoAll; +using ::testing::Mock; +using ::testing::Return; +using ::testing::SaveArg; +using ::testing::StrictMock; + +namespace media { + +class PipelineControllerTest : public ::testing::Test { + public: + PipelineControllerTest() + : pipeline_controller_(&pipeline_, + base::Bind(&PipelineControllerTest::CreateRenderer, + base::Unretained(this)), + base::Bind(&PipelineControllerTest::OnSeeked, + base::Unretained(this)), + base::Bind(&PipelineControllerTest::OnSuspended, + base::Unretained(this)), + base::Bind(&PipelineControllerTest::OnResumed, + base::Unretained(this)), + base::Bind(&PipelineControllerTest::OnError, + base::Unretained(this))) {} + + ~PipelineControllerTest() override {} + + PipelineStatusCB StartPipeline() { + EXPECT_FALSE(pipeline_controller_.IsStable()); + PipelineStatusCB start_cb; + EXPECT_CALL(pipeline_, Start(_, _, _, _, _, _, _, _, _, _)) + .WillOnce(SaveArg<4>(&start_cb)); + pipeline_controller_.Start( + nullptr, nullptr, false, base::Closure(), PipelineMetadataCB(), + BufferingStateCB(), base::Closure(), AddTextTrackCB(), base::Closure()); + Mock::VerifyAndClear(&pipeline_); + EXPECT_FALSE(pipeline_controller_.IsStable()); + return start_cb; + } + + PipelineStatusCB SeekPipeline(base::TimeDelta time) { + EXPECT_TRUE(pipeline_controller_.IsStable()); + PipelineStatusCB seek_cb; + EXPECT_CALL(pipeline_, Seek(time, _)).WillOnce(SaveArg<1>(&seek_cb)); + pipeline_controller_.Seek(time, true); + Mock::VerifyAndClear(&pipeline_); + EXPECT_FALSE(pipeline_controller_.IsStable()); + return seek_cb; + } + + PipelineStatusCB SuspendPipeline() { + EXPECT_TRUE(pipeline_controller_.IsStable()); + PipelineStatusCB suspend_cb; + EXPECT_CALL(pipeline_, Suspend(_)).WillOnce(SaveArg<0>(&suspend_cb)); + pipeline_controller_.Suspend(); + Mock::VerifyAndClear(&pipeline_); + EXPECT_FALSE(pipeline_controller_.IsStable()); + EXPECT_FALSE(pipeline_controller_.IsSuspended()); + return suspend_cb; + } + + PipelineStatusCB ResumePipeline() { + EXPECT_TRUE(pipeline_controller_.IsSuspended()); + PipelineStatusCB resume_cb; + EXPECT_CALL(pipeline_, Resume(_, _, _)) + .WillOnce( + DoAll(SaveArg<1>(&last_resume_time_), SaveArg<2>(&resume_cb))); + EXPECT_CALL(pipeline_, GetMediaTime()) + .WillRepeatedly(Return(base::TimeDelta())); + pipeline_controller_.Resume(); + Mock::VerifyAndClear(&pipeline_); + EXPECT_FALSE(pipeline_controller_.IsStable()); + EXPECT_FALSE(pipeline_controller_.IsSuspended()); + return resume_cb; + } + + void Complete(const PipelineStatusCB& cb) { + cb.Run(PIPELINE_OK); + message_loop_.RunUntilIdle(); + } + + protected: + scoped_ptr<Renderer> CreateRenderer() { return scoped_ptr<Renderer>(); } + + void OnSeeked(bool time_updated) { + was_seeked_ = true; + last_seeked_time_updated_ = time_updated; + } + + void OnSuspended() { was_suspended_ = true; } + + void OnResumed() { was_resumed_ = true; } + + void OnError(PipelineStatus status) { NOTREACHED(); } + + base::MessageLoop message_loop_; + + StrictMock<MockPipeline> pipeline_; + PipelineController pipeline_controller_; + + bool was_seeked_ = false; + bool last_seeked_time_updated_ = false; + bool was_suspended_ = false; + bool was_resumed_ = false; + base::TimeDelta last_resume_time_; + + DISALLOW_COPY_AND_ASSIGN(PipelineControllerTest); +}; + +TEST_F(PipelineControllerTest, Startup) { + PipelineStatusCB start_cb = StartPipeline(); + EXPECT_FALSE(was_seeked_); + + Complete(start_cb); + EXPECT_TRUE(was_seeked_); + EXPECT_FALSE(last_seeked_time_updated_); + EXPECT_FALSE(was_suspended_); + EXPECT_FALSE(was_resumed_); + EXPECT_TRUE(pipeline_controller_.IsStable()); +} + +TEST_F(PipelineControllerTest, SuspendResume) { + Complete(StartPipeline()); + EXPECT_TRUE(was_seeked_); + was_seeked_ = false; + + Complete(SuspendPipeline()); + EXPECT_TRUE(was_suspended_); + EXPECT_FALSE(was_resumed_); + EXPECT_FALSE(pipeline_controller_.IsStable()); + + Complete(ResumePipeline()); + EXPECT_TRUE(was_resumed_); + EXPECT_TRUE(pipeline_controller_.IsStable()); + + // |was_seeked_| should not be affected by Suspend()/Resume() at all. + EXPECT_FALSE(was_seeked_); +} + +TEST_F(PipelineControllerTest, PendingSuspend) { + Complete(StartPipeline()); + + base::TimeDelta seek_time = base::TimeDelta::FromSeconds(5); + PipelineStatusCB seek_cb = SeekPipeline(seek_time); + message_loop_.RunUntilIdle(); + + // While the seek is ongoing, request a suspend. + // It will be a mock failure if pipeline_.Suspend() is called. + pipeline_controller_.Suspend(); + message_loop_.RunUntilIdle(); + + // Expect the suspend to trigger when the seek is completed. + EXPECT_CALL(pipeline_, Suspend(_)); + Complete(seek_cb); +} + +TEST_F(PipelineControllerTest, SeekMergesWithResume) { + Complete(StartPipeline()); + Complete(SuspendPipeline()); + + // Request a seek while suspended. + // It will be a mock failure if pipeline_.Seek() is called. + base::TimeDelta seek_time = base::TimeDelta::FromSeconds(5); + pipeline_controller_.Seek(seek_time, true); + message_loop_.RunUntilIdle(); + + // Resume and verify the resume time includes the seek. + Complete(ResumePipeline()); + EXPECT_EQ(seek_time, last_resume_time_); + EXPECT_TRUE(last_seeked_time_updated_); +} + +TEST_F(PipelineControllerTest, SeekMergesWithSeek) { + Complete(StartPipeline()); + + base::TimeDelta seek_time_1 = base::TimeDelta::FromSeconds(5); + PipelineStatusCB seek_cb_1 = SeekPipeline(seek_time_1); + message_loop_.RunUntilIdle(); + + // Request another seek while the first is ongoing. + base::TimeDelta seek_time_2 = base::TimeDelta::FromSeconds(10); + pipeline_controller_.Seek(seek_time_2, true); + message_loop_.RunUntilIdle(); + + // Request a third seek. (It should replace the second.) + base::TimeDelta seek_time_3 = base::TimeDelta::FromSeconds(15); + pipeline_controller_.Seek(seek_time_3, true); + message_loop_.RunUntilIdle(); + + // Expect the third seek to trigger when the first seek completes. + EXPECT_CALL(pipeline_, Seek(seek_time_3, _)); + Complete(seek_cb_1); +} + +} // namespace media
diff --git a/media/media.gyp b/media/media.gyp index 5c72613c..bdc7d5c 100644 --- a/media/media.gyp +++ b/media/media.gyp
@@ -536,6 +536,8 @@ 'filters/opus_audio_decoder.h', 'filters/opus_constants.cc', 'filters/opus_constants.h', + 'filters/pipeline_controller.cc', + 'filters/pipeline_controller.h', 'filters/source_buffer_range.cc', 'filters/source_buffer_range.h', 'filters/source_buffer_stream.cc', @@ -1258,6 +1260,7 @@ 'filters/ivf_parser_unittest.cc', 'filters/jpeg_parser_unittest.cc', 'filters/memory_data_source_unittest.cc', + 'filters/pipeline_controller_unittest.cc', 'filters/source_buffer_stream_unittest.cc', 'filters/video_cadence_estimator_unittest.cc', 'filters/video_decoder_selector_unittest.cc',
diff --git a/media/mojo/DEPS b/media/mojo/DEPS index e0c0a51..0338577 100644 --- a/media/mojo/DEPS +++ b/media/mojo/DEPS
@@ -4,4 +4,7 @@ "+mojo/converters", "+mojo/logging", "+mojo/public", + + # media/mojo is not part of "media" target and should not use MEDIA_EXPORT. + "-media/base/media_export.h" ]
diff --git a/media/mojo/common/BUILD.gn b/media/mojo/common/BUILD.gn index 93a6b77..eed3ae3 100644 --- a/media/mojo/common/BUILD.gn +++ b/media/mojo/common/BUILD.gn
@@ -11,6 +11,8 @@ sources = [ "media_type_converters.cc", "media_type_converters.h", + "mojo_shared_buffer_video_frame.cc", + "mojo_shared_buffer_video_frame.h", ] deps = [ @@ -21,6 +23,7 @@ "//mojo/converters/geometry", "//mojo/environment:chromium", "//mojo/public/c/system:for_component", + "//ui/gfx/geometry", "//ui/mojo/geometry:interfaces", ] } @@ -28,6 +31,7 @@ test("media_mojo_unittests") { sources = [ "media_type_converters_unittest.cc", + "mojo_shared_buffer_video_frame_unittest.cc", ] deps = [
diff --git a/media/mojo/common/media_type_converters.cc b/media/mojo/common/media_type_converters.cc index 476d1b45..5735cb0 100644 --- a/media/mojo/common/media_type_converters.cc +++ b/media/mojo/common/media_type_converters.cc
@@ -477,8 +477,7 @@ static_cast<media::interfaces::ChannelLayout>(input.channel_layout()); config->samples_per_second = input.samples_per_second(); if (!input.extra_data().empty()) { - std::vector<uint8_t> extra_data = input.extra_data(); - config->extra_data.Swap(&extra_data); + config->extra_data = mojo::Array<uint8_t>::From(input.extra_data()); } config->seek_preroll_usec = input.seek_preroll().InMicroseconds(); config->codec_delay = input.codec_delay(); @@ -518,7 +517,9 @@ config->coded_size = Size::From(input.coded_size()); config->visible_rect = Rect::From(input.visible_rect()); config->natural_size = Size::From(input.natural_size()); - config->extra_data = mojo::Array<uint8_t>::From(input.extra_data()); + if (!input.extra_data().empty()) { + config->extra_data = mojo::Array<uint8_t>::From(input.extra_data()); + } config->is_encrypted = input.is_encrypted(); return config; }
diff --git a/media/mojo/common/media_type_converters_unittest.cc b/media/mojo/common/media_type_converters_unittest.cc index 3070a7f..f9de05d 100644 --- a/media/mojo/common/media_type_converters_unittest.cc +++ b/media/mojo/common/media_type_converters_unittest.cc
@@ -23,6 +23,10 @@ namespace { +static const gfx::Size kCodedSize(320, 240); +static const gfx::Rect kVisibleRect(320, 240); +static const gfx::Size kNaturalSize(320, 240); + void CompareBytes(uint8_t* original_data, uint8_t* result_data, size_t length) { EXPECT_GT(length, 0u); EXPECT_EQ(memcmp(original_data, result_data, length), 0); @@ -226,6 +230,7 @@ kExtraDataVector, false, base::TimeDelta(), 0); interfaces::AudioDecoderConfigPtr ptr( interfaces::AudioDecoderConfig::From(config)); + EXPECT_FALSE(ptr->extra_data.is_null()); AudioDecoderConfig result(ptr.To<AudioDecoderConfig>()); EXPECT_TRUE(result.Matches(config)); } @@ -236,6 +241,7 @@ EmptyExtraData(), false, base::TimeDelta(), 0); interfaces::AudioDecoderConfigPtr ptr( interfaces::AudioDecoderConfig::From(config)); + EXPECT_TRUE(ptr->extra_data.is_null()); AudioDecoderConfig result(ptr.To<AudioDecoderConfig>()); EXPECT_TRUE(result.Matches(config)); } @@ -248,7 +254,48 @@ base::TimeDelta(), 0); interfaces::AudioDecoderConfigPtr ptr( interfaces::AudioDecoderConfig::From(config)); + EXPECT_TRUE(ptr->is_encrypted); AudioDecoderConfig result(ptr.To<AudioDecoderConfig>()); + EXPECT_TRUE(result.is_encrypted()); + EXPECT_TRUE(result.Matches(config)); +} + +TEST(MediaTypeConvertersTest, ConvertVideoDecoderConfig_Normal) { + const uint8_t kExtraData[] = "config extra data"; + const std::vector<uint8_t> kExtraDataVector( + &kExtraData[0], &kExtraData[0] + arraysize(kExtraData)); + + VideoDecoderConfig config(kCodecVP8, VP8PROFILE_ANY, PIXEL_FORMAT_YV12, + COLOR_SPACE_UNSPECIFIED, kCodedSize, kVisibleRect, + kNaturalSize, kExtraDataVector, false); + interfaces::VideoDecoderConfigPtr ptr( + interfaces::VideoDecoderConfig::From(config)); + EXPECT_FALSE(ptr->extra_data.is_null()); + VideoDecoderConfig result(ptr.To<VideoDecoderConfig>()); + EXPECT_TRUE(result.Matches(config)); +} + +TEST(MediaTypeConvertersTest, ConvertVideoDecoderConfig_EmptyExtraData) { + VideoDecoderConfig config(kCodecVP8, VP8PROFILE_ANY, PIXEL_FORMAT_YV12, + COLOR_SPACE_UNSPECIFIED, kCodedSize, kVisibleRect, + kNaturalSize, EmptyExtraData(), false); + interfaces::VideoDecoderConfigPtr ptr( + interfaces::VideoDecoderConfig::From(config)); + EXPECT_TRUE(ptr->extra_data.is_null()); + VideoDecoderConfig result(ptr.To<VideoDecoderConfig>()); + EXPECT_TRUE(result.Matches(config)); +} + +TEST(MediaTypeConvertersTest, ConvertVideoDecoderConfig_Encrypted) { + VideoDecoderConfig config(kCodecVP8, VP8PROFILE_ANY, PIXEL_FORMAT_YV12, + COLOR_SPACE_UNSPECIFIED, kCodedSize, kVisibleRect, + kNaturalSize, EmptyExtraData(), + true /* is_encrypted */); + interfaces::VideoDecoderConfigPtr ptr( + interfaces::VideoDecoderConfig::From(config)); + EXPECT_TRUE(ptr->is_encrypted); + VideoDecoderConfig result(ptr.To<VideoDecoderConfig>()); + EXPECT_TRUE(result.is_encrypted()); EXPECT_TRUE(result.Matches(config)); }
diff --git a/media/mojo/common/mojo_shared_buffer_video_frame.cc b/media/mojo/common/mojo_shared_buffer_video_frame.cc new file mode 100644 index 0000000..fa226c2 --- /dev/null +++ b/media/mojo/common/mojo_shared_buffer_video_frame.cc
@@ -0,0 +1,147 @@ +// 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 "media/mojo/common/mojo_shared_buffer_video_frame.h" + +#include "base/bind.h" +#include "base/compiler_specific.h" +#include "base/logging.h" + +namespace media { + +// static +scoped_refptr<MojoSharedBufferVideoFrame> +MojoSharedBufferVideoFrame::CreateDefaultI420(const gfx::Size& dimensions, + base::TimeDelta timestamp) { + const VideoPixelFormat format = PIXEL_FORMAT_I420; + const gfx::Rect visible_rect(dimensions); + + // Since we're allocating memory for the new frame, pad the requested + // size if necessary so that the requested size does line up on sample + // boundaries. See related discussion in VideoFrame::CreateFrameInternal(). + const gfx::Size coded_size = DetermineAlignedSize(format, dimensions); + if (!IsValidConfig(format, STORAGE_MOJO_SHARED_BUFFER, coded_size, + visible_rect, dimensions)) { + LOG(DFATAL) << __FUNCTION__ << " Invalid config. " + << ConfigToString(format, STORAGE_MOJO_SHARED_BUFFER, + dimensions, visible_rect, dimensions); + return nullptr; + } + + // Allocate a shared memory buffer big enough to hold the desired frame. + const size_t allocation_size = VideoFrame::AllocationSize(format, coded_size); + mojo::ScopedSharedBufferHandle handle; + const MojoResult result = + mojo::CreateSharedBuffer(nullptr, allocation_size, &handle); + if (result != MOJO_RESULT_OK) + return nullptr; + + // Create and initialize the frame. As this is I420 format, the U and V + // planes have samples for each 2x2 block. The memory is laid out as follows: + // - Yplane, full size (each element represents a 1x1 block) + // - Uplane, quarter size (each element represents a 2x2 block) + // - Vplane, quarter size (each element represents a 2x2 block) + DCHECK((coded_size.width() % 2 == 0) && (coded_size.height() % 2 == 0)); + return Create(format, coded_size, visible_rect, dimensions, std::move(handle), + allocation_size, 0 /* y_offset */, coded_size.GetArea(), + coded_size.GetArea() * 5 / 4, coded_size.width(), + coded_size.width() / 2, coded_size.width() / 2, timestamp); +} + +// static +scoped_refptr<MojoSharedBufferVideoFrame> MojoSharedBufferVideoFrame::Create( + VideoPixelFormat format, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size, + mojo::ScopedSharedBufferHandle handle, + size_t data_size, + size_t y_offset, + size_t u_offset, + size_t v_offset, + int32_t y_stride, + int32_t u_stride, + int32_t v_stride, + base::TimeDelta timestamp) { + if (!IsValidConfig(format, STORAGE_MOJO_SHARED_BUFFER, coded_size, + visible_rect, natural_size)) { + LOG(DFATAL) << __FUNCTION__ << " Invalid config. " + << ConfigToString(format, STORAGE_MOJO_SHARED_BUFFER, + coded_size, visible_rect, natural_size); + return nullptr; + } + + // Now allocate the frame and initialize it. + scoped_refptr<MojoSharedBufferVideoFrame> frame( + new MojoSharedBufferVideoFrame(format, coded_size, visible_rect, + natural_size, std::move(handle), data_size, + timestamp)); + if (!frame->Init(y_stride, u_stride, v_stride, y_offset, u_offset, v_offset)) + return nullptr; + + return frame; +} + +MojoSharedBufferVideoFrame::MojoSharedBufferVideoFrame( + VideoPixelFormat format, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size, + mojo::ScopedSharedBufferHandle handle, + size_t mapped_size, + base::TimeDelta timestamp) + : VideoFrame(format, + STORAGE_MOJO_SHARED_BUFFER, + coded_size, + visible_rect, + natural_size, + timestamp), + shared_buffer_handle_(std::move(handle)), + shared_buffer_size_(mapped_size), + shared_buffer_data_(nullptr) { + DCHECK(shared_buffer_handle_.is_valid()); +} + +bool MojoSharedBufferVideoFrame::Init(int32_t y_stride, + int32_t u_stride, + int32_t v_stride, + size_t y_offset, + size_t u_offset, + size_t v_offset) { + DCHECK(!shared_buffer_data_); + void* memory = nullptr; + const MojoResult result = + mojo::MapBuffer(shared_buffer_handle_.get(), 0 /* offset */, + shared_buffer_size_, &memory, MOJO_MAP_BUFFER_FLAG_NONE); + if (result != MOJO_RESULT_OK || !memory) + return false; + shared_buffer_data_ = static_cast<uint8_t*>(memory); + + set_stride(kYPlane, y_stride); + set_stride(kUPlane, u_stride); + set_stride(kVPlane, v_stride); + offsets_[kYPlane] = y_offset; + offsets_[kUPlane] = u_offset; + offsets_[kVPlane] = v_offset; + set_data(kYPlane, shared_buffer_data_ + y_offset); + set_data(kUPlane, shared_buffer_data_ + u_offset); + set_data(kVPlane, shared_buffer_data_ + v_offset); + return true; +} + +MojoSharedBufferVideoFrame::~MojoSharedBufferVideoFrame() { + // If MapBuffer() was called, we need to have a matching call to unmap it. + if (shared_buffer_data_) { + const MojoResult result = mojo::UnmapBuffer(shared_buffer_data_); + ALLOW_UNUSED_LOCAL(result); + DCHECK_EQ(result, MOJO_RESULT_OK); + } +} + +size_t MojoSharedBufferVideoFrame::PlaneOffset(size_t plane) const { + DCHECK(IsValidPlane(plane, format())); + return offsets_[plane]; +} + +} // namespace media
diff --git a/media/mojo/common/mojo_shared_buffer_video_frame.h b/media/mojo/common/mojo_shared_buffer_video_frame.h new file mode 100644 index 0000000..d27a85f --- /dev/null +++ b/media/mojo/common/mojo_shared_buffer_video_frame.h
@@ -0,0 +1,84 @@ +// 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 MEDIA_MOJO_COMMON_MOJO_SHARED_BUFFER_VIDEO_FRAME_H_ +#define MEDIA_MOJO_COMMON_MOJO_SHARED_BUFFER_VIDEO_FRAME_H_ + +#include <stddef.h> +#include <stdint.h> + +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "media/base/video_frame.h" +#include "mojo/public/cpp/system/buffer.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" + +namespace media { + +// A derived class of media::VideoFrame holding a mojo::SharedBufferHandle +// which is mapped on constructor and remains so for the lifetime of the +// object. These frames are ref-counted. +class MojoSharedBufferVideoFrame : public VideoFrame { + public: + // Creates a new I420 frame in shared memory with provided parameters + // (coded_size() == natural_size() == visible_rect()), or returns nullptr. + // Buffers for the frame are allocated but not initialized. The caller must + // not make assumptions about the actual underlying sizes, but check the + // returned VideoFrame instead. + static scoped_refptr<MojoSharedBufferVideoFrame> CreateDefaultI420( + const gfx::Size& dimensions, + base::TimeDelta timestamp); + + // Creates a MojoSharedBufferVideoFrame that uses the memory in |handle|. + // This will take ownership of |handle|, so the caller can no longer use it. + static scoped_refptr<MojoSharedBufferVideoFrame> Create( + VideoPixelFormat format, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size, + mojo::ScopedSharedBufferHandle handle, + size_t mapped_size, + size_t y_offset, + size_t u_offset, + size_t v_offset, + int32_t y_stride, + int32_t u_stride, + int32_t v_stride, + base::TimeDelta timestamp); + + // Returns the offsets relative to the start of |shared_buffer| for the + // |plane| specified. + size_t PlaneOffset(size_t plane) const; + + private: + MojoSharedBufferVideoFrame(VideoPixelFormat format, + const gfx::Size& coded_size, + const gfx::Rect& visible_rect, + const gfx::Size& natural_size, + mojo::ScopedSharedBufferHandle handle, + size_t mapped_size, + base::TimeDelta timestamp); + ~MojoSharedBufferVideoFrame() override; + + // Initializes the MojoSharedBufferVideoFrame by creating a mapping onto + // the shared memory, and then setting the strides and offsets as specified. + bool Init(int32_t y_stride, + int32_t u_stride, + int32_t v_stride, + size_t y_offset, + size_t u_offset, + size_t v_offset); + + mojo::ScopedSharedBufferHandle shared_buffer_handle_; + size_t shared_buffer_size_; + uint8_t* shared_buffer_data_; + size_t offsets_[kMaxPlanes]; + + DISALLOW_COPY_AND_ASSIGN(MojoSharedBufferVideoFrame); +}; + +} // namespace media + +#endif // MEDIA_MOJO_COMMON_MOJO_SHARED_BUFFER_VIDEO_FRAME_H_
diff --git a/media/mojo/common/mojo_shared_buffer_video_frame_unittest.cc b/media/mojo/common/mojo_shared_buffer_video_frame_unittest.cc new file mode 100644 index 0000000..474efe8 --- /dev/null +++ b/media/mojo/common/mojo_shared_buffer_video_frame_unittest.cc
@@ -0,0 +1,122 @@ +// 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 "media/mojo/common/mojo_shared_buffer_video_frame.h" + +#include <stddef.h> +#include <stdint.h> +#include <string> + +#include "base/memory/ref_counted.h" +#include "base/time/time.h" +#include "mojo/public/cpp/system/buffer.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" + +namespace media { + +TEST(MojoSharedBufferVideoFrameTest, CreateFrameWithSharedMemory) { + const int kWidth = 16; + const int kHeight = 9; + const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(1337); + + // Create a MojoSharedBufferVideoFrame which will allocate enough space + // to hold a 16x9 video frame. + gfx::Size size(kWidth, kHeight); + scoped_refptr<MojoSharedBufferVideoFrame> frame = + MojoSharedBufferVideoFrame::CreateDefaultI420(size, kTimestamp); + ASSERT_TRUE(frame.get()); + + // Verify that the correct frame was allocated. + EXPECT_EQ(media::PIXEL_FORMAT_I420, frame->format()); + + // The offsets should be set appropriately. + EXPECT_EQ(frame->PlaneOffset(VideoFrame::kYPlane), 0u); + EXPECT_GT(frame->PlaneOffset(VideoFrame::kUPlane), 0u); + EXPECT_GT(frame->PlaneOffset(VideoFrame::kVPlane), 0u); + + // The strides should be set appropriately. + EXPECT_EQ(frame->stride(VideoFrame::kYPlane), kWidth); + EXPECT_EQ(frame->stride(VideoFrame::kUPlane), kWidth / 2); + EXPECT_EQ(frame->stride(VideoFrame::kVPlane), kWidth / 2); + + // The data pointers for each plane should be set. + EXPECT_TRUE(frame->data(VideoFrame::kYPlane)); + EXPECT_TRUE(frame->data(VideoFrame::kUPlane)); + EXPECT_TRUE(frame->data(VideoFrame::kVPlane)); +} + +TEST(MojoSharedBufferVideoFrameTest, CreateFrameAndPassSharedMemory) { + const int kWidth = 32; + const int kHeight = 18; + const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(1338); + + // Some random values to use. Since we actually don't use the data inside the + // frame, random values are fine (as long as the offsets are within the + // memory size allocated). + const VideoPixelFormat format = PIXEL_FORMAT_YV12; + const size_t y_offset = kWidth * 2; + const size_t u_offset = kWidth * 3; + const size_t v_offset = kWidth * 5; + const int32_t y_stride = kWidth; + const int32_t u_stride = kWidth - 1; + const int32_t v_stride = kWidth - 2; + + // Allocate some shared memory. + gfx::Size size(kWidth, kHeight); + gfx::Rect visible_rect(size); + size_t requested_size = VideoFrame::AllocationSize(format, size); + ASSERT_LT(y_offset, requested_size); + mojo::ScopedSharedBufferHandle handle; + MojoResult result = + mojo::CreateSharedBuffer(nullptr, requested_size, &handle); + ASSERT_EQ(result, MOJO_RESULT_OK); + + // Allocate frame. + scoped_refptr<MojoSharedBufferVideoFrame> frame = + MojoSharedBufferVideoFrame::Create(format, size, visible_rect, size, + std::move(handle), requested_size, + y_offset, u_offset, v_offset, y_stride, + u_stride, v_stride, kTimestamp); + ASSERT_TRUE(frame.get()); + EXPECT_EQ(frame->format(), format); + + // The offsets should be set appropriately. + EXPECT_EQ(frame->PlaneOffset(VideoFrame::kYPlane), y_offset); + EXPECT_EQ(frame->PlaneOffset(VideoFrame::kUPlane), u_offset); + EXPECT_EQ(frame->PlaneOffset(VideoFrame::kVPlane), v_offset); + + // The strides should be set appropriately. + EXPECT_EQ(frame->stride(VideoFrame::kYPlane), y_stride); + EXPECT_EQ(frame->stride(VideoFrame::kUPlane), u_stride); + EXPECT_EQ(frame->stride(VideoFrame::kVPlane), v_stride); + + // The data pointers for each plane should be set. + EXPECT_TRUE(frame->data(VideoFrame::kYPlane)); + EXPECT_TRUE(frame->data(VideoFrame::kUPlane)); + EXPECT_TRUE(frame->data(VideoFrame::kVPlane)); +} + +TEST(MojoSharedBufferVideoFrameTest, CreateFrameOddWidth) { + const int kWidth = 15; + const int kHeight = 9; + const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(1337); + + // Create a MojoSharedBufferVideoFrame which will allocate enough space + // to hold the video frame. Size should be adjusted. + gfx::Size size(kWidth, kHeight); + scoped_refptr<MojoSharedBufferVideoFrame> frame = + MojoSharedBufferVideoFrame::CreateDefaultI420(size, kTimestamp); + ASSERT_TRUE(frame.get()); + + // Verify that the correct frame was allocated. + EXPECT_EQ(media::PIXEL_FORMAT_I420, frame->format()); + + // The size should be >= 15x9. + EXPECT_GE(frame->coded_size().width(), kWidth); + EXPECT_GE(frame->coded_size().height(), kHeight); +} + +} // namespace media
diff --git a/media/mojo/services/media_apptest.cc b/media/mojo/services/media_apptest.cc index d61111d..27d68cc 100644 --- a/media/mojo/services/media_apptest.cc +++ b/media/mojo/services/media_apptest.cc
@@ -60,7 +60,7 @@ ApplicationTestBase::SetUp(); connection_ = connector()->Connect("mojo:media"); - connection_->SetRemoteInterfaceProviderConnectionErrorHandler( + connection_->SetConnectionLostClosure( base::Bind(&MediaAppTest::ConnectionClosed, base::Unretained(this))); connection_->GetInterface(&service_factory_);
diff --git a/media/mojo/services/mojo_media_application.cc b/media/mojo/services/mojo_media_application.cc index 0def56a..380d95f0 100644 --- a/media/mojo/services/mojo_media_application.cc +++ b/media/mojo/services/mojo_media_application.cc
@@ -27,8 +27,8 @@ void MojoMediaApplication::Initialize(mojo::Connector* connector, const std::string& /* url */, - uint32_t /* id */, - uint32_t user_id) { + const std::string& user_id, + uint32_t /* id */) { connector_ = connector; mojo_media_client_->Initialize(); }
diff --git a/media/mojo/services/mojo_media_application.h b/media/mojo/services/mojo_media_application.h index cd5f8037..9844ab13 100644 --- a/media/mojo/services/mojo_media_application.h +++ b/media/mojo/services/mojo_media_application.h
@@ -29,8 +29,8 @@ // mojo::ShellClient implementation. void Initialize(mojo::Connector* connector, const std::string& url, - uint32_t id, - uint32_t user_id) final; + const std::string& user_id, + uint32_t id) final; bool AcceptConnection(mojo::Connection* connection) final; // mojo::InterfaceFactory<interfaces::ServiceFactory> implementation.
diff --git a/media/renderers/audio_renderer_impl.cc b/media/renderers/audio_renderer_impl.cc index 9a1eeaa1..0576e02 100644 --- a/media/renderers/audio_renderer_impl.cc +++ b/media/renderers/audio_renderer_impl.cc
@@ -158,20 +158,36 @@ ended_timestamp_ = kInfiniteDuration(); last_render_time_ = stop_rendering_time_ = base::TimeTicks(); first_packet_timestamp_ = kNoTimestamp(); + last_media_timestamp_ = base::TimeDelta(); audio_clock_.reset(new AudioClock(time, audio_parameters_.sample_rate())); } base::TimeDelta AudioRendererImpl::CurrentMediaTime() { - // In practice the Render() method is called with a high enough frequency - // that returning only the front timestamp is good enough and also prevents - // returning values that go backwards in time. - base::TimeDelta current_media_time; - { - base::AutoLock auto_lock(lock_); - current_media_time = audio_clock_->front_timestamp(); + base::AutoLock auto_lock(lock_); + + // Return the current time based on the known extents of the rendered audio + // data plus an estimate based on the last time those values were calculated. + base::TimeDelta current_media_time = audio_clock_->front_timestamp(); + if (!last_render_time_.is_null()) { + current_media_time += tick_clock_->NowTicks() - last_render_time_; + if (current_media_time > audio_clock_->back_timestamp()) + current_media_time = audio_clock_->back_timestamp(); + } + + // Clamp current media time to the last reported value, this prevents higher + // level clients from seeing time go backwards based on inaccurate or spurious + // delay values reported to the AudioClock. + // + // It is expected that such events are transient and will be recovered as + // rendering continues over time. + if (current_media_time < last_media_timestamp_) { + DVLOG(2) << __FUNCTION__ << ": " << last_media_timestamp_ + << " (clamped), actual: " << current_media_time; + return last_media_timestamp_; } DVLOG(2) << __FUNCTION__ << ": " << current_media_time; + last_media_timestamp_ = current_media_time; return current_media_time; } @@ -679,16 +695,20 @@ CHECK_GE(first_packet_timestamp_, base::TimeDelta()); const base::TimeDelta play_delay = first_packet_timestamp_ - audio_clock_->back_timestamp(); - CHECK_LT(play_delay.InSeconds(), 1000) - << "first_packet_timestamp_ = " << first_packet_timestamp_ - << ", audio_clock_->back_timestamp() = " - << audio_clock_->back_timestamp(); if (play_delay > base::TimeDelta()) { DCHECK_EQ(frames_written, 0); - frames_written = - std::min(static_cast<int>(play_delay.InSecondsF() * - audio_parameters_.sample_rate()), - frames_requested); + + // Don't multiply |play_delay| out since it can be a huge value on + // poorly encoded media and multiplying by the sample rate could cause + // the value to overflow. + if (play_delay.InSecondsF() > static_cast<double>(frames_requested) / + audio_parameters_.sample_rate()) { + frames_written = frames_requested; + } else { + frames_written = + play_delay.InSecondsF() * audio_parameters_.sample_rate(); + } + audio_bus->ZeroFramesPartial(0, frames_written); }
diff --git a/media/renderers/audio_renderer_impl.h b/media/renderers/audio_renderer_impl.h index 63a6579..1db9bd3 100644 --- a/media/renderers/audio_renderer_impl.h +++ b/media/renderers/audio_renderer_impl.h
@@ -280,6 +280,10 @@ // Used to determine how long to delay playback. base::TimeDelta first_packet_timestamp_; + // Set by CurrentMediaTime(), used to prevent the current media time value as + // reported to JavaScript from going backwards in time. + base::TimeDelta last_media_timestamp_; + // End variables which must be accessed under |lock_|. ---------------------- // NOTE: Weak pointers must be invalidated before all other member variables.
diff --git a/media/renderers/audio_renderer_impl_unittest.cc b/media/renderers/audio_renderer_impl_unittest.cc index 1f7c2cc..20c5fdb 100644 --- a/media/renderers/audio_renderer_impl_unittest.cc +++ b/media/renderers/audio_renderer_impl_unittest.cc
@@ -653,7 +653,7 @@ EXPECT_EQ(0, converter_input_frames_left().value); } -TEST_F(AudioRendererImplTest, TimeUpdatesOnFirstBuffer) { +TEST_F(AudioRendererImplTest, CurrentMediaTimeBehavior) { Initialize(); Preroll(); StartTicking(); @@ -661,11 +661,19 @@ AudioTimestampHelper timestamp_helper(kOutputSamplesPerSecond); timestamp_helper.SetBaseTimestamp(base::TimeDelta()); - // Time should be the starting timestamp as nothing's been consumed yet. + // Time should be the starting timestamp as nothing has been consumed yet. + EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime()); + + const OutputFrames frames_to_consume(frames_buffered().value / 3); + const base::TimeDelta kConsumptionDuration = + timestamp_helper.GetFrameDuration(frames_to_consume.value); + + // Render() has not be called yet, thus no data has been consumed, so + // advancing tick clock must not change the media time. + tick_clock_->Advance(kConsumptionDuration); EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime()); // Consume some audio data. - OutputFrames frames_to_consume(frames_buffered().value / 2); EXPECT_TRUE(ConsumeBufferedData(frames_to_consume)); WaitForPendingRead(); @@ -673,11 +681,38 @@ // data to the hardware. EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime()); + // Advancing the tick clock now should result in an estimated media time. + tick_clock_->Advance(kConsumptionDuration); + EXPECT_EQ(timestamp_helper.GetTimestamp() + kConsumptionDuration, + CurrentMediaTime()); + // Consume some more audio data. - frames_to_consume = frames_buffered(); EXPECT_TRUE(ConsumeBufferedData(frames_to_consume)); - // Now time should change now that the audio hardware has called back. + // Time should change now that Render() has been called a second time. + timestamp_helper.AddFrames(frames_to_consume.value); + EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime()); + + // Advance current time well past all played audio to simulate an irregular or + // delayed OS callback. The value should be clamped to whats been rendered. + timestamp_helper.AddFrames(frames_to_consume.value); + tick_clock_->Advance(kConsumptionDuration * 2); + const base::TimeDelta last_media_time = CurrentMediaTime(); + EXPECT_EQ(timestamp_helper.GetTimestamp(), last_media_time); + + // Consume some more audio data, but provide a delay value which is at odds + // with the amount of time advanced so far; this would normally cause the + // media time to go backwards relative to its last value. + EXPECT_TRUE(ConsumeBufferedData(frames_to_consume, 1)); + + // Current time should never go backwards even for irregular OS callbacks and + // those with odd / wrong delay values. + EXPECT_EQ(last_media_time, CurrentMediaTime()); + + // Stop ticking, the media time should be clamped to what's been rendered. + StopTicking(); + EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime()); + tick_clock_->Advance(kConsumptionDuration * 2); timestamp_helper.AddFrames(frames_to_consume.value); EXPECT_EQ(timestamp_helper.GetTimestamp(), CurrentMediaTime()); } @@ -720,6 +755,16 @@ ASSERT_NE(0.0f, bus->channel(0)[i]); } +TEST_F(AudioRendererImplTest, RenderingDelayDoesNotOverflow) { + Initialize(); + + // Choose a first timestamp as far into the future as possible. Without care + // this can cause an overflow in rendering arithmetic. + Preroll(base::TimeDelta(), base::TimeDelta::Max(), PIPELINE_OK); + StartTicking(); + EXPECT_TRUE(ConsumeBufferedData(OutputFrames(1))); +} + TEST_F(AudioRendererImplTest, ImmediateEndOfStream) { Initialize(); { @@ -835,6 +880,10 @@ ConvertMediaTime(base::TimeDelta(), &is_time_moving)); EXPECT_TRUE(is_time_moving); + // Store current media time before advancing the tick clock since the call is + // compensated based on TimeTicks::Now(). + const base::TimeDelta current_media_time = renderer_->CurrentMediaTime(); + // The current wall clock time should change as our tick clock advances, up // until we've reached the end of played out frames. const int kSteps = 4; @@ -850,7 +899,7 @@ // Converting the current media time should be relative to wall clock zero. EXPECT_EQ(wall_clock_time_zero + kSteps * kAdvanceDelta, - ConvertMediaTime(renderer_->CurrentMediaTime(), &is_time_moving)); + ConvertMediaTime(current_media_time, &is_time_moving)); EXPECT_TRUE(is_time_moving); // Advancing once more will exceed the amount of played out frames finally.
diff --git a/media/test/BUILD.gn b/media/test/BUILD.gn index a5b47a27..cddbc69 100644 --- a/media/test/BUILD.gn +++ b/media/test/BUILD.gn
@@ -130,4 +130,5 @@ "//testing/gmock", "//ui/gfx:test_support", ] + libfuzzer_options = "media_pipeline_integration_fuzzer.options" }
diff --git a/media/test/data/eme_player_js/utils.js b/media/test/data/eme_player_js/utils.js index 8ebb033..7eec1bdb 100644 --- a/media/test/data/eme_player_js/utils.js +++ b/media/test/data/eme_player_js/utils.js
@@ -181,7 +181,7 @@ Utils.installTitleEventHandler = function(element, event) { element.addEventListener(event, function(e) { - Utils.setResultInTitle(e.type); + Utils.setResultInTitle(e.type.toUpperCase()); }, false); }; @@ -256,8 +256,8 @@ Utils.setResultInTitle = function(title) { // If document title is 'ENDED', then update it with new title to possibly // mark a test as failure. Otherwise, keep the first title change in place. - if (!this.titleChanged || document.title.toUpperCase() == 'ENDED') - document.title = title.toUpperCase(); + if (!this.titleChanged || document.title == 'ENDED') + document.title = title; Utils.timeLog('Set document title to: ' + title + ', updated title: ' + document.title); this.titleChanged = true;
diff --git a/media/test/media_pipeline_integration_fuzzer.options b/media/test/media_pipeline_integration_fuzzer.options new file mode 100644 index 0000000..ace25c6 --- /dev/null +++ b/media/test/media_pipeline_integration_fuzzer.options
@@ -0,0 +1,3 @@ +[libfuzzer] +# This is done to avoid DEATH of ASan with "Thread limit exceeded" error. +runs=500000
diff --git a/media/test/pipeline_integration_test.cc b/media/test/pipeline_integration_test.cc index 51a845b..9f4deaf 100644 --- a/media/test/pipeline_integration_test.cc +++ b/media/test/pipeline_integration_test.cc
@@ -535,9 +535,7 @@ chunk_demuxer_->AppendData( kSourceId, file_data_->data() + current_position_, size, - base::TimeDelta(), kInfiniteDuration(), &last_timestamp_offset_, - base::Bind(&MockMediaSource::InitSegmentReceived, - base::Unretained(this))); + base::TimeDelta(), kInfiniteDuration(), &last_timestamp_offset_); current_position_ += size; } @@ -546,9 +544,7 @@ int size) { CHECK(!chunk_demuxer_->IsParsingMediaSegment(kSourceId)); chunk_demuxer_->AppendData(kSourceId, pData, size, base::TimeDelta(), - kInfiniteDuration(), ×tamp_offset, - base::Bind(&MockMediaSource::InitSegmentReceived, - base::Unretained(this))); + kInfiniteDuration(), ×tamp_offset); last_timestamp_offset_ = timestamp_offset; } @@ -559,9 +555,7 @@ int size) { CHECK(!chunk_demuxer_->IsParsingMediaSegment(kSourceId)); chunk_demuxer_->AppendData(kSourceId, pData, size, append_window_start, - append_window_end, ×tamp_offset, - base::Bind(&MockMediaSource::InitSegmentReceived, - base::Unretained(this))); + append_window_end, ×tamp_offset); last_timestamp_offset_ = timestamp_offset; } @@ -622,6 +616,9 @@ } CHECK_EQ(chunk_demuxer_->AddId(kSourceId, type, codecs), ChunkDemuxer::kOk); + chunk_demuxer_->SetTracksWatcher( + kSourceId, base::Bind(&MockMediaSource::InitSegmentReceivedWrapper, + base::Unretained(this))); AppendData(initial_append_size_); } @@ -637,7 +634,12 @@ return last_timestamp_offset_; } - MOCK_METHOD1(InitSegmentReceived, void(const MediaTracks&)); + // A workaround for gtest mocks not allowing moving scoped_ptrs. + void InitSegmentReceivedWrapper(scoped_ptr<MediaTracks> tracks) { + InitSegmentReceived(tracks); + } + + MOCK_METHOD1(InitSegmentReceived, void(scoped_ptr<MediaTracks>&)); private: scoped_refptr<DecoderBuffer> file_data_;
diff --git a/media/test/pipeline_integration_test_base.cc b/media/test/pipeline_integration_test_base.cc index dbaa37c..17647ba 100644 --- a/media/test/pipeline_integration_test_base.cc +++ b/media/test/pipeline_integration_test_base.cc
@@ -10,6 +10,7 @@ #include "base/memory/scoped_vector.h" #include "media/base/cdm_context.h" #include "media/base/media_log.h" +#include "media/base/media_tracks.h" #include "media/base/test_data_util.h" #include "media/filters/chunk_demuxer.h" #if !defined(MEDIA_DISABLE_FFMPEG) @@ -79,6 +80,11 @@ encrypted_media_init_data_cb_.Run(type, init_data); } +void PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB( + scoped_ptr<MediaTracks> tracks) { + CHECK(tracks); +} + void PipelineIntegrationTestBase::OnEnded() { DCHECK(!ended_); ended_ = true; @@ -267,12 +273,16 @@ scoped_ptr<DataSource> data_source) { data_source_ = std::move(data_source); + Demuxer::MediaTracksUpdatedCB tracks_updated_cb = + base::Bind(&PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB, + base::Unretained(this)); + #if !defined(MEDIA_DISABLE_FFMPEG) demuxer_ = scoped_ptr<Demuxer>(new FFmpegDemuxer( message_loop_.task_runner(), data_source_.get(), base::Bind(&PipelineIntegrationTestBase::DemuxerEncryptedMediaInitDataCB, base::Unretained(this)), - new MediaLog())); + tracks_updated_cb, new MediaLog())); #endif }
diff --git a/media/test/pipeline_integration_test_base.h b/media/test/pipeline_integration_test_base.h index 2cbbdea..8230489 100644 --- a/media/test/pipeline_integration_test_base.h +++ b/media/test/pipeline_integration_test_base.h
@@ -148,6 +148,8 @@ void DemuxerEncryptedMediaInitDataCB(EmeInitDataType type, const std::vector<uint8_t>& init_data); + void DemuxerMediaTracksUpdatedCB(scoped_ptr<MediaTracks> tracks); + void OnEnded(); void OnError(PipelineStatus status); void QuitAfterCurrentTimeTask(const base::TimeDelta& quit_time);
diff --git a/mojo/edk/system/request_context.cc b/mojo/edk/system/request_context.cc index 4ae8713..c30d8bb8 100644 --- a/mojo/edk/system/request_context.cc +++ b/mojo/edk/system/request_context.cc
@@ -18,11 +18,11 @@ } // namespace -RequestContext::RequestContext() { +RequestContext::RequestContext() : tls_context_(g_current_context.Pointer()){ // We allow nested RequestContexts to exist as long as they aren't actually // used for anything. - if (!g_current_context.Pointer()->Get()) - g_current_context.Pointer()->Set(this); + if (!tls_context_->Get()) + tls_context_->Set(this); } RequestContext::~RequestContext() { @@ -30,7 +30,7 @@ // EDK requests on this thread, so we need to reset the thread-local context // pointer before calling them. if (IsCurrent()) - g_current_context.Pointer()->Set(nullptr); + tls_context_->Set(nullptr); for (const WatchNotifyFinalizer& watch : watch_notify_finalizers_.container()) { @@ -66,7 +66,7 @@ } bool RequestContext::IsCurrent() const { - return g_current_context.Pointer()->Get() == this; + return tls_context_->Get() == this; } RequestContext::WatchNotifyFinalizer::WatchNotifyFinalizer(
diff --git a/mojo/edk/system/request_context.h b/mojo/edk/system/request_context.h index 75ba61f..56b84987 100644 --- a/mojo/edk/system/request_context.h +++ b/mojo/edk/system/request_context.h
@@ -10,6 +10,10 @@ #include "mojo/edk/system/handle_signals_state.h" #include "mojo/edk/system/watcher.h" +namespace base { +template<typename T> class ThreadLocalPointer; +} + namespace mojo { namespace edk { @@ -73,6 +77,11 @@ WatchNotifyFinalizerList watch_notify_finalizers_; WatchCancelFinalizerList watch_cancel_finalizers_; + // Pointer to the TLS context. Although this can easily be accessed via the + // global LazyInstance, accessing a LazyInstance has a large cost relative to + // the rest of this class and its usages. + base::ThreadLocalPointer<RequestContext>* tls_context_; + DISALLOW_COPY_AND_ASSIGN(RequestContext); };
diff --git a/mojo/mojo_base.gyp b/mojo/mojo_base.gyp index 6ca027f..532d44a 100644 --- a/mojo/mojo_base.gyp +++ b/mojo/mojo_base.gyp
@@ -182,7 +182,7 @@ 'services/package_manager/public/interfaces/catalog.mojom', 'services/package_manager/public/interfaces/resolver.mojom', 'services/package_manager/public/interfaces/shell_resolver.mojom', - 'shell/public/interfaces/application_manager.mojom', + 'shell/public/interfaces/connector.mojom', 'shell/public/interfaces/interface_provider.mojom', 'shell/public/interfaces/shell.mojom', 'shell/public/interfaces/shell_client.mojom',
diff --git a/mojo/mojo_edk_tests.gyp b/mojo/mojo_edk_tests.gyp index 0353703..755ee40 100644 --- a/mojo/mojo_edk_tests.gyp +++ b/mojo/mojo_edk_tests.gyp
@@ -150,6 +150,7 @@ 'dependencies': [ '../testing/gtest.gyp:gtest', 'mojo_edk.gyp:mojo_run_all_unittests', + 'mojo_public.gyp:mojo_cpp_system', 'mojo_public.gyp:mojo_public_test_utils', ], 'sources': [
diff --git a/mojo/mojo_public.gyp b/mojo/mojo_public.gyp index a02144a..b9c5b8b4 100644 --- a/mojo/mojo_public.gyp +++ b/mojo/mojo_public.gyp
@@ -74,8 +74,8 @@ }, { # GN version: //mojo/public/cpp/system - 'target_name': 'mojo_system_cpp_headers', - 'type': 'none', + 'target_name': 'mojo_cpp_system', + 'type': 'static_library', 'sources': [ 'public/cpp/system/buffer.h', 'public/cpp/system/core.h', @@ -84,8 +84,11 @@ 'public/cpp/system/handle.h', 'public/cpp/system/macros.h', 'public/cpp/system/message_pipe.h', + 'public/cpp/system/watcher.cc', + 'public/cpp/system/watcher.h', ], 'dependencies': [ + '../base/base.gyp:base', 'mojo_system_headers', ], }, @@ -187,7 +190,7 @@ ], 'dependencies': [ '../base/base.gyp:base', - 'mojo_message_pump_lib', + 'mojo_cpp_system', 'mojo_interface_bindings_cpp_sources', ], },
diff --git a/mojo/mojo_shell.gyp b/mojo/mojo_shell.gyp index b72fe3c..7080eaa9 100644 --- a/mojo/mojo_shell.gyp +++ b/mojo/mojo_shell.gyp
@@ -12,8 +12,6 @@ 'services/package_manager/package_manager.cc', 'services/package_manager/package_manager.h', 'shell/loader.h', - 'shell/application_manager.cc', - 'shell/application_manager.h', 'shell/connect_params.cc', 'shell/connect_params.h', 'shell/connect_util.cc', @@ -22,6 +20,8 @@ 'shell/identity.h', 'shell/native_runner.h', 'shell/native_runner_delegate.h', + 'shell/shell.cc', + 'shell/shell.h', 'shell/switches.cc', 'shell/switches.cc', 'util/filename_util.cc', @@ -77,9 +77,9 @@ ], 'dependencies': [ 'mojo_runner_common_lib', - 'mojo_runner_connection_bindings_lib', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/mojo/mojo_base.gyp:mojo_application_base', + '<(DEPTH)/mojo/mojo_base.gyp:mojo_application_bindings', '<(DEPTH)/mojo/mojo_edk.gyp:mojo_system_impl', '<(DEPTH)/mojo/mojo_platform_handle.gyp:platform_handle', '<(DEPTH)/mojo/mojo_public.gyp:mojo_message_pump_lib', @@ -95,26 +95,6 @@ '..', ], }, { - 'target_name': 'mojo_runner_connection_bindings_lib', - 'type': 'static_library', - 'dependencies': [ - 'mojo_runner_connection_mojom', - ], - }, { - 'target_name': 'mojo_runner_connection_mojom', - 'type': 'none', - 'variables': { - 'mojom_files': [ - 'shell/runner/child/child_controller.mojom', - ], - }, - 'includes': [ - 'mojom_bindings_generator_explicit.gypi', - ], - 'dependencies': [ - '<(DEPTH)/mojo/mojo_base.gyp:mojo_application_base', - ], - }, { 'target_name': 'mojo_runner_host_lib', 'type': 'static_library', 'sources': [ @@ -135,7 +115,6 @@ ], 'dependencies': [ 'mojo_runner_common_lib', - 'mojo_runner_connection_bindings_lib', 'mojo_shell_lib', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n',
diff --git a/mojo/mojo_variables.gypi b/mojo/mojo_variables.gypi index 36dc4ea..66ec138 100644 --- a/mojo/mojo_variables.gypi +++ b/mojo/mojo_variables.gypi
@@ -45,6 +45,7 @@ '<(DEPTH)/mojo/public/c/system/tests/macros_unittest.cc', '<(DEPTH)/mojo/public/cpp/system/tests/core_unittest.cc', '<(DEPTH)/mojo/public/cpp/system/tests/macros_unittest.cc', + '<(DEPTH)/mojo/public/cpp/system/tests/watcher_unittest.cc', ], }, }
diff --git a/mojo/public/cpp/bindings/BUILD.gn b/mojo/public/cpp/bindings/BUILD.gn index b1726213..137d8d34 100644 --- a/mojo/public/cpp/bindings/BUILD.gn +++ b/mojo/public/cpp/bindings/BUILD.gn
@@ -101,7 +101,6 @@ deps = [ "//base", - "//mojo/message_pump", "//mojo/public/interfaces/bindings:bindings_cpp_sources", ] }
diff --git a/mojo/public/cpp/bindings/array.h b/mojo/public/cpp/bindings/array.h index a18d6ca..cb611c6 100644 --- a/mojo/public/cpp/bindings/array.h +++ b/mojo/public/cpp/bindings/array.h
@@ -25,7 +25,7 @@ // meaning that no value has been assigned to it. Null is distinct from empty. template <typename T> class Array { - MOJO_MOVE_ONLY_TYPE(Array) + MOVE_ONLY_TYPE_FOR_CPP_03(Array); public: using ConstRefType = typename std::vector<T>::const_reference; using RefType = typename std::vector<T>::reference;
diff --git a/mojo/public/cpp/bindings/associated_binding.h b/mojo/public/cpp/bindings/associated_binding.h index a135dfb..6af95cc9 100644 --- a/mojo/public/cpp/bindings/associated_binding.h +++ b/mojo/public/cpp/bindings/associated_binding.h
@@ -110,7 +110,7 @@ endpoint_client_.reset(); connection_error_handler_.reset(); - return request.Pass(); + return request; } // Sets an error handler that will be called if a connection error occurs.
diff --git a/mojo/public/cpp/bindings/binding.h b/mojo/public/cpp/bindings/binding.h index b16638c..3739331 100644 --- a/mojo/public/cpp/bindings/binding.h +++ b/mojo/public/cpp/bindings/binding.h
@@ -31,7 +31,7 @@ // class FooImpl : public Foo { // public: // explicit FooImpl(InterfaceRequest<Foo> request) -// : binding_(this, request.Pass()) {} +// : binding_(this, std::move(request)) {} // // // Foo implementation here. // @@ -42,7 +42,7 @@ // class MyFooFactory : public InterfaceFactory<Foo> { // public: // void Create(..., InterfaceRequest<Foo> request) override { -// auto f = new FooImpl(request.Pass()); +// auto f = new FooImpl(std::move(request)); // // Do something to manage the lifetime of |f|. Use StrongBinding<> to // // delete FooImpl on connection errors. // }
diff --git a/mojo/public/cpp/bindings/interface_ptr.h b/mojo/public/cpp/bindings/interface_ptr.h index 1c892fa..4aba1ff 100644 --- a/mojo/public/cpp/bindings/interface_ptr.h +++ b/mojo/public/cpp/bindings/interface_ptr.h
@@ -33,7 +33,7 @@ // any thread. template <typename Interface> class InterfacePtr { - DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(InterfacePtr) + DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(InterfacePtr); public: using GenericInterface = typename Interface::GenericInterface;
diff --git a/mojo/public/cpp/bindings/interface_ptr_info.h b/mojo/public/cpp/bindings/interface_ptr_info.h index c94a5ac..4d559f5 100644 --- a/mojo/public/cpp/bindings/interface_ptr_info.h +++ b/mojo/public/cpp/bindings/interface_ptr_info.h
@@ -17,7 +17,7 @@ // interface implementation, which could be used to construct an InterfacePtr. template <typename Interface> class InterfacePtrInfo { - MOJO_MOVE_ONLY_TYPE(InterfacePtrInfo); + MOVE_ONLY_TYPE_FOR_CPP_03(InterfacePtrInfo); public: InterfacePtrInfo() : version_(0u) {}
diff --git a/mojo/public/cpp/bindings/interface_request.h b/mojo/public/cpp/bindings/interface_request.h index c8bb46c..a2b617bc 100644 --- a/mojo/public/cpp/bindings/interface_request.h +++ b/mojo/public/cpp/bindings/interface_request.h
@@ -19,7 +19,7 @@ // if the client did not provide a message pipe. template <typename Interface> class InterfaceRequest { - MOJO_MOVE_ONLY_TYPE(InterfaceRequest) + MOVE_ONLY_TYPE_FOR_CPP_03(InterfaceRequest); public: // Constructs an empty InterfaceRequest, representing that the client is not // requesting an implementation of Interface. @@ -107,8 +107,8 @@ // CollectorPtr collector = ...; // Connect to Collector. // SourcePtr source; // InterfaceRequest<Source> source_request = GetProxy(&source); -// collector->RegisterSource(source.Pass()); -// CreateSource(source_request.Pass()); // Create implementation locally. +// collector->RegisterSource(std::move(source)); +// CreateSource(std::move(source_request)); // Create implementation locally. // template <typename Interface> InterfaceRequest<typename Interface::GenericInterface>
diff --git a/mojo/public/cpp/bindings/lib/associated_interface_ptr_state.h b/mojo/public/cpp/bindings/lib/associated_interface_ptr_state.h index 0bfc12be..caa4ce82 100644 --- a/mojo/public/cpp/bindings/lib/associated_interface_ptr_state.h +++ b/mojo/public/cpp/bindings/lib/associated_interface_ptr_state.h
@@ -97,7 +97,7 @@ AssociatedInterfacePtrInfo<GenericInterface> result; result.set_version(version_); AssociatedInterfacePtrInfoHelper::SetHandle(&result, std::move(handle)); - return result.Pass(); + return result; } bool is_bound() const { return !!endpoint_client_; }
diff --git a/mojo/public/cpp/bindings/lib/binding_state.h b/mojo/public/cpp/bindings/lib/binding_state.h index 055efc7..84a8a36 100644 --- a/mojo/public/cpp/bindings/lib/binding_state.h +++ b/mojo/public/cpp/bindings/lib/binding_state.h
@@ -192,7 +192,7 @@ MakeRequest<GenericInterface>(router_->PassMessagePipe()); router_ = nullptr; connection_error_handler_.reset(); - return request.Pass(); + return request; } void set_connection_error_handler(const Closure& error_handler) {
diff --git a/mojo/public/cpp/bindings/lib/connector.cc b/mojo/public/cpp/bindings/lib/connector.cc index 7f9a9c30..812b4c11 100644 --- a/mojo/public/cpp/bindings/lib/connector.cc +++ b/mojo/public/cpp/bindings/lib/connector.cc
@@ -11,6 +11,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/synchronization/lock.h" +#include "base/thread_task_runner_handle.h" #include "mojo/public/cpp/bindings/lib/sync_handle_watcher.h" namespace mojo { @@ -247,7 +248,7 @@ return SyncHandleWatcher::current()->WatchAllHandles(should_stop_array, 2); } -void Connector::OnHandleWatcherHandleReady(MojoResult result) { +void Connector::OnWatcherHandleReady(MojoResult result) { OnHandleReadyInternal(result); } @@ -273,12 +274,21 @@ } void Connector::WaitToReadMore() { - CHECK(!handle_watcher_.is_watching()); CHECK(!paused_); - handle_watcher_.Start(message_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, - MOJO_DEADLINE_INDEFINITE, - base::Bind(&Connector::OnHandleWatcherHandleReady, - base::Unretained(this))); + DCHECK(!handle_watcher_.IsWatching()); + + MojoResult rv = handle_watcher_.Start( + message_pipe_.get(), MOJO_HANDLE_SIGNAL_READABLE, + base::Bind(&Connector::OnWatcherHandleReady, + base::Unretained(this))); + + if (rv != MOJO_RESULT_OK) { + // If the watch failed because the handle is invalid or its conditions can + // no longer be met, we signal the error asynchronously to avoid reentry. + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(&Connector::OnWatcherHandleReady, + weak_factory_.GetWeakPtr(), rv)); + } if (register_sync_handle_watch_count_ > 0 && !registered_with_sync_handle_watcher_) { @@ -304,13 +314,6 @@ *read_result = rv; if (rv == MOJO_RESULT_OK) { - // Dispatching the message may spin in a nested message loop. To ensure we - // continue dispatching messages when this happens start listening for - // messagse now. - if (!handle_watcher_.is_watching()) { - // TODO: Need to evaluate the perf impact of this. - WaitToReadMore(); - } receiver_result = incoming_receiver_ && incoming_receiver_->Accept(&message); } @@ -344,21 +347,13 @@ if (paused_) return; - if (rv == MOJO_RESULT_SHOULD_WAIT) { - // ReadSingleMessage could end up calling HandleError which resets - // message_pipe_ to a dummy one that is closed. The old EDK will see the - // that the peer is closed immediately, while the new one is asynchronous - // because of thread hops. In that case, there'll still be an async - // waiter. - if (!handle_watcher_.is_watching()) - WaitToReadMore(); + if (rv == MOJO_RESULT_SHOULD_WAIT) break; - } } } void Connector::CancelWait() { - handle_watcher_.Stop(); + handle_watcher_.Cancel(); if (registered_with_sync_handle_watcher_) { SyncHandleWatcher::current()->UnregisterHandle(message_pipe_.get()); @@ -394,8 +389,6 @@ } if (force_async_handler) { - // |dummy_pipe.handle1| has been destructed. Reading the pipe will - // eventually cause a read error on |message_pipe_| and set error state. if (!paused_) WaitToReadMore(); } else {
diff --git a/mojo/public/cpp/bindings/lib/connector.h b/mojo/public/cpp/bindings/lib/connector.h index 2d2a5cc..2989d70 100644 --- a/mojo/public/cpp/bindings/lib/connector.h +++ b/mojo/public/cpp/bindings/lib/connector.h
@@ -9,10 +9,10 @@ #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" -#include "mojo/message_pump/handle_watcher.h" #include "mojo/public/cpp/bindings/callback.h" #include "mojo/public/cpp/bindings/message.h" #include "mojo/public/cpp/system/core.h" +#include "mojo/public/cpp/system/watcher.h" namespace base { class Lock; @@ -141,8 +141,8 @@ } private: - // Callback of mojo::common::HandleWatcher. - void OnHandleWatcherHandleReady(MojoResult result); + // Callback of mojo::Watcher. + void OnWatcherHandleReady(MojoResult result); // Callback of SyncHandleWatcher. void OnSyncHandleWatcherHandleReady(MojoResult result); void OnHandleReadyInternal(MojoResult result); @@ -169,7 +169,7 @@ ScopedMessagePipeHandle message_pipe_; MessageReceiver* incoming_receiver_; - common::HandleWatcher handle_watcher_; + Watcher handle_watcher_; bool error_; bool drop_writes_;
diff --git a/mojo/public/cpp/bindings/lib/filter_chain.h b/mojo/public/cpp/bindings/lib/filter_chain.h index bd7f9f5..99e8e73 100644 --- a/mojo/public/cpp/bindings/lib/filter_chain.h +++ b/mojo/public/cpp/bindings/lib/filter_chain.h
@@ -15,7 +15,7 @@ namespace internal { class FilterChain { - MOJO_MOVE_ONLY_TYPE(FilterChain) + MOVE_ONLY_TYPE_FOR_CPP_03(FilterChain) public: // Doesn't take ownership of |sink|. Therefore |sink| has to stay alive while
diff --git a/mojo/public/cpp/bindings/lib/template_util.h b/mojo/public/cpp/bindings/lib/template_util.h index 68390c1..cca06de0 100644 --- a/mojo/public/cpp/bindings/lib/template_util.h +++ b/mojo/public/cpp/bindings/lib/template_util.h
@@ -46,7 +46,7 @@ }; // A helper template to determine if given type is non-const move-only-type, -// i.e. if a value of the given type should be passed via .Pass() in a +// i.e. if a value of the given type should be passed via std::move() in a // destructive way. template <typename T> struct IsMoveOnlyType {
diff --git a/mojo/public/cpp/bindings/map.h b/mojo/public/cpp/bindings/map.h index 078da84..4c64d48 100644 --- a/mojo/public/cpp/bindings/map.h +++ b/mojo/public/cpp/bindings/map.h
@@ -26,7 +26,7 @@ // using the insert() method. template <typename Key, typename Value> class Map { - MOJO_MOVE_ONLY_TYPE(Map) + MOVE_ONLY_TYPE_FOR_CPP_03(Map); public: // Map keys cannot be move only classes. @@ -156,8 +156,7 @@ // Removes all contents from the Map and places them into parallel key/value // arrays. Each key will be copied from the source to the destination, and // values will be copied unless their type is designated move-only, in which - // case they will be passed by calling their Pass() method. Either way, the - // Map will be left in a null state. + // case they will be moved. Either way, the Map will be left in a null state. void DecomposeMapTo(mojo::Array<Key>* keys, mojo::Array<Value>* values) { std::vector<Key> key_vector; key_vector.reserve(map_.size());
diff --git a/mojo/public/cpp/bindings/strong_binding.h b/mojo/public/cpp/bindings/strong_binding.h index e5d6ffd..59ddb78 100644 --- a/mojo/public/cpp/bindings/strong_binding.h +++ b/mojo/public/cpp/bindings/strong_binding.h
@@ -28,7 +28,7 @@ // class StronglyBound : public Foo { // public: // explicit StronglyBound(InterfaceRequest<Foo> request) -// : binding_(this, request.Pass()) {} +// : binding_(this, std::move(request)) {} // // // Foo implementation here // @@ -39,8 +39,8 @@ // class MyFooFactory : public InterfaceFactory<Foo> { // public: // void Create(..., InterfaceRequest<Foo> request) override { -// new StronglyBound(request.Pass()); // The binding now owns the -// // instance of StronglyBound. +// new StronglyBound(std::move(request)); // The binding now owns the +// // instance of StronglyBound. // } // }; // @@ -48,7 +48,7 @@ // bound, it may be bound or destroyed on any thread. template <typename Interface> class StrongBinding { - MOJO_MOVE_ONLY_TYPE(StrongBinding) + MOVE_ONLY_TYPE_FOR_CPP_03(StrongBinding); public: explicit StrongBinding(Interface* impl) : binding_(impl) {}
diff --git a/mojo/public/cpp/bindings/struct_ptr.h b/mojo/public/cpp/bindings/struct_ptr.h index c57d34ca..3e907e0d 100644 --- a/mojo/public/cpp/bindings/struct_ptr.h +++ b/mojo/public/cpp/bindings/struct_ptr.h
@@ -28,7 +28,7 @@ // Smart pointer wrapping a mojom structure with move-only semantics. template <typename Struct> class StructPtr { - MOJO_MOVE_ONLY_TYPE(StructPtr) + MOVE_ONLY_TYPE_FOR_CPP_03(StructPtr); public: @@ -117,7 +117,7 @@ // Designed to be used when Struct is small and copyable. template <typename Struct> class InlinedStructPtr { - MOJO_MOVE_ONLY_TYPE(InlinedStructPtr); + MOVE_ONLY_TYPE_FOR_CPP_03(InlinedStructPtr); public:
diff --git a/mojo/public/cpp/bindings/tests/container_test_util.h b/mojo/public/cpp/bindings/tests/container_test_util.h index 8a77f7e7..ff46b8f 100644 --- a/mojo/public/cpp/bindings/tests/container_test_util.h +++ b/mojo/public/cpp/bindings/tests/container_test_util.h
@@ -7,6 +7,7 @@ #include <stddef.h> +#include "base/move.h" #include "mojo/public/cpp/system/macros.h" namespace mojo { @@ -30,7 +31,7 @@ }; class MoveOnlyType { - MOJO_MOVE_ONLY_TYPE(MoveOnlyType) + MOVE_ONLY_TYPE_FOR_CPP_03(MoveOnlyType); public: typedef MoveOnlyType Data_; MoveOnlyType();
diff --git a/mojo/public/cpp/bindings/tests/versioning_test_service.cc b/mojo/public/cpp/bindings/tests/versioning_test_service.cc index 7d4b3c0..bf3ca87 100644 --- a/mojo/public/cpp/bindings/tests/versioning_test_service.cc +++ b/mojo/public/cpp/bindings/tests/versioning_test_service.cc
@@ -5,6 +5,7 @@ #include <stdint.h> #include <map> +#include <utility> #include "mojo/public/c/system/main.h" #include "mojo/public/cpp/bindings/strong_binding.h" @@ -33,7 +34,7 @@ public: explicit HumanResourceDatabaseImpl( InterfaceRequest<HumanResourceDatabase> request) - : strong_binding_(this, request.Pass()) { + : strong_binding_(this, std::move(request)) { // Pretend that there is already some data in the system. EmployeeInfo* info = new EmployeeInfo(); employees_[1] = info; @@ -60,7 +61,7 @@ uint64_t id = employee->employee_id; if (employees_.find(id) == employees_.end()) employees_[id] = new EmployeeInfo(); - employees_[id]->employee = employee.Pass(); + employees_[id]->employee = std::move(employee); callback.Run(true); } @@ -83,7 +84,7 @@ callback.Run(false); return; } - employees_[id]->finger_print = finger_print.Pass(); + employees_[id]->finger_print = std::move(finger_print); callback.Run(true); } @@ -110,7 +111,7 @@ InterfaceRequest<HumanResourceDatabase> request) override { // It will be deleted automatically when the underlying pipe encounters a // connection error. - new HumanResourceDatabaseImpl(request.Pass()); + new HumanResourceDatabaseImpl(std::move(request)); } };
diff --git a/mojo/public/cpp/bindings/type_converter.h b/mojo/public/cpp/bindings/type_converter.h index 803d8f5..1446ab3 100644 --- a/mojo/public/cpp/bindings/type_converter.h +++ b/mojo/public/cpp/bindings/type_converter.h
@@ -47,7 +47,7 @@ // geometry::PointPtr result; // result->x = input.x(); // result->y = input.y(); -// return result.Pass(); +// return result; // } // }; // template <>
diff --git a/mojo/public/cpp/system/BUILD.gn b/mojo/public/cpp/system/BUILD.gn index d5298f2d..dc2d28c 100644 --- a/mojo/public/cpp/system/BUILD.gn +++ b/mojo/public/cpp/system/BUILD.gn
@@ -11,6 +11,8 @@ "handle.h", "macros.h", "message_pipe.h", + "watcher.cc", + "watcher.h", ] public_deps = [
diff --git a/mojo/public/cpp/system/handle.h b/mojo/public/cpp/system/handle.h index 801ebde3..989d0c54 100644 --- a/mojo/public/cpp/system/handle.h +++ b/mojo/public/cpp/system/handle.h
@@ -11,6 +11,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/move.h" #include "mojo/public/c/system/functions.h" #include "mojo/public/c/system/types.h" #include "mojo/public/cpp/system/macros.h" @@ -72,7 +73,7 @@ // like the C++11 |unique_ptr|. template <class HandleType> class ScopedHandleBase { - MOJO_MOVE_ONLY_TYPE(ScopedHandleBase) + MOVE_ONLY_TYPE_FOR_CPP_03(ScopedHandleBase); public: ScopedHandleBase() {}
diff --git a/mojo/public/cpp/system/macros.h b/mojo/public/cpp/system/macros.h index cdf7b886..931c978 100644 --- a/mojo/public/cpp/system/macros.h +++ b/mojo/public/cpp/system/macros.h
@@ -13,20 +13,6 @@ #include "mojo/public/c/system/macros.h" // Symbols exposed. -// Used to make a type non-copyable. See Chromium's base/move.h for more -// details. The MoveOnlyTypeForCPP03 typedef is for Chromium's base/callback.h -// to tell that this type is move-only, allowing these types to be bound or -// passed to Callbacks. -#define MOJO_MOVE_ONLY_TYPE(type) \ - private: \ - type(const type&) = delete; \ - void operator=(const type&) = delete; \ - \ - public: \ - typedef void MoveOnlyTypeForCPP03; \ - \ - private: - // The C++ standard requires that static const members have an out-of-class // definition (in a single compilation unit), but MSVC chokes on this (when // language extensions, which are required, are enabled). (You're only likely to @@ -50,15 +36,4 @@ #define MOJO_STATIC_CONST_MEMBER_DEFINITION #endif -namespace mojo { - -// Used to explicitly mark the return value of a function as unused. (You this -// if you are really sure you don't want to do anything with the return value of -// a function marked with |WARN_UNUSED_RESULT|. -template <typename T> -inline void ignore_result(const T&) { -} - -} // namespace mojo - #endif // MOJO_PUBLIC_CPP_SYSTEM_MACROS_H_
diff --git a/mojo/public/cpp/system/tests/BUILD.gn b/mojo/public/cpp/system/tests/BUILD.gn index 068f009..e7c8f29 100644 --- a/mojo/public/cpp/system/tests/BUILD.gn +++ b/mojo/public/cpp/system/tests/BUILD.gn
@@ -8,9 +8,11 @@ sources = [ "core_unittest.cc", "macros_unittest.cc", + "watcher_unittest.cc", ] deps = [ + "//base", "//mojo/public/c/system/tests", "//mojo/public/cpp/environment:standalone", "//mojo/public/cpp/system",
diff --git a/mojo/public/cpp/system/tests/macros_unittest.cc b/mojo/public/cpp/system/tests/macros_unittest.cc index 7a63e0d..30d7c844 100644 --- a/mojo/public/cpp/system/tests/macros_unittest.cc +++ b/mojo/public/cpp/system/tests/macros_unittest.cc
@@ -56,71 +56,11 @@ x.AlsoToBeOverridden(); } -// Note: MSVS is very strict (and arguably buggy) about warnings for classes -// defined in a local scope, so define these globally. -class MoveOnlyInt { - MOJO_MOVE_ONLY_TYPE(MoveOnlyInt) - - public: - MoveOnlyInt() : is_set_(false), value_() {} - explicit MoveOnlyInt(int value) : is_set_(true), value_(value) {} - ~MoveOnlyInt() {} - - // Move-only constructor and operator=. - MoveOnlyInt(MoveOnlyInt&& other) { *this = std::move(other); } - MoveOnlyInt& operator=(MoveOnlyInt&& other) { - if (&other != this) { - is_set_ = other.is_set_; - value_ = other.value_; - other.is_set_ = false; - } - return *this; - } - - int value() const { - assert(is_set()); - return value_; - } - bool is_set() const { return is_set_; } - - private: - bool is_set_; - int value_; -}; - -TEST(MacrosCppTest, MoveOnlyType) { - MoveOnlyInt x(123); - EXPECT_TRUE(x.is_set()); - EXPECT_EQ(123, x.value()); - MoveOnlyInt y; - EXPECT_FALSE(y.is_set()); - y = std::move(x); - EXPECT_FALSE(x.is_set()); - EXPECT_TRUE(y.is_set()); - EXPECT_EQ(123, y.value()); - MoveOnlyInt z(std::move(y)); - EXPECT_FALSE(y.is_set()); - EXPECT_TRUE(z.is_set()); - EXPECT_EQ(123, z.value()); -} - // Use it, to make sure things get linked in and to avoid any warnings about // unused things. TEST(MacrosCppTest, StaticConstMemberDefinition) { EXPECT_EQ(123, StructWithStaticConstMember::kStaticConstMember); } -// The test for |ignore_result()| is also just a compilation test. (Note that -// |WARN_UNUSED_RESULT| can only be used in the prototype. -int ReturnsIntYouMustUse() WARN_UNUSED_RESULT; - -int ReturnsIntYouMustUse() { - return 123; -} - -TEST(MacrosCppTest, IgnoreResult) { - ignore_result(ReturnsIntYouMustUse()); -} - } // namespace } // namespace mojo
diff --git a/mojo/public/cpp/system/tests/watcher_unittest.cc b/mojo/public/cpp/system/tests/watcher_unittest.cc new file mode 100644 index 0000000..ea78a56 --- /dev/null +++ b/mojo/public/cpp/system/tests/watcher_unittest.cc
@@ -0,0 +1,186 @@ +// 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 "base/bind.h" +#include "base/callback.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "base/thread_task_runner_handle.h" +#include "mojo/public/c/system/types.h" +#include "mojo/public/cpp/system/message_pipe.h" +#include "mojo/public/cpp/system/watcher.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace mojo { +namespace { + +template <typename Handler> +void RunResultHandler(Handler f, MojoResult result) { f(result); } + +template <typename Handler> +Watcher::ReadyCallback OnReady(Handler f) { + return base::Bind(&RunResultHandler<Handler>, f); +} + +Watcher::ReadyCallback NotReached() { + return OnReady([] (MojoResult) { NOTREACHED(); }); +} + +class WatcherTest : public testing::Test { + public: + WatcherTest() {} + ~WatcherTest() override {} + + void SetUp() override { + message_loop_.reset(new base::MessageLoop); + } + + void TearDown() override { + message_loop_.reset(); + } + + protected: + scoped_ptr<base::MessageLoop> message_loop_; +}; + +TEST_F(WatcherTest, WatchBasic) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + + bool notified = false; + base::RunLoop run_loop; + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_OK, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + OnReady([&] (MojoResult result) { + EXPECT_EQ(MOJO_RESULT_OK, result); + notified = true; + run_loop.Quit(); + }))); + EXPECT_TRUE(b_watcher.IsWatching()); + + EXPECT_EQ(MOJO_RESULT_OK, WriteMessageRaw(a.get(), "hello", 5, nullptr, 0, + MOJO_WRITE_MESSAGE_FLAG_NONE)); + run_loop.Run(); + EXPECT_TRUE(notified); + + b_watcher.Cancel(); +} + +TEST_F(WatcherTest, WatchUnsatisfiable) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + a.reset(); + + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_FAILED_PRECONDITION, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + NotReached())); + EXPECT_FALSE(b_watcher.IsWatching()); +} + +TEST_F(WatcherTest, WatchInvalidHandle) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + a.reset(); + b.reset(); + + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + NotReached())); + EXPECT_FALSE(b_watcher.IsWatching()); +} + +TEST_F(WatcherTest, Cancel) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + + base::RunLoop run_loop; + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_OK, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + NotReached())); + EXPECT_TRUE(b_watcher.IsWatching()); + b_watcher.Cancel(); + EXPECT_FALSE(b_watcher.IsWatching()); + + // This should never trigger the watcher. + EXPECT_EQ(MOJO_RESULT_OK, WriteMessageRaw(a.get(), "hello", 5, nullptr, 0, + MOJO_WRITE_MESSAGE_FLAG_NONE)); + + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); +} + +TEST_F(WatcherTest, CancelOnClose) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + + base::RunLoop run_loop; + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_OK, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + OnReady([&] (MojoResult result) { + EXPECT_EQ(MOJO_RESULT_CANCELLED, result); + run_loop.Quit(); + }))); + EXPECT_TRUE(b_watcher.IsWatching()); + + // This should trigger the watcher above. + b.reset(); + + run_loop.Run(); + + EXPECT_FALSE(b_watcher.IsWatching()); +} + +TEST_F(WatcherTest, CancelOnDestruction) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + base::RunLoop run_loop; + { + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_OK, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + NotReached())); + EXPECT_TRUE(b_watcher.IsWatching()); + + // |b_watcher| should be cancelled when it goes out of scope. + } + + // This should never trigger the watcher above. + EXPECT_EQ(MOJO_RESULT_OK, WriteMessageRaw(a.get(), "hello", 5, nullptr, 0, + MOJO_WRITE_MESSAGE_FLAG_NONE)); + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, run_loop.QuitClosure()); + run_loop.Run(); +} + +TEST_F(WatcherTest, NotifyOnMessageLoopDestruction) { + ScopedMessagePipeHandle a, b; + CreateMessagePipe(nullptr, &a, &b); + + bool notified = false; + Watcher b_watcher; + EXPECT_EQ(MOJO_RESULT_OK, + b_watcher.Start(b.get(), MOJO_HANDLE_SIGNAL_READABLE, + OnReady([&] (MojoResult result) { + EXPECT_EQ(MOJO_RESULT_ABORTED, result); + notified = true; + }))); + EXPECT_TRUE(b_watcher.IsWatching()); + + message_loop_.reset(); + + EXPECT_TRUE(notified); + + EXPECT_TRUE(b_watcher.IsWatching()); + b_watcher.Cancel(); +} + +} // namespace +} // namespace mojo
diff --git a/mojo/public/cpp/system/watcher.cc b/mojo/public/cpp/system/watcher.cc new file mode 100644 index 0000000..ad965ff --- /dev/null +++ b/mojo/public/cpp/system/watcher.cc
@@ -0,0 +1,134 @@ +// 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 "mojo/public/cpp/system/watcher.h" + +#include "base/bind.h" +#include "base/location.h" +#include "base/macros.h" +#include "base/message_loop/message_loop.h" +#include "base/thread_task_runner_handle.h" +#include "mojo/public/c/system/functions.h" + +namespace mojo { + +class Watcher::MessageLoopObserver + : public base::MessageLoop::DestructionObserver { + public: + explicit MessageLoopObserver(Watcher* watcher) : watcher_(watcher) { + base::MessageLoop::current()->AddDestructionObserver(this); + } + + ~MessageLoopObserver() override { + StopObservingIfNecessary(); + } + + private: + // base::MessageLoop::DestructionObserver: + void WillDestroyCurrentMessageLoop() override { + StopObservingIfNecessary(); + if (watcher_->IsWatching()) + watcher_->OnHandleReady(MOJO_RESULT_ABORTED); + } + + void StopObservingIfNecessary() { + if (is_observing_) { + is_observing_ = false; + base::MessageLoop::current()->RemoveDestructionObserver(this); + } + } + + bool is_observing_ = true; + Watcher* watcher_; + + DISALLOW_COPY_AND_ASSIGN(MessageLoopObserver); +}; + +Watcher::Watcher() + : task_runner_(base::ThreadTaskRunnerHandle::Get()), + weak_factory_(this) { + weak_self_ = weak_factory_.GetWeakPtr(); +} + +Watcher::~Watcher() { + if(IsWatching()) + Cancel(); +} + +bool Watcher::IsWatching() const { + DCHECK(thread_checker_.CalledOnValidThread()); + return handle_.is_valid(); +} + +MojoResult Watcher::Start(Handle handle, + MojoHandleSignals signals, + const ReadyCallback& callback) { + DCHECK(thread_checker_.CalledOnValidThread()); + DCHECK(!IsWatching()); + DCHECK(!callback.is_null()); + + message_loop_observer_.reset(new MessageLoopObserver(this)); + callback_ = callback; + handle_ = handle; + MojoResult result = MojoWatch(handle_.value(), signals, + &Watcher::CallOnHandleReady, + reinterpret_cast<uintptr_t>(this)); + if (result != MOJO_RESULT_OK) { + handle_.set_value(kInvalidHandleValue); + callback_.Reset(); + message_loop_observer_.reset(); + DCHECK(result == MOJO_RESULT_FAILED_PRECONDITION || + result == MOJO_RESULT_INVALID_ARGUMENT); + return result; + } + + return MOJO_RESULT_OK; +} + +void Watcher::Cancel() { + DCHECK(thread_checker_.CalledOnValidThread()); + + // The watch may have already been cancelled if the handle was closed. + if (!handle_.is_valid()) + return; + + MojoResult result = + MojoCancelWatch(handle_.value(), reinterpret_cast<uintptr_t>(this)); + message_loop_observer_.reset(); + DCHECK_EQ(result, MOJO_RESULT_OK); + handle_.set_value(kInvalidHandleValue); + callback_.Reset(); +} + +void Watcher::OnHandleReady(MojoResult result) { + DCHECK(thread_checker_.CalledOnValidThread()); + + ReadyCallback callback = callback_; + if (result == MOJO_RESULT_CANCELLED) { + message_loop_observer_.reset(); + handle_.set_value(kInvalidHandleValue); + callback_.Reset(); + } + + // NOTE: It's legal for |callback| to delete |this|. + if (!callback.is_null()) + callback.Run(result); +} + +// static +void Watcher::CallOnHandleReady(uintptr_t context, + MojoResult result, + MojoHandleSignalsState signals_state) { + // NOTE: It is safe to assume the Watcher still exists because this callback + // will never be run after the Watcher's destructor. + // + // TODO: Maybe we should also expose |signals_state| throught he Watcher API. + // Current HandleWatcher users have no need for it, so it's omitted here. + Watcher* watcher = reinterpret_cast<Watcher*>(context); + watcher->task_runner_->PostTask( + FROM_HERE, + base::Bind(&Watcher::OnHandleReady, watcher->weak_self_, result)); +} + +} // namespace mojo
diff --git a/mojo/public/cpp/system/watcher.h b/mojo/public/cpp/system/watcher.h new file mode 100644 index 0000000..cd068aa --- /dev/null +++ b/mojo/public/cpp/system/watcher.h
@@ -0,0 +1,117 @@ +// 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 MOJO_PUBLIC_CPP_SYSTEM_WATCHER_H_ +#define MOJO_PUBLIC_CPP_SYSTEM_WATCHER_H_ + +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/single_thread_task_runner.h" +#include "base/threading/thread_checker.h" +#include "mojo/public/c/system/types.h" +#include "mojo/public/cpp/system/handle.h" + +namespace mojo { + +// A Watcher watches a single Mojo handle for signal state changes. +// +// NOTE: Watchers may only be used on threads which have a running MessageLoop. +class Watcher { + public: + // A callback to be called any time a watched handle changes state in some + // interesting way. The |result| argument indicates one of the following + // conditions depending on its value: + // + // |MOJO_RESULT_OK|: One or more of the signals being watched is satisfied. + // + // |MOJO_RESULT_FAILED_PRECONDITION|: None of the signals being watched can + // ever be satisfied again. + // + // |MOJO_RESULT_CANCELLED|: The handle has been closed and the watch has + // been cancelled implicitly. + // + // |MOJO_RESULT_ABORTED|: Notifications can no longer be delivered for this + // watcher for some unspecified reason, e.g., the watching thread may + // be shutting down soon. Note that it is still necessary to explicitly + // Cancel() the watch in this case. + using ReadyCallback = base::Callback<void(MojoResult result)>; + + // TODO(rockot/yzshen): Support giving Watcher an explicit TaskRunner for + // more fine-grained control over dispatch behavior. + Watcher(); + + // NOTE: This destructor automatically calls |Cancel()| if the Watcher is + // still active. + ~Watcher(); + + // Indicates if the Watcher is currently watching a handle. + bool IsWatching() const; + + // Starts watching |handle|. A Watcher may only watch one handle at a time, + // but it is safe to call this more than once as long as the previous watch + // has been cancelled (i.e. |is_watching()| returns |false|.) + // + // If no signals in |signals| can ever be satisfied for |handle|, this returns + // |MOJO_RESULT_FAILED_PRECONDITION|. + // + // If |handle| is not a valid watchable (message or data pipe) handle, this + // returns |MOJO_RESULT_INVALID_ARGUMENT|. + // + // Otherwise |MOJO_RESULT_OK| is returned and the handle will be watched until + // closure or cancellation. + // + // Once the watch is started, |callback| may be called at any time on the + // current thread until |Cancel()| is called or the handle is closed. + // + // Destroying the Watcher implicitly calls |Cancel()|. + MojoResult Start(Handle handle, + MojoHandleSignals signals, + const ReadyCallback& callback); + + // Cancels the current watch. Once this returns, the callback previously + // passed to |Start()| will never be called again for this Watcher. + void Cancel(); + + private: + class MessageLoopObserver; + friend class MessageLoopObserver; + + void OnHandleReady(MojoResult result); + + static void CallOnHandleReady(uintptr_t context, + MojoResult result, + MojoHandleSignalsState signals_state); + + base::ThreadChecker thread_checker_; + + // The TaskRunner of this Watcher's owning thread. This field is safe to + // access from any thread. + const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; + + scoped_ptr<MessageLoopObserver> message_loop_observer_; + + // A persistent weak reference to this Watcher which can be passed to the + // Dispatcher any time this object should be signalled. Safe to access (but + // not to dereference!) from any thread. + base::WeakPtr<Watcher> weak_self_; + + // Fields below must only be accessed on the Watcher's owning thread. + + // The handle currently under watch. Not owned. + Handle handle_; + + // The callback to call when the handle is signaled. + ReadyCallback callback_; + + base::WeakPtrFactory<Watcher> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(Watcher); +}; + +} // namespace mojo + +#endif // MOJO_PUBLIC_CPP_SYSTEM_WATCHER_H_
diff --git a/mojo/services/network/network_service_delegate.cc b/mojo/services/network/network_service_delegate.cc index 806261dc..aadc5cac 100644 --- a/mojo/services/network/network_service_delegate.cc +++ b/mojo/services/network/network_service_delegate.cc
@@ -49,7 +49,8 @@ void NetworkServiceDelegate::Initialize(Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) { + const std::string& user_id, + uint32_t id) { // TODO(erg): Find everything else that writes to the filesystem and // transition it to proxying mojo:filesystem. We shouldn't have any path // calculation code here, but sadly need it until the transition is done. In
diff --git a/mojo/services/network/network_service_delegate.h b/mojo/services/network/network_service_delegate.h index 0c444ad..07e93b5 100644 --- a/mojo/services/network/network_service_delegate.h +++ b/mojo/services/network/network_service_delegate.h
@@ -36,7 +36,7 @@ private: // mojo::ShellClient implementation. void Initialize(Connector* connector, const std::string& url, - uint32_t id, uint32_t user_id) override; + const std::string& user_id, uint32_t id) override; bool AcceptConnection(Connection* connection) override; // InterfaceFactory<NetworkService> implementation.
diff --git a/mojo/shell/BUILD.gn b/mojo/shell/BUILD.gn index 60edc374..51c6c215 100644 --- a/mojo/shell/BUILD.gn +++ b/mojo/shell/BUILD.gn
@@ -20,8 +20,6 @@ source_set("shell") { output_name = "mojo_shell" sources = [ - "application_manager.cc", - "application_manager.h", "connect_params.cc", "connect_params.h", "connect_util.cc", @@ -31,6 +29,8 @@ "loader.h", "native_runner.h", "native_runner_delegate.h", + "shell.cc", + "shell.h", "switches.cc", "switches.h", ]
diff --git a/mojo/shell/background/background_shell.cc b/mojo/shell/background/background_shell.cc index e53d7f9..1d31de7 100644 --- a/mojo/shell/background/background_shell.cc +++ b/mojo/shell/background/background_shell.cc
@@ -13,11 +13,11 @@ #include "base/threading/simple_thread.h" #include "mojo/message_pump/message_pump_mojo.h" #include "mojo/services/package_manager/package_manager.h" -#include "mojo/shell/application_manager.h" #include "mojo/shell/connect_params.h" #include "mojo/shell/loader.h" #include "mojo/shell/public/cpp/shell_client.h" #include "mojo/shell/public/cpp/shell_connection.h" +#include "mojo/shell/shell.h" #include "mojo/shell/standalone/context.h" namespace mojo { @@ -81,14 +81,13 @@ // Only valid to call this on the background thread. DCHECK_EQ(message_loop_, base::MessageLoop::current()); - // Ownership of |loader| passes to ApplicationManager. + // Ownership of |loader| passes to Shell. const std::string name = params->target().name(); BackgroundLoader* loader = new BackgroundLoader( base::Bind(&MojoThread::OnGotApplicationRequest, base::Unretained(this), name, signal, request)); - context_->application_manager()->SetLoaderForName(make_scoped_ptr(loader), - name); - context_->application_manager()->Connect(std::move(params)); + context_->shell()->SetLoaderForName(make_scoped_ptr(loader), name); + context_->shell()->Connect(std::move(params)); // The request is asynchronously processed. When processed // OnGotApplicationRequest() is called and we'll signal |signal|. } @@ -146,7 +145,7 @@ mojom::ShellClientRequest actual_request) { *request_result = std::move(actual_request); // Trigger destruction of the loader. - context_->application_manager()->SetLoaderForName(nullptr, name); + context_->shell()->SetLoaderForName(nullptr, name); signal->Signal(); } @@ -179,8 +178,7 @@ mojom::ShellClientRequest BackgroundShell::CreateShellClientRequest( const std::string& name) { scoped_ptr<ConnectParams> params(new ConnectParams); - params->set_target(Identity(name, std::string(), - mojom::Connector::kUserRoot)); + params->set_target(Identity(name, std::string(), mojom::kRootUserID)); mojom::ShellClientRequest request; base::WaitableEvent signal(true, false); thread_->message_loop()->task_runner()->PostTask(
diff --git a/mojo/shell/connect_params.h b/mojo/shell/connect_params.h index 2c64404..b90ac32 100644 --- a/mojo/shell/connect_params.h +++ b/mojo/shell/connect_params.h
@@ -12,8 +12,8 @@ #include "base/macros.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/shell/identity.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" namespace mojo { namespace shell {
diff --git a/mojo/shell/connect_util.cc b/mojo/shell/connect_util.cc index c2a972df..e5210c69 100644 --- a/mojo/shell/connect_util.cc +++ b/mojo/shell/connect_util.cc
@@ -6,14 +6,14 @@ #include <utility> -#include "mojo/shell/application_manager.h" #include "mojo/shell/connect_params.h" +#include "mojo/shell/shell.h" namespace mojo { namespace shell { ScopedMessagePipeHandle ConnectToInterfaceByName( - ApplicationManager* application_manager, + Shell* shell, const Identity& source, const Identity& target, const std::string& interface_name) { @@ -22,7 +22,7 @@ params->set_source(source); params->set_target(target); params->set_remote_interfaces(GetProxy(&remote_interfaces)); - application_manager->Connect(std::move(params)); + shell->Connect(std::move(params)); MessagePipe pipe; remote_interfaces->GetInterface(interface_name, std::move(pipe.handle1)); return std::move(pipe.handle0);
diff --git a/mojo/shell/connect_util.h b/mojo/shell/connect_util.h index a81a13e..87df3d81 100644 --- a/mojo/shell/connect_util.h +++ b/mojo/shell/connect_util.h
@@ -8,40 +8,38 @@ #include "mojo/public/cpp/bindings/interface_ptr.h" #include "mojo/public/cpp/system/handle.h" #include "mojo/shell/identity.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mojo { namespace shell { -class ApplicationManager; +class Shell; ScopedMessagePipeHandle ConnectToInterfaceByName( - ApplicationManager* application_manager, + Shell* shell, const Identity& source, const Identity& target, const std::string& interface_name); // Must only be used by shell internals and test code as it does not forward -// capability filters. Runs |application_name| with a permissive capability -// filter. +// capability filters. Runs |name| with a permissive capability filter. template <typename Interface> -inline void ConnectToInterface(ApplicationManager* application_manager, +inline void ConnectToInterface(Shell* shell, const Identity& source, const Identity& target, InterfacePtr<Interface>* ptr) { - ScopedMessagePipeHandle service_handle = ConnectToInterfaceByName( - application_manager, source, target, Interface::Name_); + ScopedMessagePipeHandle service_handle = + ConnectToInterfaceByName(shell, source, target, Interface::Name_); ptr->Bind(InterfacePtrInfo<Interface>(std::move(service_handle), 0u)); } template <typename Interface> -inline void ConnectToInterface(ApplicationManager* application_manager, +inline void ConnectToInterface(Shell* shell, const Identity& source, - const std::string& application_name, + const std::string& name, InterfacePtr<Interface>* ptr) { ScopedMessagePipeHandle service_handle = ConnectToInterfaceByName( - application_manager, source, - Identity(application_name, std::string(), mojom::Connector::kUserInherit), + shell, source, Identity(name, std::string(), mojom::kInheritUserID), Interface::Name_); ptr->Bind(InterfacePtrInfo<Interface>(std::move(service_handle), 0u)); }
diff --git a/mojo/shell/identity.cc b/mojo/shell/identity.cc index c8c1fed..243565a 100644 --- a/mojo/shell/identity.cc +++ b/mojo/shell/identity.cc
@@ -5,7 +5,7 @@ #include "mojo/shell/identity.h" #include "mojo/shell/public/cpp/names.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mojo { namespace shell { @@ -13,10 +13,10 @@ Identity::Identity() {} Identity::Identity(const std::string& name) - : Identity(name, GetNamePath(name), mojom::Connector::kUserRoot) {} + : Identity(name, GetNamePath(name), mojom::kRootUserID) {} Identity::Identity(const std::string& name, const std::string& qualifier, - uint32_t user_id) + const std::string& user_id) : name_(name), qualifier_(qualifier.empty() ? GetNamePath(name_) : qualifier), user_id_(user_id) {} @@ -45,7 +45,7 @@ } Identity CreateShellIdentity() { - Identity id = Identity("mojo:shell", "", mojom::Connector::kUserRoot); + Identity id = Identity("mojo:shell", "", mojom::kRootUserID); id.set_filter(GetPermissiveCapabilityFilter()); return id; }
diff --git a/mojo/shell/identity.h b/mojo/shell/identity.h index 921c839b..7d33295d 100644 --- a/mojo/shell/identity.h +++ b/mojo/shell/identity.h
@@ -20,7 +20,6 @@ // more details. using CapabilityFilter = std::map<std::string, AllowedInterfaces>; - // Represents the identity of an application. // |name| is the structured name of the application. // |qualifier| is a string that allows to tie a specific instance of an @@ -31,12 +30,12 @@ class Identity { public: Identity(); - // Assumes user = mojom::Connector::kUserRoot. + // Assumes user = mojom::kRootUserID. // Used in tests or for shell-initiated connections. explicit Identity(const std::string& in_name); Identity(const std::string& in_name, const std::string& in_qualifier, - uint32_t user_id); + const std::string& user_id); Identity(const Identity& other); ~Identity(); @@ -45,8 +44,8 @@ bool operator==(const Identity& other) const; const std::string& name() const { return name_; } - uint32_t user_id() const { return user_id_; } - void set_user_id(uint32_t user_id) { user_id_ = user_id; } + const std::string& user_id() const { return user_id_; } + void set_user_id(const std::string& user_id) { user_id_ = user_id; } const std::string& qualifier() const { return qualifier_; } void set_filter(const CapabilityFilter& filter) { filter_ = filter; } const CapabilityFilter& filter() const { return filter_; } @@ -55,7 +54,7 @@ std::string name_; std::string qualifier_; - uint32_t user_id_; + std::string user_id_; // TODO(beng): CapabilityFilter is not currently included in equivalence // checks for Identity since we're not currently clear on the
diff --git a/mojo/shell/loader.h b/mojo/shell/loader.h index cec8fced..756c070 100644 --- a/mojo/shell/loader.h +++ b/mojo/shell/loader.h
@@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef SHELL_APPLICATION_MANAGER_LOADER_H_ -#define SHELL_APPLICATION_MANAGER_LOADER_H_ +#ifndef MOJO_SHELL_LOADER_H_ +#define MOJO_SHELL_LOADER_H_ #include "base/callback.h" #include "mojo/public/cpp/system/core.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/shell_client.mojom.h" namespace mojo { @@ -25,4 +25,4 @@ } // namespace shell } // namespace mojo -#endif // SHELL_APPLICATION_MANAGER_LOADER_H_ +#endif // MOJO_SHELL_LOADER_H_
diff --git a/mojo/shell/native_runner.h b/mojo/shell/native_runner.h index ff312d2..ce14f11 100644 --- a/mojo/shell/native_runner.h +++ b/mojo/shell/native_runner.h
@@ -10,6 +10,7 @@ #include "base/process/process_handle.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/shell/public/interfaces/shell_client.mojom.h" +#include "mojo/shell/public/interfaces/shell_client_factory.mojom.h" namespace base { class FilePath; @@ -20,8 +21,8 @@ class Identity; -// ApplicationManager requires implementations of NativeRunner and -// NativeRunnerFactory to run native applications. +// Shell requires implementations of NativeRunner and NativeRunnerFactory to run +// native applications. class NativeRunner { public: virtual ~NativeRunner() {} @@ -35,11 +36,6 @@ InterfaceRequest<mojom::ShellClient> request, const base::Callback<void(base::ProcessId)>& pid_available_callback, const base::Closure& app_completed_callback) = 0; - - // Like Start(), but used to initialize the host for a child process started - // by someone else. Provides |request| via |channel|. - virtual void InitHost(ScopedHandle channel, - InterfaceRequest<mojom::ShellClient> request) = 0; }; class NativeRunnerFactory {
diff --git a/mojo/shell/public/cpp/BUILD.gn b/mojo/shell/public/cpp/BUILD.gn index 994c7b3..576704c 100644 --- a/mojo/shell/public/cpp/BUILD.gn +++ b/mojo/shell/public/cpp/BUILD.gn
@@ -50,7 +50,6 @@ deps = [ "//base", "//base:i18n", - "//mojo/message_pump", ] public_deps = [
diff --git a/mojo/shell/public/cpp/application_test_base.h b/mojo/shell/public/cpp/application_test_base.h index 91160df..958c779 100644 --- a/mojo/shell/public/cpp/application_test_base.h +++ b/mojo/shell/public/cpp/application_test_base.h
@@ -34,9 +34,9 @@ ~TestHelper(); Connector* connector() { return shell_connection_->connector(); } - std::string test_name() { return name_; } + const std::string& test_name() { return name_; } + const std::string& test_userid() { return userid_; } uint32_t test_instance_id() { return instance_id_; } - uint32_t test_userid() { return userid_; } private: // The application delegate used if GetShellClient is not overridden. @@ -46,8 +46,8 @@ scoped_ptr<ShellConnection> shell_connection_; std::string name_; + std::string userid_; uint32_t instance_id_; - uint32_t userid_; DISALLOW_COPY_AND_ASSIGN(TestHelper); }; @@ -62,17 +62,16 @@ Connector* connector() { return test_helper_ ? test_helper_->connector() : nullptr; } - std::string test_name() const { - return test_helper_ ? test_helper_->test_name() : std::string(); + const std::string& test_name() const { + return test_helper_ ? test_helper_->test_name() : empty_; + } + const std::string& test_userid() const { + return test_helper_ ? test_helper_->test_userid() : inherit_user_id_; } uint32_t test_instance_id() const { return test_helper_ ? test_helper_->test_instance_id() : shell::mojom::Connector::kInvalidApplicationID; } - uint32_t test_userid() const { - return test_helper_ ? test_helper_->test_userid() : - shell::mojom::Connector::kUserInherit; - } // Get the ShellClient for the application to be tested. virtual ShellClient* GetShellClient(); @@ -88,6 +87,8 @@ private: scoped_ptr<TestHelper> test_helper_; + std::string empty_; + std::string inherit_user_id_ = shell::mojom::kInheritUserID; DISALLOW_COPY_AND_ASSIGN(ApplicationTestBase); };
diff --git a/mojo/shell/public/cpp/connection.h b/mojo/shell/public/cpp/connection.h index 1825d9b..066d1a18 100644 --- a/mojo/shell/public/cpp/connection.h +++ b/mojo/shell/public/cpp/connection.h
@@ -13,6 +13,7 @@ #include "base/memory/weak_ptr.h" #include "mojo/shell/public/cpp/connect.h" #include "mojo/shell/public/cpp/interface_registry.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" namespace mojo { @@ -81,25 +82,34 @@ // callback being fired, this will return the value passed via Connect(). // After the Connect() callback (call AddRemoteIDCallback to register one) // this will return the actual user id the shell ran the target as. - virtual uint32_t GetRemoteUserID() const = 0; + virtual const std::string& GetRemoteUserID() const = 0; // Register a handler to receive an error notification on the pipe to the // remote application's InterfaceProvider. - virtual void SetRemoteInterfaceProviderConnectionErrorHandler( - const Closure& handler) = 0; + virtual void SetConnectionLostClosure(const Closure& handler) = 0; - // Returns the id of the remote application. For Connections created via - // Shell::Connect(), this will not be determined until Connect()'s callback is - // run, and this function will return false. Use AddRemoteIDCallback() to - // schedule a callback to be run when the remote application id is available. - // A value of Shell::kInvalidApplicationID indicates the connection has not - // been established. + // Returns true if |result| has been modified to include the result of the + // connection (see mojo/shell/public/interfaces/connector.mojom for error + // codes), false if the connection is still pending and |result| has not been + // modified. Call AddConnectionCompletedClosure() to schedule a closure to be + // run when the connection is completed and the result is available. + virtual bool GetConnectionResult( + shell::mojom::ConnectResult* result) const = 0; + + // Returns true if |remote_id| has been modified to include the instance id of + // the remote application. For connections created via Connector::Connect(), + // this will not be determined until the connection has been completed by the + // shell. Use AddConnectionCompletedClosure() to schedule a closure to be run + // when the connection is completed and the remote id is available. Returns + // false if the connection has not yet been completed and |remote_id| is not + // modified. virtual bool GetRemoteApplicationID(uint32_t* remote_id) const = 0; - // See description in GetRemoteApplicationID()/ - // GetRemoteShellClientFactoryID(). If the ids are available, |callback| is - // run immediately. - virtual void AddRemoteIDCallback(const Closure& callback) = 0; + // Register a closure to be run when the connection has been completed by the + // shell and remote metadata is available. Useful only for connections created + // via Connector::Connect(). Once the connection is complete, metadata is + // available immediately. + virtual void AddConnectionCompletedClosure(const Closure& callback) = 0; // Returns true if the Shell allows |interface_name| to be exposed to the // remote application.
diff --git a/mojo/shell/public/cpp/connector.h b/mojo/shell/public/cpp/connector.h index 8f7fe64..94fdc9a 100644 --- a/mojo/shell/public/cpp/connector.h +++ b/mojo/shell/public/cpp/connector.h
@@ -6,7 +6,7 @@ #define MOJO_SHELL_PUBLIC_CPP_CONNECTOR_H_ #include "mojo/shell/public/cpp/connection.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mojo { @@ -34,12 +34,12 @@ ~ConnectParams(); const std::string& name() { return name_; } - void set_user_id(uint32_t user_id) { user_id_ = user_id; } - uint32_t user_id() const { return user_id_; } + void set_user_id(const std::string& user_id) { user_id_ = user_id; } + const std::string& user_id() const { return user_id_; } private: std::string name_; - uint32_t user_id_; + std::string user_id_; DISALLOW_COPY_AND_ASSIGN(ConnectParams); };
diff --git a/mojo/shell/public/cpp/lib/application_runner.cc b/mojo/shell/public/cpp/lib/application_runner.cc index 3a358608..dd9be48 100644 --- a/mojo/shell/public/cpp/lib/application_runner.cc +++ b/mojo/shell/public/cpp/lib/application_runner.cc
@@ -9,7 +9,6 @@ #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/process/launch.h" -#include "mojo/message_pump/message_pump_mojo.h" #include "mojo/shell/public/cpp/shell_client.h" #include "mojo/shell/public/cpp/shell_connection.h" @@ -20,7 +19,7 @@ ApplicationRunner::ApplicationRunner(ShellClient* client) : client_(scoped_ptr<ShellClient>(client)), - message_loop_type_(base::MessageLoop::TYPE_CUSTOM), + message_loop_type_(base::MessageLoop::TYPE_DEFAULT), has_run_(false) {} ApplicationRunner::~ApplicationRunner() {} @@ -49,10 +48,7 @@ { scoped_ptr<base::MessageLoop> loop; - if (message_loop_type_ == base::MessageLoop::TYPE_CUSTOM) - loop.reset(new base::MessageLoop(common::MessagePumpMojo::Create())); - else - loop.reset(new base::MessageLoop(message_loop_type_)); + loop.reset(new base::MessageLoop(message_loop_type_)); connection_.reset(new ShellConnection( client_.get(),
diff --git a/mojo/shell/public/cpp/lib/application_test_base.cc b/mojo/shell/public/cpp/lib/application_test_base.cc index ec54839..9e5b99c 100644 --- a/mojo/shell/public/cpp/lib/application_test_base.cc +++ b/mojo/shell/public/cpp/lib/application_test_base.cc
@@ -21,7 +21,7 @@ // Share the application name with multiple application tests. String g_name; uint32_t g_id = shell::mojom::Connector::kInvalidApplicationID; -uint32_t g_user_id = shell::mojom::Connector::kUserRoot; +String g_user_id = shell::mojom::kRootUserID; // ShellClient request handle passed from the shell in MojoMain, stored in // between SetUp()/TearDown() so we can (re-)intialize new ShellConnections. @@ -45,9 +45,9 @@ private: // shell::mojom::ShellClient implementation. void Initialize(shell::mojom::ConnectorPtr connector, - const mojo::String& name, - uint32_t id, - uint32_t user_id) override { + const String& name, + const String& user_id, + uint32_t id) override { g_name = name; g_id = id; g_user_id = user_id; @@ -57,7 +57,7 @@ void AcceptConnection( const String& requestor_name, - uint32_t requestor_user_id, + const String& requestor_user_id, uint32_t requestor_id, shell::mojom::InterfaceProviderRequest local_interfaces, shell::mojom::InterfaceProviderPtr remote_interfaces, @@ -119,11 +119,11 @@ client == nullptr ? &default_shell_client_ : client, std::move(g_shell_client_request))), name_(g_name), - instance_id_(g_id), - userid_(g_user_id) { + userid_(g_user_id), + instance_id_(g_id) { // Fake ShellClient initialization. shell::mojom::ShellClient* shell_client = shell_connection_.get(); - shell_client->Initialize(std::move(g_connector), g_name, g_id, g_user_id); + shell_client->Initialize(std::move(g_connector), g_name, g_user_id, g_id); } TestHelper::~TestHelper() {
diff --git a/mojo/shell/public/cpp/lib/connection_impl.cc b/mojo/shell/public/cpp/lib/connection_impl.cc index 8ac305f..e5fd42f 100644 --- a/mojo/shell/public/cpp/lib/connection_impl.cc +++ b/mojo/shell/public/cpp/lib/connection_impl.cc
@@ -23,14 +23,14 @@ const std::string& connection_name, const std::string& remote_name, uint32_t remote_id, - uint32_t remote_user_id, + const std::string& remote_user_id, shell::mojom::InterfaceProviderPtr remote_interfaces, shell::mojom::InterfaceProviderRequest local_interfaces, const std::set<std::string>& allowed_interfaces) : connection_name_(connection_name), remote_name_(remote_name), remote_id_(remote_id), - remote_ids_valid_( + connection_completed_( remote_id != shell::mojom::Connector::kInvalidApplicationID), remote_user_id_(remote_user_id), local_registry_(std::move(local_interfaces), this), @@ -41,16 +41,14 @@ weak_factory_(this) {} ConnectionImpl::ConnectionImpl() - : remote_id_(shell::mojom::Connector::kInvalidApplicationID), - remote_ids_valid_(false), - local_registry_(shell::mojom::InterfaceProviderRequest(), this), + : local_registry_(shell::mojom::InterfaceProviderRequest(), this), allow_all_interfaces_(true), weak_factory_(this) {} ConnectionImpl::~ConnectionImpl() {} shell::mojom::Connector::ConnectCallback ConnectionImpl::GetConnectCallback() { - return base::Bind(&ConnectionImpl::OnGotInstanceID, + return base::Bind(&ConnectionImpl::OnConnectionCompleted, weak_factory_.GetWeakPtr()); } @@ -65,29 +63,37 @@ return remote_name_; } -uint32_t ConnectionImpl::GetRemoteUserID() const { +const std::string& ConnectionImpl::GetRemoteUserID() const { return remote_user_id_; } -void ConnectionImpl::SetRemoteInterfaceProviderConnectionErrorHandler( - const Closure& handler) { +void ConnectionImpl::SetConnectionLostClosure(const Closure& handler) { remote_interfaces_.set_connection_error_handler(handler); } +bool ConnectionImpl::GetConnectionResult( + shell::mojom::ConnectResult* result) const { + if (!connection_completed_) + return false; + *result = result_; + return true; +} + + bool ConnectionImpl::GetRemoteApplicationID(uint32_t* remote_id) const { - if (!remote_ids_valid_) + if (!connection_completed_) return false; *remote_id = remote_id_; return true; } -void ConnectionImpl::AddRemoteIDCallback(const Closure& callback) { - if (remote_ids_valid_) { +void ConnectionImpl::AddConnectionCompletedClosure(const Closure& callback) { + if (connection_completed_) { callback.Run(); return; } - remote_id_callbacks_.push_back(callback); + connection_completed_callbacks_.push_back(callback); } bool ConnectionImpl::AllowsInterface(const std::string& interface_name) const { @@ -109,15 +115,17 @@ //////////////////////////////////////////////////////////////////////////////// // ConnectionImpl, private: -void ConnectionImpl::OnGotInstanceID(uint32_t target_application_id, - uint32_t target_user_id) { - DCHECK(!remote_ids_valid_); - remote_ids_valid_ = true; +void ConnectionImpl::OnConnectionCompleted(shell::mojom::ConnectResult result, + const std::string& target_user_id, + uint32_t target_application_id) { + DCHECK(!connection_completed_); + connection_completed_ = true; + result_ = result; remote_id_ = target_application_id; remote_user_id_= target_user_id; std::vector<Closure> callbacks; - callbacks.swap(remote_id_callbacks_); + callbacks.swap(connection_completed_callbacks_); for (auto callback : callbacks) callback.Run(); }
diff --git a/mojo/shell/public/cpp/lib/connection_impl.h b/mojo/shell/public/cpp/lib/connection_impl.h index 74140ff..c8e66d77 100644 --- a/mojo/shell/public/cpp/lib/connection_impl.h +++ b/mojo/shell/public/cpp/lib/connection_impl.h
@@ -12,8 +12,8 @@ #include "mojo/public/cpp/bindings/binding.h" #include "mojo/shell/public/cpp/connection.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" namespace mojo { namespace internal { @@ -30,7 +30,7 @@ ConnectionImpl(const std::string& connection_name, const std::string& remote_name, uint32_t remote_id, - uint32_t remote_user_id, + const std::string& remote_user_id, shell::mojom::InterfaceProviderPtr remote_interfaces, shell::mojom::InterfaceProviderRequest local_interfaces, const std::set<std::string>& allowed_interfaces); @@ -42,26 +42,28 @@ // Connection: const std::string& GetConnectionName() override; const std::string& GetRemoteApplicationName() override; - uint32_t GetRemoteUserID() const override; - void SetRemoteInterfaceProviderConnectionErrorHandler( - const Closure& handler) override; + const std::string& GetRemoteUserID() const override; + void SetConnectionLostClosure(const Closure& handler) override; + bool GetConnectionResult(shell::mojom::ConnectResult* result) const override; bool GetRemoteApplicationID(uint32_t* remote_id) const override; - void AddRemoteIDCallback(const Closure& callback) override; + void AddConnectionCompletedClosure(const Closure& callback) override; bool AllowsInterface(const std::string& interface_name) const override; shell::mojom::InterfaceProvider* GetRemoteInterfaces() override; InterfaceRegistry* GetLocalRegistry() override; base::WeakPtr<Connection> GetWeakPtr() override; - void OnGotInstanceID(uint32_t target_application_id, - uint32_t target_user_id); + void OnConnectionCompleted(shell::mojom::ConnectResult result, + const std::string& target_user_id, + uint32_t target_application_id); const std::string connection_name_; const std::string remote_name_; - uint32_t remote_id_; - bool remote_ids_valid_; - std::vector<Closure> remote_id_callbacks_; - uint32_t remote_user_id_; + shell::mojom::ConnectResult result_ = shell::mojom::ConnectResult::OK; + uint32_t remote_id_ = shell::mojom::Connector::kInvalidApplicationID; + bool connection_completed_ = false; + std::vector<Closure> connection_completed_callbacks_; + std::string remote_user_id_ = shell::mojom::kInheritUserID; InterfaceRegistry local_registry_; shell::mojom::InterfaceProviderPtr remote_interfaces_;
diff --git a/mojo/shell/public/cpp/lib/connector_impl.cc b/mojo/shell/public/cpp/lib/connector_impl.cc index 675017d4..d6d0e51 100644 --- a/mojo/shell/public/cpp/lib/connector_impl.cc +++ b/mojo/shell/public/cpp/lib/connector_impl.cc
@@ -10,7 +10,7 @@ Connector::ConnectParams::ConnectParams(const std::string& name) : name_(name), - user_id_(shell::mojom::Connector::kUserInherit) { + user_id_(shell::mojom::kInheritUserID) { } Connector::ConnectParams::~ConnectParams() {}
diff --git a/mojo/shell/public/cpp/lib/connector_impl.h b/mojo/shell/public/cpp/lib/connector_impl.h index 44f37b1..74db73de 100644 --- a/mojo/shell/public/cpp/lib/connector_impl.h +++ b/mojo/shell/public/cpp/lib/connector_impl.h
@@ -8,7 +8,7 @@ #include "base/callback.h" #include "base/threading/thread_checker.h" #include "mojo/shell/public/cpp/connector.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" namespace mojo {
diff --git a/mojo/shell/public/cpp/lib/shell_client.cc b/mojo/shell/public/cpp/lib/shell_client.cc index a06c875..f5441ce1 100644 --- a/mojo/shell/public/cpp/lib/shell_client.cc +++ b/mojo/shell/public/cpp/lib/shell_client.cc
@@ -10,7 +10,7 @@ ShellClient::~ShellClient() {} void ShellClient::Initialize(Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) { + const std::string& user_id, uint32_t id) { } bool ShellClient::AcceptConnection(Connection* connection) {
diff --git a/mojo/shell/public/cpp/lib/shell_connection.cc b/mojo/shell/public/cpp/lib/shell_connection.cc index ca7dd1f..c8d206db 100644 --- a/mojo/shell/public/cpp/lib/shell_connection.cc +++ b/mojo/shell/public/cpp/lib/shell_connection.cc
@@ -35,20 +35,20 @@ // ShellConnection, shell::mojom::ShellClient implementation: void ShellConnection::Initialize(shell::mojom::ConnectorPtr connector, - const mojo::String& name, - uint32_t id, - uint32_t user_id) { + const String& name, + const String& user_id, + uint32_t id) { connector_.reset(new ConnectorImpl(std::move(connector))); binding_.set_connection_error_handler( base::Bind(&ShellConnection::OnConnectionError, weak_factory_.GetWeakPtr())); - client_->Initialize(connector_.get(), name, id, user_id); + client_->Initialize(connector_.get(), name, user_id, id); } void ShellConnection::AcceptConnection( const String& requestor_name, + const String& requestor_user_id, uint32_t requestor_id, - uint32_t requestor_user_id, shell::mojom::InterfaceProviderRequest local_interfaces, shell::mojom::InterfaceProviderPtr remote_interfaces, Array<String> allowed_interfaces,
diff --git a/mojo/shell/public/cpp/lib/shell_test.cc b/mojo/shell/public/cpp/lib/shell_test.cc index 929fb745..7f981fe8 100644 --- a/mojo/shell/public/cpp/lib/shell_test.cc +++ b/mojo/shell/public/cpp/lib/shell_test.cc
@@ -15,8 +15,8 @@ ShellTestClient::~ShellTestClient() {} void ShellTestClient::Initialize(Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) { - test_->InitializeCalled(connector, name, id, user_id); + const std::string& user_id, uint32_t id) { + test_->InitializeCalled(connector, name, user_id, id); } ShellTest::ShellTest() {} @@ -34,12 +34,12 @@ void ShellTest::InitializeCalled(Connector* connector, const std::string& name, - uint32_t id, - uint32_t userid) { + const std::string& user_id, + uint32_t id) { connector_ = connector; initialize_name_ = name; initialize_instance_id_ = id; - initialize_userid_ = userid; + initialize_userid_ = user_id; } void ShellTest::SetUp() {
diff --git a/mojo/shell/public/cpp/names.h b/mojo/shell/public/cpp/names.h index 0bad8ac..9815c87 100644 --- a/mojo/shell/public/cpp/names.h +++ b/mojo/shell/public/cpp/names.h
@@ -28,9 +28,9 @@ // Represents a native executable on the host platform, expected to live // alongside the shell executable. Executables launched via this mechanism are // passed a handle to the shell on the command line and are expected to bind -// a ChildController via which they will receive a ShellClientRequest enabling -// further communication with the shell. The path component contains the -// executable name, minus any platform-specific extension. +// a ShellClientFactory via which they will receive a ShellClientRequest +// enabling further communication with the shell. The path component contains +// the executable name, minus any platform-specific extension. // // Other types may be supplied but are not recognized by any of the // NativeRunners, and as such custom loaders must be specified for such names.
diff --git a/mojo/shell/public/cpp/shell_client.h b/mojo/shell/public/cpp/shell_client.h index 36b93874..12c444a 100644 --- a/mojo/shell/public/cpp/shell_client.h +++ b/mojo/shell/public/cpp/shell_client.h
@@ -33,8 +33,8 @@ // Called exactly once before any other method. virtual void Initialize(Connector* connector, const std::string& name, - uint32_t id, - uint32_t user_id = 0); + const std::string& user_id, + uint32_t id); // Called when a connection to this client is brokered by the shell. Override // to expose services to the remote application. Return true if the connection
diff --git a/mojo/shell/public/cpp/shell_connection.h b/mojo/shell/public/cpp/shell_connection.h index 07dc39d..8e2f980 100644 --- a/mojo/shell/public/cpp/shell_connection.h +++ b/mojo/shell/public/cpp/shell_connection.h
@@ -15,7 +15,7 @@ #include "mojo/public/cpp/bindings/callback.h" #include "mojo/public/cpp/system/core.h" #include "mojo/shell/public/cpp/shell_client.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/shell_client.mojom.h" namespace mojo { @@ -59,13 +59,13 @@ private: // shell::mojom::ShellClient: void Initialize(shell::mojom::ConnectorPtr connector, - const mojo::String& name, - uint32_t id, - uint32_t user_id) override; + const String& name, + const String& user_id, + uint32_t id) override; void AcceptConnection( const String& requestor_name, + const String& requestor_user_id, uint32_t requestor_id, - uint32_t requestor_user_id, shell::mojom::InterfaceProviderRequest remote_interfaces, shell::mojom::InterfaceProviderPtr local_interfaces, Array<String> allowed_interfaces,
diff --git a/mojo/shell/public/cpp/shell_test.h b/mojo/shell/public/cpp/shell_test.h index 78a1a25..a839397 100644 --- a/mojo/shell/public/cpp/shell_test.h +++ b/mojo/shell/public/cpp/shell_test.h
@@ -36,8 +36,8 @@ protected: void Initialize(Connector* connector, const std::string& name, - uint32_t id, - uint32_t user_id) override; + const std::string& user_id, + uint32_t id) override; private: ShellTest* test_; @@ -63,8 +63,8 @@ // Instance information received from the Shell during Initialize(). const std::string& test_name() const { return initialize_name_; } + const std::string& test_userid() const { return initialize_userid_; } uint32_t test_instance_id() const { return initialize_instance_id_; } - uint32_t test_userid() const { return initialize_userid_; } // By default, creates a simple ShellClient that captures the metadata sent // via Initialize(). Override to customize, but custom implementations must @@ -75,8 +75,8 @@ // Call to set Initialize() metadata when GetShellClient() is overridden. void InitializeCalled(Connector* connector, const std::string& name, - uint32_t id, - uint32_t userid); + const std::string& userid, + uint32_t id); // testing::Test: void SetUp() override; @@ -96,9 +96,9 @@ Connector* connector_ = nullptr; std::string initialize_name_; + std::string initialize_userid_ = shell::mojom::kInheritUserID; uint32_t initialize_instance_id_ = shell::mojom::Connector::kInvalidApplicationID; - uint32_t initialize_userid_ = shell::mojom::Connector::kUserInherit; DISALLOW_COPY_AND_ASSIGN(ShellTest); };
diff --git a/mojo/shell/public/interfaces/BUILD.gn b/mojo/shell/public/interfaces/BUILD.gn index 39c678e..023141e 100644 --- a/mojo/shell/public/interfaces/BUILD.gn +++ b/mojo/shell/public/interfaces/BUILD.gn
@@ -7,7 +7,7 @@ # GYP version: mojo/mojo_base.gyp:mojo_application_bindings mojom("interfaces") { sources = [ - "application_manager.mojom", + "connector.mojom", "interface_provider.mojom", "shell.mojom", "shell_client.mojom",
diff --git a/mojo/shell/public/interfaces/application_manager.mojom b/mojo/shell/public/interfaces/application_manager.mojom deleted file mode 100644 index 943c767..0000000 --- a/mojo/shell/public/interfaces/application_manager.mojom +++ /dev/null
@@ -1,60 +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. - -module mojo.shell.mojom; - -import "mojo/shell/public/interfaces/shell.mojom"; - -struct InstanceInfo { - uint32 id; - string name; - string qualifier; - uint32 pid; -}; - -// Implemented by a client that wishes to be informed when the list of running -// instances changes. -interface InstanceListener { - // Called once when the listener is added via - // ApplicationManager::AddInstanceListener() to provide the initial list of - // instances that the listener observes changes against. - SetExistingInstances(array<InstanceInfo> instances); - - // Called when the application manager has started tracking an instance. - // This happens when the application manager first handles a request to launch - // the instance, before any process is created for it. - InstanceCreated(InstanceInfo instance); - - // Called when the application manager has stopped tracking an instance. - // (i.e. when it has ended/quit). - InstanceDestroyed(uint32 id); - - // Called when a pid is available for the instance. This could be because a - // process was created by the runner for it, or because an existing content - // handler process was assigned. - InstancePIDAvailable(uint32 id, uint32 pid); -}; - -// Implemented by an object in the application manager associated with a -// specific instance. Tells it the PID for a process launched by the client. -// This interface is only available to callers of ApplicationManager:: -// CreateInstanceForHandle(). -interface PIDReceiver { - SetPID(uint32 pid); -}; - -interface ApplicationManager { - // Instructs the ApplicationManager to create an instance for an existing - // process at the other end of |channel|, and perform applicable - // initialization. This assumes the target process will bind the other end of - // channel to an implementation of ChildController and bind an Application - // request there. - CreateInstanceForHandle(handle channel, - string name, - CapabilityFilter filter, - PIDReceiver& pid_receiver); - - // The listener is removed when the |listener| pipe is closed. - AddInstanceListener(InstanceListener listener); -};
diff --git a/mojo/shell/public/interfaces/connector.mojom b/mojo/shell/public/interfaces/connector.mojom new file mode 100644 index 0000000..94ffa6b2 --- /dev/null +++ b/mojo/shell/public/interfaces/connector.mojom
@@ -0,0 +1,99 @@ +// 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. + +module mojo.shell.mojom; + +import "mojo/shell/public/interfaces/interface_provider.mojom"; + +const string kRootUserID = "505C0EE9-3013-43C0-82B0-A84F50CF8D84"; +const string kInheritUserID = "D26290E4-4485-4EAE-81A2-66D1EEB40A9D"; + +enum ConnectResult { + // The connection was established successfully. + OK, + + // The name or user id supplied was malformed, or the application specified + // by |name| could not be loaded. + INVALID_ARGUMENT, + + // The connection was blocked by policy. Either connections to |name| are + // forbidden from this app by the CapabilityFilter, or the application + // attempted to connect using a user id other than its own, + // kInheritUserID or kRootUserID. + PERMISSION_DENIED +}; + +// Encapsulates establishing connections with other Mojo applications. +interface Connector { + const uint32 kInvalidApplicationID = 0; + + // Requests a connection with another application. The application originating + // the request is referred to as the "source" and the one receiving the + // "target". + // + // The connection is embodied by a pair of message pipes binding the + // InterfaceProvider interface, which allows both the source and target + // applications to export interfaces to one another. The interfaces bound via + // these InterfaceProviders are brokered by the shell according to the + // security policy defined by each application in its manifest . + // + // If the target application is not running, the shell will run it, calling + // its Initialize() method before completing the connection. + // + // Parameters: + // + // name + // A mojo: or exe: name identifying the target application. + // + // user_id + // The user id of the target application instance to connect to. If no such + // instance exists, the shell may start one. This user id will be passed + // to the new instance via Initialize(). Applications must generally pass + // kInheritUserID for this value, and the shell will either connect to an + // existing instance matching the caller's user id, create a new instance + // matching the caller's user id, or connect to an existing instance + // running as kRootUserID. By default, applications do not have the ability + // to pass arbitrary values to this method, and doing so will result in a + // connection error on the remote service provider. An application with + // the ability to launch applications with arbitrary user ids (e.g. a login + // app) may set this value to something meaningful to it. The user id + // string is a valid guid of the form "%08X-%04X-%04X-%04X-%012llX", and + // (aside from the root user whose guid is defined above) intended to be + // not-guessable. + // + // remote_interfaces + // Allows the source application access to interface implementations + // exposed by the target application. The interfaces accessible via this + // InterfaceParameter are filtered by the security policy described by the + // source and target application manifests. + // + // local_interfaces + // Allows the remote application access to interface implementations + // exposed by the source application. The interfaces accessible via this + // InterfaceProvider are filtered by the security policy described by the + // source and target application manifests. + // + // Response parameters: + // + // result + // Indicates the result of the Connect() operation. + // + // user_id + // The user id the shell ran the target application as. Typically a client + // passes kInheritUserID as the user id to Connect() which is resolved by + // the shell into a valid user id returned through this callback. + // + // application_id + // A unique identifier for the instance that was connected to. + // + Connect(string name, + string user_id, + InterfaceProvider&? remote_interfaces, + InterfaceProvider? local_interfaces) => (ConnectResult result, + string user_id, + uint32 application_id); + + // Clones this Connector so it can be passed to another thread. + Clone(Connector& request); +};
diff --git a/mojo/shell/public/interfaces/shell.mojom b/mojo/shell/public/interfaces/shell.mojom index 9702d48b..f20b87ce 100644 --- a/mojo/shell/public/interfaces/shell.mojom +++ b/mojo/shell/public/interfaces/shell.mojom
@@ -1,10 +1,48 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. +// 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. module mojo.shell.mojom; -import "mojo/shell/public/interfaces/interface_provider.mojom"; +import "mojo/shell/public/interfaces/connector.mojom"; +import "mojo/shell/public/interfaces/shell_client_factory.mojom"; + +struct InstanceInfo { + uint32 id; + string name; + string qualifier; + uint32 pid; +}; + +// Implemented by a client that wishes to be informed when the list of running +// instances changes. +interface InstanceListener { + // Called once when the listener is added via Shell::AddInstanceListener() to + // provide the initial list of instances that the listener observes changes + // against. + SetExistingInstances(array<InstanceInfo> instances); + + // Called when the shell has started tracking an instance. This happens when + // the shell first handles a request to launch the instance, before any + // process is created for it. + InstanceCreated(InstanceInfo instance); + + // Called when the shell has stopped tracking an instance. (i.e. when it has + // ended/quit). + InstanceDestroyed(uint32 id); + + // Called when a pid is available for the instance. This could be because a + // process was created by the runner for it, or because an existing content + // handler process was assigned. + InstancePIDAvailable(uint32 id, uint32 pid); +}; + +// Implemented by an object in the shell associated with a specific instance. +// Tells it the PID for a process launched by the client. This interface is only +// available to callers of Shell::CreateInstanceForFactory(). +interface PIDReceiver { + SetPID(uint32 pid); +}; // Specifies a whitelist of applications and services an application can connect // to. Connections to applications not explicitly specified here as a key are @@ -20,72 +58,20 @@ map<string, array<string>> filter; }; -// Encapsulates establishing connections with other Mojo applications. -interface Connector { - const uint32 kInvalidApplicationID = 0; - const uint32 kUserRoot = 0; - const uint32 kUserInherit = 1; +interface Shell { + // Instructs the Shell to create an instance for an existing process at the + // other end of |factory|, and perform applicable initialization. |user_id| is + // the user the instance should be created as. This is typically set to + // Connector::kUserInherit, unless the application has the ability to connect + // as other users. |result| passed in the response indicates (via a MojoResult + // code, see connector.mojom for definitions) the status of the instance + // creation. + CreateInstance(ShellClientFactory factory, + string name, + string user_id, + CapabilityFilter filter, + PIDReceiver& pid_receiver) => (ConnectResult result); - // Requests a connection with another application. The application originating - // the request is referred to as the "source" and the one receiving the - // "target". - // - // The connection is embodied by a pair of message pipes binding the - // InterfaceProvider interface, which allows both the source and target - // applications to export interfaces to one another. The interfaces bound via - // these InterfaceProviders are brokered by the shell according to the - // security policy defined by each application in its manifest . - // - // If the target application is not running, the shell will run it, calling - // its Initialize() method before completing the connection. - // - // Parameters: - // - // name - // A mojo: or exe: name identifying the target application. - // - // user_id - // The user id of the target application instance to connect to. If no such - // instance exists, the shell may start one. This user id will be passed - // to the new instance via Initialize(). Applications must generally set - // this to kUserInherit, and the shell will either connect to an existing - // instance matching the caller's user id, create a new instance matching - // the caller's user id, or connect to an existing instance running as - // kUserRoot. By default, applications do not have the ability to pass - // arbitrary values to this method, and doing so will result in a - // connection error on the remote service provider. An application with - // the ability to launch applications with arbitrary user ids (e.g. a login - // app) may set this value to something meaningful to it. - // - // remote_interfaces - // Allows the source application access to interface implementations - // exposed by the target application. The interfaces accessible via this - // InterfaceParameter are filtered by the security policy described by the - // source and target application manifests. - // - // local_interfaces - // Allows the remote application access to interface implementations - // exposed by the source application. The interfaces accessible via this - // InterfaceProvider are filtered by the security policy described by the - // source and target application manifests. - // - // Response parameters: - // - // application_id - // A unique identifier for the instance that was connected to. - // - // user_id - // The user id the shell ran the target application as. Typically a client - // passes kUserInherit to Connect(), which is an invalid user id, so this - // value in the response is guaranteed to be a valid user id, either the - // id connected to, or kUserRoot if no user-specific instance was located. - // - Connect(string name, - uint32 user_id, - InterfaceProvider&? remote_interfaces, - InterfaceProvider? local_interfaces) => (uint32 application_id, - uint32 user_id); - - // Clones this Connector so it can be passed to another thread. - Clone(Connector& request); + // The listener is removed when the |listener| pipe is closed. + AddInstanceListener(InstanceListener listener); };
diff --git a/mojo/shell/public/interfaces/shell_client.mojom b/mojo/shell/public/interfaces/shell_client.mojom index e8643e6..2af9a1f 100644 --- a/mojo/shell/public/interfaces/shell_client.mojom +++ b/mojo/shell/public/interfaces/shell_client.mojom
@@ -4,8 +4,8 @@ module mojo.shell.mojom; +import "mojo/shell/public/interfaces/connector.mojom"; import "mojo/shell/public/interfaces/interface_provider.mojom"; -import "mojo/shell/public/interfaces/shell.mojom"; // Implemented by something "known to" the Mojo Shell (e.g. an application or // service), for which an instance is tracked. It allows the implementor to @@ -24,16 +24,16 @@ // The resolved name used in the connection request that resulted in this // application being initialized. // - // id - // A unique identifier used by the shell to identify this instance. - // // user_id // Identifies the user this instance is run as in the shell. This may // differ from the user the application that caused this application to be // instantiated is run as. This will always be a valid user id, never // Shell::kUserInherit. // - Initialize(Connector connector, string name, uint32 id, uint32 user_id); + // id + // A unique identifier used by the shell to identify this instance. + // + Initialize(Connector connector, string name, string user_id, uint32 id); // Called when another application attempts to open a connection to this // application. An application implements this method to complete the exchange @@ -55,7 +55,7 @@ // An identifier for the user the source application is run as. This may // differ from the application the target is run as (i.e. the one received // via Initialize() above). This will always be a valid user id, never - // Shell::kUserInherit. + // kInheritUserID. // // local_interfaces // A request for an InterfaceProvider by which the source application may @@ -75,8 +75,8 @@ // The resolved name used to complete this connection. // AcceptConnection(string requestor_name, + string requestor_user_id, uint32 requestor_id, - uint32 requestor_user_id, InterfaceProvider&? local_interfaces, InterfaceProvider? remote_interfaces, array<string> allowed_interfaces,
diff --git a/mojo/shell/runner/child/BUILD.gn b/mojo/shell/runner/child/BUILD.gn index cdc50d9..a534dff8 100644 --- a/mojo/shell/runner/child/BUILD.gn +++ b/mojo/shell/runner/child/BUILD.gn
@@ -21,7 +21,6 @@ ] deps = [ - ":interfaces", "//base", "//mojo/edk/system", "//mojo/message_pump", @@ -31,18 +30,6 @@ ] } -mojom("interfaces") { - sources = [ - "child_controller.mojom", - ] - - deps = [ - "//mojo/shell/public/interfaces", - ] - - import_dirs = [ "//mojo/services" ] -} - source_set("test_native_main") { sources = [ "test_native_main.cc",
diff --git a/mojo/shell/runner/child/child_controller.mojom b/mojo/shell/runner/child/child_controller.mojom deleted file mode 100644 index f71c0d5..0000000 --- a/mojo/shell/runner/child/child_controller.mojom +++ /dev/null
@@ -1,15 +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. - -module mojo.shell.mojom; - -import "mojo/shell/public/interfaces/shell_client.mojom"; - -interface ChildController { - // Starts the app. - StartApp(ShellClient& request) => (int32 result); - - // Exits the child process now (with no cleanup), with the given exit code. - ExitNow(int32 exit_code); -};
diff --git a/mojo/shell/runner/child/runner_connection.cc b/mojo/shell/runner/child/runner_connection.cc index 900ee2c9..fc56f6a 100644 --- a/mojo/shell/runner/child/runner_connection.cc +++ b/mojo/shell/runner/child/runner_connection.cc
@@ -22,7 +22,7 @@ #include "mojo/edk/embedder/scoped_platform_handle.h" #include "mojo/message_pump/message_pump_mojo.h" #include "mojo/public/cpp/bindings/binding.h" -#include "mojo/shell/runner/child/child_controller.mojom.h" +#include "mojo/shell/public/interfaces/shell_client_factory.mojom.h" #include "mojo/shell/runner/common/switches.h" namespace mojo { @@ -33,11 +33,15 @@ // and runs a closure provided by that thread. class Blocker { public: + // Unblocks a Blocker. Safe to copy around to any thread, but must only be + // used from a single thread. class Unblocker { public: explicit Unblocker(Blocker* blocker = nullptr) : blocker_(blocker) {} ~Unblocker() {} + bool IsBlocking() const { return blocker_ != nullptr; } + void Unblock(base::Closure run_after) { DCHECK(blocker_); DCHECK(blocker_->run_after_.is_null()); @@ -128,13 +132,10 @@ DISALLOW_COPY_AND_ASSIGN(RunnerConnectionImpl); }; -class ChildControllerImpl : public mojom::ChildController { +class ChildControllerImpl : public mojom::ShellClientFactory { public: ~ChildControllerImpl() override { DCHECK(thread_checker_.CalledOnValidThread()); - - // TODO(vtl): Pass in the result from |MainMain()|. - on_app_complete_.Run(MOJO_RESULT_UNIMPLEMENTED); } // To be executed on the controller thread. Creates the |ChildController|, @@ -165,32 +166,16 @@ // A connection error means the connection to the shell is lost. This is not // recoverable. DLOG(ERROR) << "Connection error to the shell."; - if (exit_on_error_) { + if (exit_on_error_) _exit(1); - } else if (on_app_complete_.is_null()) { - // If we failed before we could even get a ShellClient request from the - // shell, signal failure to the RunnerConnection, as it's still blocking - // on a response. - unblocker_.Unblock( - base::Bind(&ChildControllerImpl::ReturnApplicationRequestOnMainThread, - callback_, nullptr)); - } + else + UnblockConnection(nullptr); } - // |mojom::ChildController| methods: - void StartApp(InterfaceRequest<mojom::ShellClient> request, - const StartAppCallback& on_app_complete) override { - DCHECK(thread_checker_.CalledOnValidThread()); - - on_app_complete_ = on_app_complete; - unblocker_.Unblock( - base::Bind(&ChildControllerImpl::ReturnApplicationRequestOnMainThread, - callback_, base::Passed(&request))); - } - - void ExitNow(int32_t exit_code) override { - DVLOG(2) << "ChildControllerImpl::ExitNow(" << exit_code << ")"; - _exit(exit_code); + // |mojom::ShellClientFactory| methods: + void CreateShellClient(mojom::ShellClientRequest request, + const String& name) override { + UnblockConnection(std::move(request)); } private: @@ -210,13 +195,21 @@ callback.Run(std::move(request)); } + void UnblockConnection(mojom::ShellClientRequest request) { + DCHECK(thread_checker_.CalledOnValidThread()); + if (unblocker_.IsBlocking()) { + unblocker_.Unblock( + base::Bind(&ChildControllerImpl::ReturnApplicationRequestOnMainThread, + callback_, base::Passed(&request))); + } + } + base::ThreadChecker thread_checker_; RunnerConnectionImpl* const connection_; GotApplicationRequestCallback callback_; Blocker::Unblocker unblocker_; - StartAppCallback on_app_complete_; - Binding<ChildController> binding_; + Binding<mojom::ShellClientFactory> binding_; bool exit_on_error_;
diff --git a/mojo/shell/runner/host/BUILD.gn b/mojo/shell/runner/host/BUILD.gn index 7ca4037..59f2cc7d 100644 --- a/mojo/shell/runner/host/BUILD.gn +++ b/mojo/shell/runner/host/BUILD.gn
@@ -48,8 +48,8 @@ "//mojo/message_pump", "//mojo/platform_handle:platform_handle_impl", "//mojo/shell", + "//mojo/shell/public/interfaces", "//mojo/shell/runner:init", - "//mojo/shell/runner/child:interfaces", "//mojo/shell/runner/common", ] } @@ -76,8 +76,8 @@ "//mojo/message_pump", "//mojo/platform_handle:platform_handle_impl", "//mojo/shell", + "//mojo/shell/public/interfaces", "//mojo/shell/runner:init", - "//mojo/shell/runner/child:interfaces", "//mojo/shell/runner/common", ]
diff --git a/mojo/shell/runner/host/child_process.cc b/mojo/shell/runner/host/child_process.cc index 5111064..51915d7 100644 --- a/mojo/shell/runner/host/child_process.cc +++ b/mojo/shell/runner/host/child_process.cc
@@ -33,7 +33,6 @@ #include "mojo/message_pump/message_pump_mojo.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/core.h" -#include "mojo/shell/runner/child/child_controller.mojom.h" #include "mojo/shell/runner/common/switches.h" #include "mojo/shell/runner/host/child_process_base.h" #include "mojo/shell/runner/host/native_application_support.h"
diff --git a/mojo/shell/runner/host/child_process_base.cc b/mojo/shell/runner/host/child_process_base.cc index a1c3f1e..d4d6870 100644 --- a/mojo/shell/runner/host/child_process_base.cc +++ b/mojo/shell/runner/host/child_process_base.cc
@@ -32,7 +32,7 @@ #include "mojo/message_pump/message_pump_mojo.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/system/core.h" -#include "mojo/shell/runner/child/child_controller.mojom.h" +#include "mojo/shell/public/interfaces/shell_client_factory.mojom.h" #include "mojo/shell/runner/common/switches.h" #include "mojo/shell/runner/init.h" @@ -176,13 +176,10 @@ // ChildControllerImpl ------------------------------------------------------ -class ChildControllerImpl : public mojom::ChildController { +class ChildControllerImpl : public mojom::ShellClientFactory { public: ~ChildControllerImpl() override { DCHECK(thread_checker_.CalledOnValidThread()); - - // TODO(vtl): Pass in the result from |MainMain()|. - on_app_complete_.Run(MOJO_RESULT_UNIMPLEMENTED); } // To be executed on the controller thread. Creates the |ChildController|, @@ -216,20 +213,13 @@ _exit(1); } - // |ChildController| methods: - void StartApp(InterfaceRequest<mojom::ShellClient> request, - const StartAppCallback& on_app_complete) override { + // |mojom::ShellClientFactory| methods: + void CreateShellClient(mojom::ShellClientRequest request, + const String& name) override { DCHECK(thread_checker_.CalledOnValidThread()); - - on_app_complete_ = on_app_complete; unblocker_.Unblock(base::Bind(run_callback_, base::Passed(&request))); } - void ExitNow(int32_t exit_code) override { - DVLOG(2) << "ChildControllerImpl::ExitNow(" << exit_code << ")"; - _exit(exit_code); - } - private: ChildControllerImpl(AppContext* app_context, const RunCallback& run_callback, @@ -239,9 +229,8 @@ base::ThreadChecker thread_checker_; RunCallback run_callback_; Blocker::Unblocker unblocker_; - StartAppCallback on_app_complete_; - Binding<ChildController> binding_; + Binding<mojom::ShellClientFactory> binding_; DISALLOW_COPY_AND_ASSIGN(ChildControllerImpl); };
diff --git a/mojo/shell/runner/host/child_process_host.cc b/mojo/shell/runner/host/child_process_host.cc index 1fae5d7..60a9947 100644 --- a/mojo/shell/runner/host/child_process_host.cc +++ b/mojo/shell/runner/host/child_process_host.cc
@@ -49,32 +49,25 @@ weak_factory_(this) { node_channel_.reset(new edk::PlatformChannelPair); primordial_pipe_token_ = edk::GenerateRandomToken(); - controller_.Bind( - InterfacePtrInfo<mojom::ChildController>( - edk::CreateParentMessagePipe(primordial_pipe_token_), 0u)); -} - -ChildProcessHost::ChildProcessHost(ScopedHandle channel) - : external_process_(true), - launch_process_runner_(nullptr), - delegate_(nullptr), - start_sandboxed_(false), - start_child_process_event_(false, false), - weak_factory_(this) { - CHECK(channel.is_valid()); - ScopedMessagePipeHandle handle(MessagePipeHandle(channel.release().value())); - controller_.Bind( - InterfacePtrInfo<mojom::ChildController>(std::move(handle), 0u)); + factory_.Bind(InterfacePtrInfo<mojom::ShellClientFactory>( + edk::CreateParentMessagePipe(primordial_pipe_token_), 0u)); } ChildProcessHost::~ChildProcessHost() { if (!app_path_.empty()) - CHECK(!controller_) << "Destroying ChildProcessHost before calling Join"; + CHECK(!factory_) << "Destroying ChildProcessHost before calling Join"; } -void ChildProcessHost::Start(const ProcessReadyCallback& callback) { - DCHECK(!external_process_); +void ChildProcessHost::Start(mojom::ShellClientRequest request, + const String& name, + const ProcessReadyCallback& callback, + const base::Closure& quit_closure) { DCHECK(!child_process_.IsValid()); + // Request is invalid in child_process_host_unittest. + if (request.is_pending()) { + factory_->CreateShellClient(std::move(request), name); + factory_.set_connection_error_handler(quit_closure); + } launch_process_runner_->PostTaskAndReply( FROM_HERE, base::Bind(&ChildProcessHost::DoLaunch, base::Unretained(this)), @@ -82,11 +75,11 @@ weak_factory_.GetWeakPtr(), callback)); } -int ChildProcessHost::Join() { - if (controller_ && !external_process_) +void ChildProcessHost::Join() { + if (factory_) start_child_process_event_.Wait(); - controller_ = mojom::ChildControllerPtr(); + factory_.reset(); // This host may be hosting a child process whose lifetime is controlled // elsewhere. In this case we have no known process handle to wait on. @@ -96,42 +89,19 @@ << "Failed to wait for child process"; child_process_.Close(); - return rv; } - - return 0; -} - -void ChildProcessHost::StartApp( - InterfaceRequest<mojom::ShellClient> request, - const mojom::ChildController::StartAppCallback& on_app_complete) { - DCHECK(controller_); - on_app_complete_ = on_app_complete; - controller_->StartApp( - std::move(request), - base::Bind(&ChildProcessHost::AppCompleted, weak_factory_.GetWeakPtr())); -} - -void ChildProcessHost::ExitNow(int32_t exit_code) { - DCHECK(controller_); - - controller_->ExitNow(exit_code); } void ChildProcessHost::DidStart(const ProcessReadyCallback& callback) { - DVLOG(2) << "ChildProcessHost::DidStart()"; - if (child_process_.IsValid()) { callback.Run(child_process_.Pid()); } else { LOG(ERROR) << "Failed to start child process"; - AppCompleted(MOJO_RESULT_UNKNOWN); + factory_.reset(); } } void ChildProcessHost::DoLaunch() { - DCHECK(!external_process_); - const base::CommandLine* parent_command_line = base::CommandLine::ForCurrentProcess(); base::FilePath target_path = parent_command_line->GetProgram(); @@ -229,13 +199,5 @@ start_child_process_event_.Signal(); } -void ChildProcessHost::AppCompleted(int32_t result) { - if (!on_app_complete_.is_null()) { - auto on_app_complete = on_app_complete_; - on_app_complete_.reset(); - on_app_complete.Run(result); - } -} - } // namespace shell } // namespace mojo
diff --git a/mojo/shell/runner/host/child_process_host.h b/mojo/shell/runner/host/child_process_host.h index 4f3082b..25b59dc3 100644 --- a/mojo/shell/runner/host/child_process_host.h +++ b/mojo/shell/runner/host/child_process_host.h
@@ -20,7 +20,7 @@ #include "mojo/edk/embedder/platform_channel_pair.h" #include "mojo/public/cpp/system/message_pipe.h" #include "mojo/shell/identity.h" -#include "mojo/shell/runner/child/child_controller.mojom.h" +#include "mojo/shell/public/interfaces/shell_client_factory.mojom.h" #include "mojo/shell/runner/host/child_process_host.h" namespace base { @@ -55,23 +55,17 @@ bool start_sandboxed, const Identity& target, const base::FilePath& app_path); - // Allows a ChildProcessHost to be instantiated for an existing channel - // created by someone else (e.g. an app that launched its own process). - explicit ChildProcessHost(ScopedHandle channel); virtual ~ChildProcessHost(); // |Start()|s the child process; calls |DidStart()| (on the thread on which // |Start()| was called) when the child has been started (or failed to start). - void Start(const ProcessReadyCallback& callback); + void Start(mojom::ShellClientRequest request, + const String& name, + const ProcessReadyCallback& callback, + const base::Closure& quit_closure); - // Waits for the child process to terminate, and returns its exit code. - int Join(); - - // See |mojom::ChildController|: - void StartApp( - InterfaceRequest<mojom::ShellClient> request, - const mojom::ChildController::StartAppCallback& on_app_complete); - void ExitNow(int32_t exit_code); + // Waits for the child process to terminate. + void Join(); protected: void DidStart(const ProcessReadyCallback& callback); @@ -79,22 +73,15 @@ private: void DoLaunch(); - void AppCompleted(int32_t result); - - // If |true|, the hosted process is neither launched nor owned by this - // ChildProcessHost. - bool external_process_ = false; - scoped_refptr<base::TaskRunner> launch_process_runner_; - NativeRunnerDelegate* delegate_; - bool start_sandboxed_; + NativeRunnerDelegate* delegate_ = nullptr; + bool start_sandboxed_ = false; Identity target_; const base::FilePath app_path_; base::Process child_process_; - // Used for the ChildController binding. + // Used for the ShellClientFactory binding. edk::PlatformChannelPair platform_channel_pair_; - mojom::ChildControllerPtr controller_; - mojom::ChildController::StartAppCallback on_app_complete_; + mojom::ShellClientFactoryPtr factory_; edk::HandlePassingInformation handle_passing_info_; // Used to back the NodeChannel between the parent and child node.
diff --git a/mojo/shell/runner/host/child_process_host_unittest.cc b/mojo/shell/runner/host/child_process_host_unittest.cc index e14d2ac2..2f57bf60 100644 --- a/mojo/shell/runner/host/child_process_host_unittest.cc +++ b/mojo/shell/runner/host/child_process_host_unittest.cc
@@ -96,13 +96,12 @@ Identity(), base::FilePath()); base::RunLoop run_loop; child_process_host.Start( - base::Bind(&ProcessReadyCallbackAdapater, run_loop.QuitClosure())); + mojom::ShellClientRequest(), String(), + base::Bind(&ProcessReadyCallbackAdapater, run_loop.QuitClosure()), + base::Bind(&base::DoNothing)); run_loop.Run(); - child_process_host.ExitNow(123); - int exit_code = child_process_host.Join(); - VLOG(2) << "Joined child: exit_code = " << exit_code; - EXPECT_EQ(123, exit_code); + child_process_host.Join(); blocking_pool->Shutdown(); edk::ShutdownIPCSupport(); EXPECT_EQ(1u, native_runner_delegate.get_and_clear_adjust_count());
diff --git a/mojo/shell/runner/host/in_process_native_runner.cc b/mojo/shell/runner/host/in_process_native_runner.cc index 9cd89db..c006a79 100644 --- a/mojo/shell/runner/host/in_process_native_runner.cc +++ b/mojo/shell/runner/host/in_process_native_runner.cc
@@ -37,7 +37,7 @@ const base::FilePath& app_path, const Identity& target, bool start_sandboxed, - InterfaceRequest<mojom::ShellClient> request, + mojom::ShellClientRequest request, const base::Callback<void(base::ProcessId)>& pid_available_callback, const base::Closure& app_completed_callback) { app_path_ = app_path; @@ -60,12 +60,6 @@ pid_available_callback.Run(base::kNullProcessId); } -void InProcessNativeRunner::InitHost( - ScopedHandle channel, - InterfaceRequest<mojom::ShellClient> request) { - NOTREACHED(); // Can't host another process in this runner. -} - void InProcessNativeRunner::Run() { DVLOG(2) << "Loading/running Mojo app in process from library: " << app_path_.value()
diff --git a/mojo/shell/runner/host/in_process_native_runner.h b/mojo/shell/runner/host/in_process_native_runner.h index 8e62172..9f633964 100644 --- a/mojo/shell/runner/host/in_process_native_runner.h +++ b/mojo/shell/runner/host/in_process_native_runner.h
@@ -37,9 +37,6 @@ InterfaceRequest<mojom::ShellClient> request, const base::Callback<void(base::ProcessId)>& pid_available_callback, const base::Closure& app_completed_callback) override; - void InitHost( - ScopedHandle channel, - InterfaceRequest<mojom::ShellClient> request) override; private: // |base::DelegateSimpleThread::Delegate| method:
diff --git a/mojo/shell/runner/host/out_of_process_native_runner.cc b/mojo/shell/runner/host/out_of_process_native_runner.cc index cb3da62..619bb1d 100644 --- a/mojo/shell/runner/host/out_of_process_native_runner.cc +++ b/mojo/shell/runner/host/out_of_process_native_runner.cc
@@ -33,7 +33,7 @@ const base::FilePath& app_path, const Identity& target, bool start_sandboxed, - InterfaceRequest<mojom::ShellClient> request, + mojom::ShellClientRequest request, const base::Callback<void(base::ProcessId)>& pid_available_callback, const base::Closure& app_completed_callback) { app_path_ = app_path; @@ -43,24 +43,13 @@ child_process_host_.reset(new ChildProcessHost( launch_process_runner_, delegate_, start_sandboxed, target, app_path)); - child_process_host_->Start(base::Bind( - &OutOfProcessNativeRunner::OnProcessLaunched, base::Unretained(this), - base::Passed(&request), pid_available_callback)); + child_process_host_->Start(std::move(request), target.name(), + pid_available_callback, + base::Bind(&OutOfProcessNativeRunner::AppCompleted, + base::Unretained(this))); } -void OutOfProcessNativeRunner::InitHost( - ScopedHandle channel, - InterfaceRequest<mojom::ShellClient> request) { - child_process_host_.reset(new ChildProcessHost(std::move(channel))); - child_process_host_->StartApp( - std::move(request), - base::Bind(&OutOfProcessNativeRunner::AppCompleted, - base::Unretained(this))); -} - -void OutOfProcessNativeRunner::AppCompleted(int32_t result) { - DVLOG(2) << "OutOfProcessNativeRunner::AppCompleted(" << result << ")"; - +void OutOfProcessNativeRunner::AppCompleted() { if (child_process_host_) child_process_host_->Join(); child_process_host_.reset(); @@ -71,18 +60,6 @@ app_completed_callback.Run(); } -void OutOfProcessNativeRunner::OnProcessLaunched( - InterfaceRequest<mojom::ShellClient> request, - const base::Callback<void(base::ProcessId)>& pid_available_callback, - base::ProcessId pid) { - DCHECK(child_process_host_); - child_process_host_->StartApp( - std::move(request), - base::Bind(&OutOfProcessNativeRunner::AppCompleted, - base::Unretained(this))); - pid_available_callback.Run(pid); -} - OutOfProcessNativeRunnerFactory::OutOfProcessNativeRunnerFactory( base::TaskRunner* launch_process_runner, NativeRunnerDelegate* delegate)
diff --git a/mojo/shell/runner/host/out_of_process_native_runner.h b/mojo/shell/runner/host/out_of_process_native_runner.h index 6b63c8ad..d56fd6c5 100644 --- a/mojo/shell/runner/host/out_of_process_native_runner.h +++ b/mojo/shell/runner/host/out_of_process_native_runner.h
@@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "mojo/shell/native_runner.h" +#include "mojo/shell/public/interfaces/shell_client_factory.mojom.h" namespace base { class TaskRunner; @@ -36,22 +37,12 @@ const base::FilePath& app_path, const Identity& identity, bool start_sandboxed, - InterfaceRequest<mojom::ShellClient> request, + mojom::ShellClientRequest request, const base::Callback<void(base::ProcessId)>& pid_available_callback, const base::Closure& app_completed_callback) override; - void InitHost( - ScopedHandle channel, - InterfaceRequest<mojom::ShellClient> request) override; private: - // |ChildController::StartApp()| callback: - void AppCompleted(int32_t result); - - // Callback run when the child process has launched. - void OnProcessLaunched( - InterfaceRequest<mojom::ShellClient> request, - const base::Callback<void(base::ProcessId)>& pid_available_callback, - base::ProcessId pid); + void AppCompleted(); base::TaskRunner* const launch_process_runner_; NativeRunnerDelegate* delegate_;
diff --git a/mojo/shell/application_manager.cc b/mojo/shell/shell.cc similarity index 64% rename from mojo/shell/application_manager.cc rename to mojo/shell/shell.cc index 3fc9959..c6e0a43 100644 --- a/mojo/shell/application_manager.cc +++ b/mojo/shell/shell.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 "mojo/shell/application_manager.h" +#include "mojo/shell/shell.h" #include <stdint.h> @@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/guid.h" #include "base/logging.h" #include "base/macros.h" #include "base/process/process.h" @@ -25,7 +26,7 @@ #include "mojo/shell/public/cpp/connect.h" #include "mojo/shell/public/cpp/names.h" #include "mojo/shell/public/cpp/shell_connection.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/shell.mojom.h" #include "mojo/shell/public/interfaces/shell_client.mojom.h" #include "mojo/util/filename_util.h" @@ -43,14 +44,17 @@ } // Encapsulates a connection to an instance of an application, tracked by the -// shell's ApplicationManager. -class ApplicationManager::Instance : public mojom::Connector, - public mojom::PIDReceiver { +// shell's Shell. +class Shell::Instance : public mojom::Connector, + public mojom::PIDReceiver, + public ShellClient, + public InterfaceFactory<mojom::Shell>, + public mojom::Shell { public: Instance(mojom::ShellClientPtr shell_client, - ApplicationManager* manager, + mojo::shell::Shell* shell, const Identity& identity) - : manager_(manager), + : shell_(shell), id_(GenerateUniqueID()), identity_(identity), allow_any_application_(identity.filter().size() == 1 && @@ -59,7 +63,7 @@ pid_receiver_binding_(this), weak_factory_(this) { if (identity_.name() == "mojo:shell" || - manager_->GetLoaderForName(identity_.name())) { + shell_->GetLoaderForName(identity_.name())) { pid_ = base::Process::Current().Pid(); } DCHECK_NE(kInvalidApplicationID, id_); @@ -67,25 +71,26 @@ ~Instance() override {} - void Initialize() { + void InitializeClient() { shell_client_->Initialize(connectors_.CreateInterfacePtrAndBind(this), - identity_.name(), id_, identity_.user_id()); + identity_.name(), identity_.user_id(), id_); connectors_.set_connection_error_handler( - base::Bind(&ApplicationManager::OnInstanceError, - base::Unretained(manager_), base::Unretained(this))); + base::Bind(&mojo::shell::Shell::OnInstanceError, + base::Unretained(shell_), base::Unretained(this))); } void ConnectToClient(scoped_ptr<ConnectParams> params) { - params->connect_callback().Run(id_, identity_.user_id()); + params->connect_callback().Run(mojom::ConnectResult::OK, + identity_.user_id(), id_); AllowedInterfaces interfaces; interfaces.insert("*"); if (!params->source().is_null()) interfaces = GetAllowedInterfaces(params->source().filter(), identity_); - Instance* source = manager_->GetExistingInstance(params->source()); + Instance* source = shell_->GetExistingInstance(params->source()); uint32_t source_id = source ? source->id() : kInvalidApplicationID; shell_client_->AcceptConnection( - params->source().name(), source_id, params->source().user_id(), + params->source().name(), params->source().user_id(), source_id, params->TakeRemoteInterfaces(), params->TakeLocalInterfaces(), Array<String>::From(interfaces), params->target().name()); } @@ -100,24 +105,12 @@ runner_->Start(path, identity_, start_sandboxed, std::move(request), base::Bind(&Instance::PIDAvailable, weak_factory_.GetWeakPtr()), - base::Bind(&ApplicationManager::CleanupRunner, - manager_->weak_ptr_factory_.GetWeakPtr(), + base::Bind(&mojo::shell::Shell::CleanupRunner, + shell_->weak_ptr_factory_.GetWeakPtr(), runner_)); return runner; } - scoped_ptr<NativeRunner> StartWithChannel( - ScopedHandle channel, - mojom::ShellClientRequest request, - mojom::PIDReceiverRequest pid_receiver_request, - NativeRunnerFactory* factory) { - pid_receiver_binding_.Bind(std::move(pid_receiver_request)); - scoped_ptr<NativeRunner> runner = factory->Create(base::FilePath()); - runner_ = runner.get(); - runner_->InitHost(std::move(channel), std::move(request)); - return runner; - } - mojom::InstanceInfoPtr CreateInstanceInfo() const { mojom::InstanceInfoPtr info(mojom::InstanceInfo::New()); info->id = id_; @@ -130,18 +123,33 @@ const Identity& identity() const { return identity_; } uint32_t id() const { return id_; } + // ShellClient: + bool AcceptConnection(Connection* connection) override { + connection->AddInterface<mojom::Shell>(this); + return true; + } + private: - // Connector implementation: + // mojom::Connector implementation: void Connect(const String& app_name, - uint32_t user_id, + const String& user_id, shell::mojom::InterfaceProviderRequest remote_interfaces, shell::mojom::InterfaceProviderPtr local_interfaces, const ConnectCallback& callback) override { if (!IsValidName(app_name)) { LOG(ERROR) << "Error: invalid Name: " << app_name; - callback.Run(kInvalidApplicationID, kUserInherit); + callback.Run(mojom::ConnectResult::INVALID_ARGUMENT, + mojom::kInheritUserID, kInvalidApplicationID); return; } + if (!base::IsValidGUID(user_id)) { + LOG(ERROR) << "Error: invalid user_id: " << user_id; + callback.Run(mojom::ConnectResult::INVALID_ARGUMENT, + mojom::kInheritUserID, kInvalidApplicationID); + return; + } + // TODO(beng): perform checking on policy of whether this instance is + // allowed to pass different user_ids. if (allow_any_application_ || identity_.filter().find(app_name) != identity_.filter().end()) { scoped_ptr<ConnectParams> params(new ConnectParams); @@ -150,23 +158,63 @@ params->set_remote_interfaces(std::move(remote_interfaces)); params->set_local_interfaces(std::move(local_interfaces)); params->set_connect_callback(callback); - manager_->Connect(std::move(params)); - } - else { + shell_->Connect(std::move(params)); + } else { LOG(WARNING) << "CapabilityFilter prevented connection from: " << identity_.name() << " to: " << app_name; - callback.Run(kInvalidApplicationID, kUserInherit); + callback.Run(mojom::ConnectResult::PERMISSION_DENIED, + mojom::kInheritUserID, kInvalidApplicationID); } } void Clone(mojom::ConnectorRequest request) override { connectors_.AddBinding(this, std::move(request)); } - // PIDReceiver implementation: + // mojom::PIDReceiver: void SetPID(uint32_t pid) override { PIDAvailable(pid); } + // InterfaceFactory<mojom::Shell>: + void Create(Connection* connection, + mojom::ShellRequest request) override { + shell_bindings_.AddBinding(this, std::move(request)); + } + + // mojom::Shell implementation: + void CreateInstance(mojom::ShellClientFactoryPtr factory, + const String& name, + const String& user_id, + mojom::CapabilityFilterPtr filter, + mojom::PIDReceiverRequest pid_receiver, + const CreateInstanceCallback& callback) override { + if (!base::IsValidGUID(user_id)) + callback.Run(mojom::ConnectResult::INVALID_ARGUMENT); + // TODO(beng): perform checking on policy of whether this instance is + // allowed to pass different user_ids. + std::string user_id_string = user_id; + if (user_id_string == mojom::kInheritUserID) + user_id_string = identity_.user_id(); + + // We don't call ConnectToClient() here since the instance was created + // manually by other code, not in response to a Connect() request. The newly + // created instance is identified by |name| and may be subsequently reached + // by client code using this identity. + Identity target_id(name, std::string(), user_id_string); + target_id.set_filter(filter->filter.To<CapabilityFilter>()); + mojom::ShellClientRequest request; + Instance* instance = shell_->CreateInstance(target_id, &request); + instance->pid_receiver_binding_.Bind(std::move(pid_receiver)); + instance->factory_ = std::move(factory); + instance->factory_->CreateShellClient(std::move(request), name); + callback.Run(mojom::ConnectResult::OK); + } + void AddInstanceListener(mojom::InstanceListenerPtr listener) override { + // TODO(beng): this should only track the instances matching this user, and + // root. + shell_->AddInstanceListener(std::move(listener)); + } + uint32_t GenerateUniqueID() const { static uint32_t id = kInvalidApplicationID; ++id; @@ -176,10 +224,10 @@ void PIDAvailable(base::ProcessId pid) { pid_ = pid; - manager_->NotifyPIDAvailable(id_, pid_); + shell_->NotifyPIDAvailable(id_, pid_); } - ApplicationManager* const manager_; + mojo::shell::Shell* const shell_; // An id that identifies this instance. Distinct from pid, as a single process // may vend multiple application instances, and this object may exist before a // process is launched. @@ -189,6 +237,8 @@ mojom::ShellClientPtr shell_client_; Binding<mojom::PIDReceiver> pid_receiver_binding_; BindingSet<mojom::Connector> connectors_; + BindingSet<mojom::Shell> shell_bindings_; + mojom::ShellClientFactoryPtr factory_; NativeRunner* runner_ = nullptr; base::ProcessId pid_ = base::kNullProcessId; base::WeakPtrFactory<Instance> weak_factory_; @@ -197,26 +247,20 @@ }; // static -ApplicationManager::TestAPI::TestAPI(ApplicationManager* manager) - : manager_(manager) { -} +Shell::TestAPI::TestAPI(Shell* shell) : shell_(shell) {} +Shell::TestAPI::~TestAPI() {} -ApplicationManager::TestAPI::~TestAPI() { -} - -bool ApplicationManager::TestAPI::HasRunningInstanceForName( - const std::string& name) const { - return manager_->identity_to_instance_.find(Identity(name)) != - manager_->identity_to_instance_.end(); +bool Shell::TestAPI::HasRunningInstanceForName(const std::string& name) const { + return shell_->identity_to_instance_.find(Identity(name)) != + shell_->identity_to_instance_.end(); } //////////////////////////////////////////////////////////////////////////////// -// ApplicationManager, public: +// Shell, public: -ApplicationManager::ApplicationManager( - scoped_ptr<NativeRunnerFactory> native_runner_factory, - base::TaskRunner* file_task_runner, - scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog) +Shell::Shell(scoped_ptr<NativeRunnerFactory> native_runner_factory, + base::TaskRunner* file_task_runner, + scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog) : file_task_runner_(file_task_runner), native_runner_factory_(std::move(native_runner_factory)), weak_ptr_factory_(this) { @@ -227,30 +271,30 @@ InitPackageManager(std::move(app_catalog)); } -ApplicationManager::~ApplicationManager() { +Shell::~Shell() { TerminateShellConnections(); STLDeleteValues(&name_to_loader_); for (auto& runner : native_runners_) runner.reset(); } -void ApplicationManager::SetInstanceQuitCallback( +void Shell::SetInstanceQuitCallback( base::Callback<void(const Identity&)> callback) { instance_quit_callback_ = callback; } -void ApplicationManager::Connect(scoped_ptr<ConnectParams> params) { - TRACE_EVENT_INSTANT1("mojo_shell", "ApplicationManager::Connect", +void Shell::Connect(scoped_ptr<ConnectParams> params) { + TRACE_EVENT_INSTANT1("mojo_shell", "Shell::Connect", TRACE_EVENT_SCOPE_THREAD, "original_name", params->target().name()); DCHECK(IsValidName(params->target().name())); - if (params->target().user_id() == mojom::Connector::kUserInherit) { + if (params->target().user_id() == mojom::kInheritUserID) { Instance* source = GetExistingInstance(params->source()); Identity target = params->target(); // TODO(beng): we should CHECK source. target.set_user_id(source ? source->identity().user_id() - : mojom::Connector::kUserRoot); + : mojom::kRootUserID); params->set_target(target); } @@ -261,16 +305,15 @@ std::string name = params->target().name(); shell_resolver_->ResolveMojoName( name, - base::Bind(&ApplicationManager::OnGotResolvedName, + base::Bind(&Shell::OnGotResolvedName, weak_ptr_factory_.GetWeakPtr(), base::Passed(¶ms))); } -mojom::ShellClientRequest ApplicationManager::InitInstanceForEmbedder( +mojom::ShellClientRequest Shell::InitInstanceForEmbedder( const std::string& name) { DCHECK(!embedder_instance_); - mojo::shell::Identity target(name, std::string(), - mojom::Connector::kUserRoot); + mojo::shell::Identity target(name, std::string(), mojom::kRootUserID); target.set_filter(GetPermissiveCapabilityFilter()); DCHECK(!GetExistingInstance(target)); @@ -281,8 +324,8 @@ return request; } -void ApplicationManager::SetLoaderForName(scoped_ptr<Loader> loader, - const std::string& name) { +void Shell::SetLoaderForName(scoped_ptr<Loader> loader, + const std::string& name) { NameToLoaderMap::iterator it = name_to_loader_.find(name); if (it != name_to_loader_.end()) delete it->second; @@ -290,59 +333,30 @@ } //////////////////////////////////////////////////////////////////////////////// -// ApplicationManager, ShellClient implementation: +// Shell, ShellClient implementation: -bool ApplicationManager::AcceptConnection(Connection* connection) { - connection->AddInterface<mojom::ApplicationManager>(this); - return true; +bool Shell::AcceptConnection(Connection* connection) { + // The only interface we expose is mojom::Shell, and access to this interface + // is brokered by a policy specific to each caller, managed by the caller's + // instance. Here we look to see who's calling, and forward to the caller's + // instance to continue. + uint32_t caller_instance_id = mojom::Connector::kInvalidApplicationID; + CHECK(connection->GetRemoteApplicationID(&caller_instance_id)); + Instance* instance = nullptr; + for (const auto& entry : identity_to_instance_) { + if (entry.second->id() == caller_instance_id) { + instance = entry.second; + break; + } + } + DCHECK(instance); + return instance->AcceptConnection(connection); } //////////////////////////////////////////////////////////////////////////////// -// ApplicationManager, InterfaceFactory<mojom::ApplicationManager> -// implementation: +// Shell, private: -void ApplicationManager::Create(Connection* connection, - mojom::ApplicationManagerRequest request) { - bindings_.AddBinding(this, std::move(request)); -} - -//////////////////////////////////////////////////////////////////////////////// -// ApplicationManager, mojom::ApplicationManager implemetation: - -void ApplicationManager::CreateInstanceForHandle( - ScopedHandle channel, - const String& name, - mojom::CapabilityFilterPtr filter, - mojom::PIDReceiverRequest pid_receiver) { - // We don't call ConnectToClient() here since the instance was created - // manually by other code, not in response to a Connect() request. The newly - // created instance is identified by |name| and may be subsequently reached by - // client code using this identity. - // TODO(beng): obtain userid from the inbound connection. - Identity target_id(name, std::string(), mojom::Connector::kUserInherit); - target_id.set_filter(filter->filter.To<CapabilityFilter>()); - mojom::ShellClientRequest request; - Instance* instance = CreateInstance(target_id, &request); - native_runners_.push_back( - instance->StartWithChannel(std::move(channel), std::move(request), - std::move(pid_receiver), - native_runner_factory_.get())); -} - -void ApplicationManager::AddInstanceListener( - mojom::InstanceListenerPtr listener) { - Array<mojom::InstanceInfoPtr> instances; - for (auto& instance : identity_to_instance_) - instances.push_back(instance.second->CreateInstanceInfo()); - listener->SetExistingInstances(std::move(instances)); - - instance_listeners_.AddInterfacePtr(std::move(listener)); -} - -//////////////////////////////////////////////////////////////////////////////// -// ApplicationManager, private: - -void ApplicationManager::InitPackageManager( +void Shell::InitPackageManager( scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog) { scoped_ptr<Loader> loader( new package_manager::Loader(file_task_runner_, std::move(app_catalog))); @@ -364,11 +378,11 @@ } } -void ApplicationManager::TerminateShellConnections() { +void Shell::TerminateShellConnections() { STLDeleteValues(&identity_to_instance_); } -void ApplicationManager::OnInstanceError(Instance* instance) { +void Shell::OnInstanceError(Instance* instance) { const Identity identity = instance->identity(); // Remove the shell. auto it = identity_to_instance_.find(identity); @@ -383,24 +397,22 @@ instance_quit_callback_.Run(identity); } -ApplicationManager::Instance* ApplicationManager::GetExistingInstance( - const Identity& identity) const { +Shell::Instance* Shell::GetExistingInstance(const Identity& identity) const { const auto& it = identity_to_instance_.find(identity); return it != identity_to_instance_.end() ? it->second : nullptr; } -void ApplicationManager::NotifyPIDAvailable(uint32_t id, base::ProcessId pid) { +void Shell::NotifyPIDAvailable(uint32_t id, base::ProcessId pid) { instance_listeners_.ForAllPtrs([id, pid](mojom::InstanceListener* listener) { listener->InstancePIDAvailable(id, pid); }); } -bool ApplicationManager::ConnectToExistingInstance( - scoped_ptr<ConnectParams>* params) { +bool Shell::ConnectToExistingInstance(scoped_ptr<ConnectParams>* params) { Instance* instance = GetExistingInstance((*params)->target()); if (!instance) { Identity root_identity = (*params)->target(); - root_identity.set_user_id(mojom::Connector::kUserRoot); + root_identity.set_user_id(mojom::kRootUserID); instance = GetExistingInstance(root_identity); if (!instance) return false; } @@ -408,9 +420,8 @@ return true; } -ApplicationManager::Instance* ApplicationManager::CreateInstance( - const Identity& target_id, - mojom::ShellClientRequest* request) { +Shell::Instance* Shell::CreateInstance(const Identity& target_id, + mojom::ShellClientRequest* request) { mojom::ShellClientPtr shell_client; *request = GetProxy(&shell_client); Instance* instance = new Instance(std::move(shell_client), this, target_id); @@ -422,21 +433,30 @@ [this, &info](mojom::InstanceListener* listener) { listener->InstanceCreated(info.Clone()); }); - instance->Initialize(); + instance->InitializeClient(); return instance; } -void ApplicationManager::CreateShellClient( - const Identity& source, - const Identity& shell_client_factory, - const std::string& name, - mojom::ShellClientRequest request) { +void Shell::AddInstanceListener(mojom::InstanceListenerPtr listener) { + // TODO(beng): filter instances provided by those visible to this client. + Array<mojom::InstanceInfoPtr> instances; + for (auto& instance : identity_to_instance_) + instances.push_back(instance.second->CreateInstanceInfo()); + listener->SetExistingInstances(std::move(instances)); + + instance_listeners_.AddInterfacePtr(std::move(listener)); +} + +void Shell::CreateShellClient(const Identity& source, + const Identity& shell_client_factory, + const std::string& name, + mojom::ShellClientRequest request) { mojom::ShellClientFactory* factory = GetShellClientFactory(shell_client_factory, source); factory->CreateShellClient(std::move(request), name); } -mojom::ShellClientFactory* ApplicationManager::GetShellClientFactory( +mojom::ShellClientFactory* Shell::GetShellClientFactory( const Identity& shell_client_factory_identity, const Identity& source_identity) { auto it = shell_client_factories_.find(shell_client_factory_identity); @@ -449,26 +469,25 @@ &factory); mojom::ShellClientFactory* factory_interface = factory.get(); factory.set_connection_error_handler( - base::Bind(&ApplicationManager::OnShellClientFactoryLost, + base::Bind(&Shell::OnShellClientFactoryLost, weak_ptr_factory_.GetWeakPtr(), shell_client_factory_identity)); shell_client_factories_[shell_client_factory_identity] = std::move(factory); return factory_interface; } -void ApplicationManager::OnShellClientFactoryLost(const Identity& which) { +void Shell::OnShellClientFactoryLost(const Identity& which) { // Remove the mapping. auto it = shell_client_factories_.find(which); DCHECK(it != shell_client_factories_.end()); shell_client_factories_.erase(it); } -void ApplicationManager::OnGotResolvedName( - scoped_ptr<ConnectParams> params, - const String& resolved_name, - const String& resolved_qualifier, - mojom::CapabilityFilterPtr base_filter, - const String& file_url) { +void Shell::OnGotResolvedName(scoped_ptr<ConnectParams> params, + const String& resolved_name, + const String& resolved_qualifier, + mojom::CapabilityFilterPtr base_filter, + const String& file_url) { std::string qualifier = params->target().qualifier(); if (qualifier == GetNamePath(params->target().name())) qualifier = resolved_qualifier; @@ -515,8 +534,8 @@ } } -bool ApplicationManager::LoadWithLoader(const Identity& target, - mojom::ShellClientRequest* request) { +bool Shell::LoadWithLoader(const Identity& target, + mojom::ShellClientRequest* request) { Loader* loader = GetLoaderForName(target.name()); if (!loader) return false; @@ -524,14 +543,14 @@ return true; } -Loader* ApplicationManager::GetLoaderForName(const std::string& name) { +Loader* Shell::GetLoaderForName(const std::string& name) { auto name_it = name_to_loader_.find(name); if (name_it != name_to_loader_.end()) return name_it->second; return default_loader_.get(); } -void ApplicationManager::CleanupRunner(NativeRunner* runner) { +void Shell::CleanupRunner(NativeRunner* runner) { for (auto it = native_runners_.begin(); it != native_runners_.end(); ++it) { if (it->get() == runner) { native_runners_.erase(it);
diff --git a/mojo/shell/application_manager.h b/mojo/shell/shell.h similarity index 77% rename from mojo/shell/application_manager.h rename to mojo/shell/shell.h index ff81be1..4a5dcb2 100644 --- a/mojo/shell/application_manager.h +++ b/mojo/shell/shell.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 MOJO_SHELL_APPLICATION_MANAGER_H_ -#define MOJO_SHELL_APPLICATION_MANAGER_H_ +#ifndef MOJO_SHELL_SHELL_H_ +#define MOJO_SHELL_SHELL_H_ #include <map> #include <vector> @@ -21,7 +21,7 @@ #include "mojo/shell/native_runner.h" #include "mojo/shell/public/cpp/interface_factory.h" #include "mojo/shell/public/cpp/shell_client.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" #include "mojo/shell/public/interfaces/shell.mojom.h" #include "mojo/shell/public/interfaces/shell_client.mojom.h" @@ -36,20 +36,18 @@ class ShellConnection; namespace shell { -class ApplicationManager : public ShellClient, - public InterfaceFactory<mojom::ApplicationManager>, - public mojom::ApplicationManager { +class Shell : public ShellClient { public: // API for testing. class TestAPI { public: - explicit TestAPI(ApplicationManager* manager); + explicit TestAPI(Shell* shell); ~TestAPI(); // Returns true if there is a Instance for this name. bool HasRunningInstanceForName(const std::string& name) const; private: - ApplicationManager* manager_; + Shell* shell_; DISALLOW_COPY_AND_ASSIGN(TestAPI); }; @@ -60,15 +58,14 @@ // |file_task_runner| provides access to a thread to perform file copy // operations on. This may be null only in testing environments where // applications are loaded via Loader implementations. - ApplicationManager( - scoped_ptr<NativeRunnerFactory> native_runner_factory, - base::TaskRunner* file_task_runner, - scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog); - ~ApplicationManager() override; + Shell(scoped_ptr<NativeRunnerFactory> native_runner_factory, + base::TaskRunner* file_task_runner, + scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog); + ~Shell() override; // Provide a callback to be notified whenever an instance is destroyed. - // Typically the creator of the ApplicationManager will use this to determine - // when some set of instances it created are destroyed, so it can shut down. + // Typically the creator of the Shell will use this to determine when some set + // of instances it created are destroyed, so it can shut down. void SetInstanceQuitCallback(base::Callback<void(const Identity&)> callback); // Completes a connection between a source and target application as defined @@ -77,9 +74,9 @@ void Connect(scoped_ptr<ConnectParams> params); // Creates a new Instance identified as |name|. This is intended for use by - // the ApplicationManager's embedder to register itself with the shell. The - // name is never resolved and there must not be an existing instance - // associated with it. This must only be called once. + // the Shell's embedder to register itself with the shell. The name is never + // resolved and there must not be an existing instance associated with it. + // This must only be called once. mojom::ShellClientRequest InitInstanceForEmbedder(const std::string& name); // Sets the default Loader to be used if not overridden by SetLoaderForName(). @@ -101,23 +98,12 @@ // ShellClient: bool AcceptConnection(Connection* connection) override; - // InterfaceFactory<mojom::ApplicationManager>: - void Create(Connection* connection, - InterfaceRequest<mojom::ApplicationManager> request) override; - - // mojom::ApplicationManager: - void CreateInstanceForHandle(ScopedHandle channel, - const String& name, - mojom::CapabilityFilterPtr filter, - mojom::PIDReceiverRequest pid_receiver) override; - void AddInstanceListener(mojom::InstanceListenerPtr listener) override; - void InitPackageManager( scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog); // Destroys all Shell-ends of connections established with Applications. - // Applications connected by this ApplicationManager will observe pipe errors - // and have a chance to shutdown. + // Applications connected by this Shell will observe pipe errors and have a + // chance to shutdown. void TerminateShellConnections(); // Removes a Instance when it encounters an error. @@ -135,6 +121,17 @@ Instance* CreateInstance(const Identity& target_id, mojom::ShellClientRequest* request); + // Called from the instance implementing mojom::Shell. |user_id| must be + // resolved by the instance (i.e. must not be mojom::kInheritUserID). + void CreateInstanceForFactory( + mojom::ShellClientFactoryPtr factory, + const std::string& name, + const std::string& user_id, + mojom::CapabilityFilterPtr filter, + mojom::PIDReceiverRequest pid_receiver); + // Called from the instance implementing mojom::Shell. + void AddInstanceListener(mojom::InstanceListenerPtr listener); + void CreateShellClient(const Identity& source, const Identity& shell_client_factory, const std::string& name, @@ -193,10 +190,9 @@ scoped_ptr<NativeRunnerFactory> native_runner_factory_; std::vector<scoped_ptr<NativeRunner>> native_runners_; scoped_ptr<ShellConnection> shell_connection_; - BindingSet<mojom::ApplicationManager> bindings_; - base::WeakPtrFactory<ApplicationManager> weak_ptr_factory_; + base::WeakPtrFactory<Shell> weak_ptr_factory_; - DISALLOW_COPY_AND_ASSIGN(ApplicationManager); + DISALLOW_COPY_AND_ASSIGN(Shell); }; mojom::Connector::ConnectCallback EmptyConnectCallback(); @@ -204,4 +200,4 @@ } // namespace shell } // namespace mojo -#endif // MOJO_SHELL_APPLICATION_MANAGER_H_ +#endif // MOJO_SHELL_SHELL_H_
diff --git a/mojo/shell/standalone/context.cc b/mojo/shell/standalone/context.cc index e1a5e77..6cd1ac4 100644 --- a/mojo/shell/standalone/context.cc +++ b/mojo/shell/standalone/context.cc
@@ -155,9 +155,8 @@ scoped_ptr<package_manager::ApplicationCatalogStore> app_catalog; if (init_params) app_catalog = std::move(init_params->app_catalog); - application_manager_.reset(new ApplicationManager(std::move(runner_factory), - blocking_pool_.get(), - std::move(app_catalog))); + shell_.reset(new Shell(std::move(runner_factory), blocking_pool_.get(), + std::move(app_catalog))); shell::mojom::InterfaceProviderPtr tracing_remote_interfaces; shell::mojom::InterfaceProviderPtr tracing_local_interfaces; @@ -165,11 +164,11 @@ scoped_ptr<ConnectParams> params(new ConnectParams); params->set_source(CreateShellIdentity()); - params->set_target(Identity("mojo:tracing", std::string(), - mojom::Connector::kUserInherit)); + params->set_target( + Identity("mojo:tracing", std::string(), mojom::kInheritUserID)); params->set_remote_interfaces(GetProxy(&tracing_remote_interfaces)); params->set_local_interfaces(std::move(tracing_local_interfaces)); - application_manager_->Connect(std::move(params)); + shell_->Connect(std::move(params)); if (command_line.HasSwitch(tracing::kTraceStartup)) { tracing::TraceCollectorPtr coordinator; @@ -196,10 +195,10 @@ } void Context::Shutdown() { - // Actions triggered by ApplicationManager's destructor may require a current - // message loop, so we should destruct it explicitly now as ~Context() occurs - // post message loop shutdown. - application_manager_.reset(); + // Actions triggered by Shell's destructor may require a current message loop, + // so we should destruct it explicitly now as ~Context() occurs post message + // loop shutdown. + shell_.reset(); TRACE_EVENT0("mojo_shell", "Context::Shutdown"); DCHECK_EQ(base::MessageLoop::current()->task_runner(), shell_runner_); @@ -232,19 +231,17 @@ } void Context::Run(const std::string& name) { - application_manager_->SetInstanceQuitCallback( - base::Bind(&OnInstanceQuit, name)); + shell_->SetInstanceQuitCallback(base::Bind(&OnInstanceQuit, name)); shell::mojom::InterfaceProviderPtr remote_interfaces; shell::mojom::InterfaceProviderPtr local_interfaces; scoped_ptr<ConnectParams> params(new ConnectParams); params->set_source(CreateShellIdentity()); - params->set_target(Identity(name, std::string(), - mojom::Connector::kUserRoot)); + params->set_target(Identity(name, std::string(), mojom::kRootUserID)); params->set_remote_interfaces(GetProxy(&remote_interfaces)); params->set_local_interfaces(std::move(local_interfaces)); - application_manager_->Connect(std::move(params)); + shell_->Connect(std::move(params)); } } // namespace shell
diff --git a/mojo/shell/standalone/context.h b/mojo/shell/standalone/context.h index 2b729a9..6daf8d1f 100644 --- a/mojo/shell/standalone/context.h +++ b/mojo/shell/standalone/context.h
@@ -12,7 +12,7 @@ #include "base/threading/thread.h" #include "base/time/time.h" #include "mojo/edk/embedder/process_delegate.h" -#include "mojo/shell/application_manager.h" +#include "mojo/shell/shell.h" #include "mojo/shell/standalone/tracer.h" namespace base { @@ -53,9 +53,7 @@ // Run the application specified on the command line. void RunCommandLineApplication(); - ApplicationManager* application_manager() { - return application_manager_.get(); - } + Shell* shell() { return shell_.get(); } private: // edk::ProcessDelegate: @@ -71,7 +69,7 @@ // Ensure this is destructed before task_runners_ since it owns a message pipe // that needs the IO thread to destruct cleanly. Tracer tracer_; - scoped_ptr<ApplicationManager> application_manager_; + scoped_ptr<Shell> shell_; base::Time main_entry_time_; DISALLOW_COPY_AND_ASSIGN(Context);
diff --git a/mojo/shell/tests/BUILD.gn b/mojo/shell/tests/BUILD.gn index 52f4c47..008eff4 100644 --- a/mojo/shell/tests/BUILD.gn +++ b/mojo/shell/tests/BUILD.gn
@@ -31,9 +31,9 @@ "//mojo/shell/background:main", "//mojo/shell/background/tests:unittests", "//mojo/shell/public/cpp", - "//mojo/shell/tests/application_manager", "//mojo/shell/tests/connect", "//mojo/shell/tests/lifecycle", + "//mojo/shell/tests/shell", "//mojo/util:filename_util", "//testing/gtest", ]
diff --git a/mojo/shell/tests/application_manager/application_manager_unittest_manifest.json b/mojo/shell/tests/application_manager/application_manager_unittest_manifest.json deleted file mode 100644 index 9aea712..0000000 --- a/mojo/shell/tests/application_manager/application_manager_unittest_manifest.json +++ /dev/null
@@ -1,5 +0,0 @@ -{ - "name": "mojo:application_manager_unittest", - "display_name": "Application Manager Unittest", - "capabilities": { "*": [ "*" ] } -}
diff --git a/mojo/shell/tests/application_manager/driver_manifest.json b/mojo/shell/tests/application_manager/driver_manifest.json deleted file mode 100644 index 9c8dd47..0000000 --- a/mojo/shell/tests/application_manager/driver_manifest.json +++ /dev/null
@@ -1,5 +0,0 @@ -{ - "name": "exe:application_manager_unittest_driver", - "display_name": "Application Manager Unittest: Driver", - "capabilities": { "*": [ "*" ] } -}
diff --git a/mojo/shell/tests/connect/connect_test.mojom b/mojo/shell/tests/connect/connect_test.mojom index fbd5a398..356061e 100644 --- a/mojo/shell/tests/connect/connect_test.mojom +++ b/mojo/shell/tests/connect/connect_test.mojom
@@ -19,11 +19,11 @@ struct ConnectionState { string connection_local_name; string connection_remote_name; - uint32 connection_remote_userid; + string connection_remote_userid; uint32 connection_remote_id; string initialize_local_name; + string initialize_userid; uint32 initialize_id; - uint32 initialize_userid; }; interface ExposedInterface {
diff --git a/mojo/shell/tests/connect/connect_test_app.cc b/mojo/shell/tests/connect/connect_test_app.cc index 5081c8b..2853c90 100644 --- a/mojo/shell/tests/connect/connect_test_app.cc +++ b/mojo/shell/tests/connect/connect_test_app.cc
@@ -12,7 +12,7 @@ #include "mojo/shell/public/cpp/connector.h" #include "mojo/shell/public/cpp/interface_factory.h" #include "mojo/shell/public/cpp/shell_client.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "mojo/shell/tests/connect/connect_test.mojom.h" namespace mojo { @@ -34,7 +34,7 @@ private: // mojo::ShellClient: void Initialize(Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) override { + const std::string& user_id, uint32_t id) override { connector_ = connector; name_ = name; id_ = id; @@ -102,7 +102,7 @@ base::RunLoop run_loop; scoped_ptr<Connection> connection = connector_->Connect("mojo:connect_test_a"); - connection->SetRemoteInterfaceProviderConnectionErrorHandler( + connection->SetConnectionLostClosure( base::Bind(&ConnectTestApp::OnConnectionBlocked, base::Unretained(this), callback, &run_loop)); test::mojom::ConnectTestServicePtr test_service; @@ -110,7 +110,13 @@ test_service->GetTitle( base::Bind(&ConnectTestApp::OnGotTitle, base::Unretained(this), callback, &run_loop)); - run_loop.Run(); + { + // This message is dispatched as a task on the same run loop, so we need + // to allow nesting in order to pump additional signals. + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + run_loop.Run(); + } } // test::mojom::BlockedInterface: @@ -141,7 +147,7 @@ Connector* connector_ = nullptr; std::string name_; uint32_t id_ = mojom::Connector::kInvalidApplicationID; - uint32_t userid_ = mojom::Connector::kUserRoot; + std::string userid_ = mojom::kRootUserID; BindingSet<test::mojom::ConnectTestService> bindings_; BindingSet<test::mojom::StandaloneApp> standalone_bindings_; BindingSet<test::mojom::BlockedInterface> blocked_bindings_;
diff --git a/mojo/shell/tests/connect/connect_test_package.cc b/mojo/shell/tests/connect/connect_test_package.cc index 91b6aa2..e672824 100644 --- a/mojo/shell/tests/connect/connect_test_package.cc +++ b/mojo/shell/tests/connect/connect_test_package.cc
@@ -51,7 +51,7 @@ private: // mojo::ShellClient: void Initialize(Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) override { + const std::string& user_id, uint32_t id) override { name_ = name; id_ = id; userid_ = user_id; @@ -115,7 +115,7 @@ std::string name_; uint32_t id_ = mojom::Connector::kInvalidApplicationID; - uint32_t userid_ = mojom::Connector::kUserRoot; + std::string userid_ = mojom::kRootUserID; const std::string title_; mojom::ShellClientRequest request_; test::mojom::ExposedInterfacePtr caller_; @@ -138,7 +138,7 @@ private: // mojo::ShellClient: void Initialize(Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) override { + const std::string& user_id, uint32_t id) override { bindings_.set_connection_error_handler( base::Bind(&ConnectTestShellClient::OnConnectionError, base::Unretained(this)));
diff --git a/mojo/shell/tests/connect/connect_unittest.cc b/mojo/shell/tests/connect/connect_unittest.cc index d134875..b3bb952 100644 --- a/mojo/shell/tests/connect/connect_unittest.cc +++ b/mojo/shell/tests/connect/connect_unittest.cc
@@ -13,7 +13,7 @@ #include "base/test/test_suite.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "mojo/shell/public/cpp/shell_test.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/shell.mojom.h" #include "mojo/shell/tests/connect/connect_test.mojom.h" // Tests that multiple applications can be packaged in a single Mojo application @@ -56,11 +56,11 @@ void CompareConnectionState( const std::string& connection_local_name, const std::string& connection_remote_name, - uint32_t connection_remote_userid, + const std::string& connection_remote_userid, uint32_t connection_remote_id, const std::string& initialize_local_name, - uint32_t initialize_id, - uint32_t initialize_userid) { + const std::string& initialize_userid, + uint32_t initialize_id) { EXPECT_EQ(connection_local_name, connection_state_->connection_local_name); EXPECT_EQ(connection_remote_name, connection_state_->connection_remote_name); @@ -187,8 +187,7 @@ test::mojom::ConnectTestServicePtr service_b; connection->GetInterface(&service_b); base::RunLoop run_loop; - connection->SetRemoteInterfaceProviderConnectionErrorHandler( - base::Bind(&QuitLoop, &run_loop)); + connection->SetConnectionLostClosure(base::Bind(&QuitLoop, &run_loop)); run_loop.Run(); uint32_t id = mojom::Connector::kInvalidApplicationID; EXPECT_TRUE(connection->GetRemoteApplicationID(&id)); @@ -211,7 +210,8 @@ base::RunLoop run_loop; EXPECT_FALSE(connection->GetRemoteApplicationID(&remote_id)); EXPECT_EQ(mojom::Connector::kInvalidApplicationID, remote_id); - connection->AddRemoteIDCallback(base::Bind(&QuitLoop, &run_loop)); + connection->AddConnectionCompletedClosure( + base::Bind(&QuitLoop, &run_loop)); run_loop.Run(); EXPECT_TRUE(connection->GetRemoteApplicationID(&remote_id)); EXPECT_NE(mojom::Connector::kInvalidApplicationID, remote_id); @@ -223,7 +223,7 @@ run_loop.Run(); CompareConnectionState( kTestAppName, test_name(), test_userid(), test_instance_id(), - kTestAppName, remote_id, connection->GetRemoteUserID()); + kTestAppName, connection->GetRemoteUserID(), remote_id); } } @@ -239,7 +239,8 @@ base::RunLoop run_loop; EXPECT_FALSE(connection->GetRemoteApplicationID(&remote_id)); EXPECT_EQ(mojom::Connector::kInvalidApplicationID, remote_id); - connection->AddRemoteIDCallback(base::Bind(&QuitLoop, &run_loop)); + connection->AddConnectionCompletedClosure( + base::Bind(&QuitLoop, &run_loop)); run_loop.Run(); EXPECT_TRUE(connection->GetRemoteApplicationID(&remote_id)); EXPECT_NE(mojom::Connector::kInvalidApplicationID, remote_id); @@ -251,7 +252,7 @@ run_loop.Run(); CompareConnectionState( kTestAppAName, test_name(), test_userid(), test_instance_id(), - kTestAppAName, remote_id, connection->GetRemoteUserID()); + kTestAppAName, connection->GetRemoteUserID(), remote_id); } }
diff --git a/mojo/shell/tests/lifecycle/BUILD.gn b/mojo/shell/tests/lifecycle/BUILD.gn index 2cda88b..302ba98 100644 --- a/mojo/shell/tests/lifecycle/BUILD.gn +++ b/mojo/shell/tests/lifecycle/BUILD.gn
@@ -17,13 +17,16 @@ ":manifest", "//base", "//base/test:test_support", + "//mojo/edk/system", "//mojo/shell/public/cpp:shell_test_support", "//mojo/shell/public/cpp:sources", "//mojo/shell/public/interfaces", + "//mojo/shell/runner/common", ] data_deps = [ ":lifecycle_unittest_app", + ":lifecycle_unittest_exe", ":lifecycle_unittest_package", ] } @@ -108,3 +111,23 @@ application_name = "lifecycle_unittest_app" source = "app_manifest.json" } + +executable("lifecycle_unittest_exe") { + testonly = true + sources = [ + "lifecycle_exe.cc", + ] + deps = [ + ":app_client", + ":lifecycle_unittest_exe_manifest", + "//base", + "//mojo/shell/public/cpp:sources", + "//mojo/shell/runner/child:test_native_main", + ] +} + +mojo_application_manifest("lifecycle_unittest_exe_manifest") { + type = "exe" + application_name = "lifecycle_unittest_exe" + source = "exe_manifest.json" +}
diff --git a/mojo/shell/tests/lifecycle/exe_manifest.json b/mojo/shell/tests/lifecycle/exe_manifest.json new file mode 100644 index 0000000..0308da76 --- /dev/null +++ b/mojo/shell/tests/lifecycle/exe_manifest.json
@@ -0,0 +1,5 @@ +{ + "name": "exe:lifecycle_unittest_exe", + "display_name": "Lifecycle Unittest Exe", + "capabilities": {} +}
diff --git a/mojo/shell/tests/lifecycle/lifecycle_exe.cc b/mojo/shell/tests/lifecycle/lifecycle_exe.cc new file mode 100644 index 0000000..78d7fa0 --- /dev/null +++ b/mojo/shell/tests/lifecycle/lifecycle_exe.cc
@@ -0,0 +1,23 @@ +// 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 "base/at_exit.h" +#include "base/command_line.h" +#include "base/macros.h" +#include "mojo/shell/public/cpp/connection.h" +#include "mojo/shell/public/cpp/connector.h" +#include "mojo/shell/public/cpp/shell_client.h" +#include "mojo/shell/runner/child/test_native_main.h" +#include "mojo/shell/runner/init.h" +#include "mojo/shell/tests/lifecycle/app_client.h" + +int main(int argc, char** argv) { + base::AtExitManager at_exit; + base::CommandLine::Init(argc, argv); + + mojo::shell::InitializeLogging(); + + mojo::shell::test::AppClient client; + return mojo::shell::TestNativeMain(&client); +}
diff --git a/mojo/shell/tests/lifecycle/lifecycle_unittest.cc b/mojo/shell/tests/lifecycle/lifecycle_unittest.cc index 5b9fd0ac9..a852f052 100644 --- a/mojo/shell/tests/lifecycle/lifecycle_unittest.cc +++ b/mojo/shell/tests/lifecycle/lifecycle_unittest.cc
@@ -2,12 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/base_paths.h" +#include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/macros.h" +#include "base/path_service.h" +#include "base/process/process.h" #include "base/run_loop.h" +#include "mojo/edk/embedder/embedder.h" +#include "mojo/edk/embedder/platform_channel_pair.h" +#include "mojo/edk/embedder/scoped_platform_handle.h" #include "mojo/shell/public/cpp/shell_test.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/runner/common/switches.h" #include "mojo/shell/tests/lifecycle/lifecycle_unittest.mojom.h" namespace mojo { @@ -15,6 +23,7 @@ namespace { const char kTestAppName[] = "mojo:lifecycle_unittest_app"; +const char kTestExeName[] = "exe:lifecycle_unittest_exe"; const char kTestPackageName[] = "mojo:lifecycle_unittest_package"; const char kTestPackageAppNameA[] = "mojo:lifecycle_unittest_package_app_a"; const char kTestPackageAppNameB[] = "mojo:lifecycle_unittest_package_app_b"; @@ -155,6 +164,80 @@ return lifecycle; } + base::Process LaunchProcess() { + base::FilePath target_path; + CHECK(base::PathService::Get(base::DIR_EXE, &target_path)); + #if defined(OS_WIN) + target_path = target_path.Append( + FILE_PATH_LITERAL("lifecycle_unittest_exe.exe")); + #else + target_path = target_path.Append( + FILE_PATH_LITERAL("lifecycle_unittest_exe")); + #endif + + base::CommandLine child_command_line(target_path); + // Forward the wait-for-debugger flag but nothing else - we don't want to + // stamp on the platform-channel flag. + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kWaitForDebugger)) { + child_command_line.AppendSwitch(switches::kWaitForDebugger); + } + + mojo::shell::mojom::PIDReceiverPtr receiver; + mojo::InterfaceRequest<mojo::shell::mojom::PIDReceiver> request = + GetProxy(&receiver); + + // Create the channel to be shared with the target process. Pass one end + // on the command line. + mojo::edk::PlatformChannelPair platform_channel_pair; + mojo::edk::HandlePassingInformation handle_passing_info; + platform_channel_pair.PrepareToPassClientHandleToChildProcess( + &child_command_line, &handle_passing_info); + + // Generate a token for the child to find and connect to a primordial pipe + // and pass that as well. + std::string primordial_pipe_token = mojo::edk::GenerateRandomToken(); + child_command_line.AppendSwitchASCII(switches::kPrimordialPipeToken, + primordial_pipe_token); + + // Allocate the pipe locally. + mojo::ScopedMessagePipeHandle pipe = + mojo::edk::CreateParentMessagePipe(primordial_pipe_token); + + mojo::shell::mojom::CapabilityFilterPtr filter( + mojo::shell::mojom::CapabilityFilter::New()); + mojo::Array<mojo::String> test_interfaces; + test_interfaces.push_back("*"); + filter->filter.insert("*", std::move(test_interfaces)); + + mojo::shell::mojom::ShellPtr shell; + connector()->ConnectToInterface("mojo:shell", &shell); + + mojo::shell::mojom::ShellClientFactoryPtr factory; + factory.Bind(mojo::InterfacePtrInfo<mojo::shell::mojom::ShellClientFactory>( + std::move(pipe), 0u)); + base::RunLoop loop; + shell->CreateInstance(std::move(factory), kTestExeName, + mojom::kInheritUserID, std::move(filter), + std::move(request), + base::Bind(&LifecycleTest::OnConnectionCompleted, + base::Unretained(this), &loop)); + loop.Run(); + + base::LaunchOptions options; + #if defined(OS_WIN) + options.handles_to_inherit = &handle_passing_info; + #elif defined(OS_POSIX) + options.fds_to_remap = &handle_passing_info; + #endif + base::Process process = base::LaunchProcess(child_command_line, options); + DCHECK(process.IsValid()); + receiver->SetPID(process.Pid()); + mojo::edk::ChildProcessLaunched(process.Handle(), + platform_channel_pair.PassServerHandle()); + return process; + } + void PingPong(test::mojom::LifecycleControl* lifecycle) { base::RunLoop loop; lifecycle->Ping(base::Bind(&QuitLoop, &loop)); @@ -171,16 +254,21 @@ private: scoped_ptr<InstanceState> TrackInstances() { - mojom::ApplicationManagerPtr am; - connector()->ConnectToInterface("mojo:shell", &am); + mojom::ShellPtr shell; + connector()->ConnectToInterface("mojo:shell", &shell); mojom::InstanceListenerPtr listener; base::RunLoop loop; InstanceState* state = new InstanceState(GetProxy(&listener), &loop); - am->AddInstanceListener(std::move(listener)); + shell->AddInstanceListener(std::move(listener)); loop.Run(); return make_scoped_ptr(state); } + void OnConnectionCompleted(base::RunLoop* loop, + mojom::ConnectResult result) { + loop->Quit(); + } + scoped_ptr<InstanceState> instances_; DISALLOW_COPY_AND_ASSIGN(LifecycleTest); @@ -384,5 +472,44 @@ EXPECT_EQ(0u, instances()->GetNewInstanceCount()); } +TEST_F(LifecycleTest, Exe_GracefulQuit) { + base::Process process = LaunchProcess(); + + test::mojom::LifecycleControlPtr lifecycle = ConnectTo(kTestExeName); + + EXPECT_TRUE(instances()->HasInstanceForName(kTestExeName)); + EXPECT_EQ(1u, instances()->GetNewInstanceCount()); + + base::RunLoop loop; + lifecycle.set_connection_error_handler(base::Bind(&QuitLoop, &loop)); + lifecycle->GracefulQuit(); + loop.Run(); + + WaitForInstanceDestruction(); + EXPECT_FALSE(instances()->HasInstanceForName(kTestExeName)); + EXPECT_EQ(0u, instances()->GetNewInstanceCount()); + + process.Terminate(9, true); +} + +TEST_F(LifecycleTest, Exe_TerminateProcess) { + base::Process process = LaunchProcess(); + + test::mojom::LifecycleControlPtr lifecycle = ConnectTo(kTestExeName); + + EXPECT_TRUE(instances()->HasInstanceForName(kTestExeName)); + EXPECT_EQ(1u, instances()->GetNewInstanceCount()); + + base::RunLoop loop; + lifecycle.set_connection_error_handler(base::Bind(&QuitLoop, &loop)); + process.Terminate(9, true); + loop.Run(); + + WaitForInstanceDestruction(); + EXPECT_FALSE(instances()->HasInstanceForName(kTestExeName)); + EXPECT_EQ(0u, instances()->GetNewInstanceCount()); +} + + } // namespace shell } // namespace mojo
diff --git a/mojo/shell/tests/loader_unittest.cc b/mojo/shell/tests/loader_unittest.cc index 4c88fb59..45156be 100644 --- a/mojo/shell/tests/loader_unittest.cc +++ b/mojo/shell/tests/loader_unittest.cc
@@ -12,7 +12,6 @@ #include "base/run_loop.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "mojo/services/package_manager/package_manager.h" -#include "mojo/shell/application_manager.h" #include "mojo/shell/connect_util.h" #include "mojo/shell/loader.h" #include "mojo/shell/public/cpp/connector.h" @@ -20,6 +19,7 @@ #include "mojo/shell/public/cpp/shell_client.h" #include "mojo/shell/public/cpp/shell_connection.h" #include "mojo/shell/public/interfaces/interface_provider.mojom.h" +#include "mojo/shell/shell.h" #include "mojo/shell/tests/test.mojom.h" #include "testing/gtest/include/gtest/gtest.h" @@ -389,7 +389,8 @@ ScopedVector<TestAImpl> a_bindings_; }; -void OnConnect(base::RunLoop* loop, uint32_t instance_id, uint32_t user_id) { +void OnConnect(base::RunLoop* loop, mojom::ConnectResult result, + const String& user_id, uint32_t instance_id) { loop->Quit(); } @@ -399,10 +400,9 @@ ~LoaderTest() override {} void SetUp() override { - application_manager_.reset( - new ApplicationManager(nullptr, nullptr, nullptr)); + shell_.reset(new Shell(nullptr, nullptr, nullptr)); test_loader_ = new TestLoader(&context_); - application_manager_->set_default_loader(scoped_ptr<Loader>(test_loader_)); + shell_->set_default_loader(scoped_ptr<Loader>(test_loader_)); TestServicePtr service_proxy; ConnectToInterface(kTestURLString, &service_proxy); @@ -411,18 +411,18 @@ void TearDown() override { test_client_.reset(); - application_manager_.reset(); + shell_.reset(); } void AddLoaderForName(const std::string& name, const std::string& requestor_name) { - application_manager_->SetLoaderForName( + shell_->SetLoaderForName( make_scoped_ptr(new Tester(&tester_context_, requestor_name)), name); } bool HasRunningInstanceForName(const std::string& name) { - ApplicationManager::TestAPI manager_test_api(application_manager_.get()); - return manager_test_api.HasRunningInstanceForName(name); + Shell::TestAPI test_api(shell_.get()); + return test_api.HasRunningInstanceForName(name); } protected: @@ -437,7 +437,7 @@ params->set_remote_interfaces(GetProxy(&remote_interfaces)); params->set_connect_callback( base::Bind(&OnConnect, base::Unretained(&loop))); - application_manager_->Connect(std::move(params)); + shell_->Connect(std::move(params)); loop.Run(); mojo::GetInterface(remote_interfaces.get(), ptr); @@ -449,7 +449,7 @@ TestContext context_; base::MessageLoop loop_; scoped_ptr<TestClient> test_client_; - scoped_ptr<ApplicationManager> application_manager_; + scoped_ptr<Shell> shell_; DISALLOW_COPY_AND_ASSIGN(LoaderTest); }; @@ -472,13 +472,13 @@ TEST_F(LoaderTest, Deletes) { { - ApplicationManager am(nullptr, nullptr, nullptr); + Shell shell(nullptr, nullptr, nullptr); TestLoader* default_loader = new TestLoader(&context_); TestLoader* name_loader1 = new TestLoader(&context_); TestLoader* name_loader2 = new TestLoader(&context_); - am.set_default_loader(scoped_ptr<Loader>(default_loader)); - am.SetLoaderForName(scoped_ptr<Loader>(name_loader1), "test:test1"); - am.SetLoaderForName(scoped_ptr<Loader>(name_loader2), "test:test1"); + shell.set_default_loader(scoped_ptr<Loader>(default_loader)); + shell.SetLoaderForName(scoped_ptr<Loader>(name_loader1), "test:test1"); + shell.SetLoaderForName(scoped_ptr<Loader>(name_loader2), "test:test1"); } EXPECT_EQ(3, context_.num_loader_deletes); } @@ -487,9 +487,8 @@ TEST_F(LoaderTest, SetLoaders) { TestLoader* default_loader = new TestLoader(&context_); TestLoader* name_loader = new TestLoader(&context_); - application_manager_->set_default_loader(scoped_ptr<Loader>(default_loader)); - application_manager_->SetLoaderForName( - scoped_ptr<Loader>(name_loader), "test:test1"); + shell_->set_default_loader(scoped_ptr<Loader>(default_loader)); + shell_->SetLoaderForName(scoped_ptr<Loader>(name_loader), "test:test1"); // test::test1 should go to name_loader. TestServicePtr test_service; @@ -506,8 +505,8 @@ TEST_F(LoaderTest, NoServiceNoLoad) { AddLoaderForName(kTestAURLString, std::string()); - // There is no TestC service implementation registered with - // ApplicationManager, so this cannot succeed (but also shouldn't crash). + // There is no TestC service implementation registered with the Shell, so this + // cannot succeed (but also shouldn't crash). TestCPtr c; ConnectToInterface(kTestAURLString, &c); c.set_connection_error_handler( @@ -519,16 +518,15 @@ TEST_F(LoaderTest, TestEndApplicationClosure) { ClosingLoader* loader = new ClosingLoader(); - application_manager_->SetLoaderForName( - scoped_ptr<Loader>(loader), "test:test"); + shell_->SetLoaderForName(scoped_ptr<Loader>(loader), "test:test"); bool called = false; scoped_ptr<ConnectParams> params(new ConnectParams); params->set_source(CreateShellIdentity()); - params->set_target(Identity("test:test", "", mojom::Connector::kUserRoot)); - application_manager_->SetInstanceQuitCallback( + params->set_target(Identity("test:test", "", mojom::kRootUserID)); + shell_->SetInstanceQuitCallback( base::Bind(&QuitClosure, params->target(), &called)); - application_manager_->Connect(std::move(params)); + shell_->Connect(std::move(params)); loop_.Run(); EXPECT_TRUE(called); }
diff --git a/mojo/shell/tests/application_manager/BUILD.gn b/mojo/shell/tests/shell/BUILD.gn similarity index 74% rename from mojo/shell/tests/application_manager/BUILD.gn rename to mojo/shell/tests/shell/BUILD.gn index 6989d964..6742da11 100644 --- a/mojo/shell/tests/application_manager/BUILD.gn +++ b/mojo/shell/tests/shell/BUILD.gn
@@ -7,10 +7,10 @@ import("//mojo/public/tools/bindings/mojom.gni") import("//testing/test.gni") -source_set("application_manager") { +source_set("shell") { testonly = true sources = [ - "application_manager_unittest.cc", + "shell_unittest.cc", ] deps = [ @@ -25,23 +25,23 @@ ] data_deps = [ - ":application_manager_unittest_driver", - ":application_manager_unittest_target", + ":shell_unittest_driver", + ":shell_unittest_target", ] } mojom("interfaces") { sources = [ - "application_manager_unittest.mojom", + "shell_unittest.mojom", ] } mojo_application_manifest("manifest") { - application_name = "application_manager_unittest" - source = "application_manager_unittest_manifest.json" + application_name = "shell_unittest" + source = "shell_unittest_manifest.json" } -executable("application_manager_unittest_driver") { +executable("shell_unittest_driver") { testonly = true sources = [ @@ -63,11 +63,11 @@ mojo_application_manifest("driver_manifest") { type = "exe" - application_name = "application_manager_unittest_driver" + application_name = "shell_unittest_driver" source = "driver_manifest.json" } -executable("application_manager_unittest_target") { +executable("shell_unittest_target") { testonly = true sources = [
diff --git a/mojo/shell/tests/application_manager/driver.cc b/mojo/shell/tests/shell/driver.cc similarity index 79% rename from mojo/shell/tests/application_manager/driver.cc rename to mojo/shell/tests/shell/driver.cc index 5b114de..62c57bfc 100644 --- a/mojo/shell/tests/application_manager/driver.cc +++ b/mojo/shell/tests/shell/driver.cc
@@ -26,11 +26,12 @@ #include "mojo/shell/public/cpp/connector.h" #include "mojo/shell/public/cpp/interface_factory.h" #include "mojo/shell/public/cpp/shell_client.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" +#include "mojo/shell/public/interfaces/shell.mojom.h" #include "mojo/shell/runner/child/test_native_main.h" #include "mojo/shell/runner/common/switches.h" #include "mojo/shell/runner/init.h" -#include "mojo/shell/tests/application_manager/application_manager_unittest.mojom.h" +#include "mojo/shell/tests/shell/shell_unittest.mojom.h" namespace { @@ -44,15 +45,15 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) override { + const std::string& user_id, uint32_t id) override { base::FilePath target_path; CHECK(base::PathService::Get(base::DIR_EXE, &target_path)); #if defined(OS_WIN) target_path = target_path.Append( - FILE_PATH_LITERAL("application_manager_unittest_target.exe")); + FILE_PATH_LITERAL("shell_unittest_target.exe")); #else target_path = target_path.Append( - FILE_PATH_LITERAL("application_manager_unittest_target")); + FILE_PATH_LITERAL("shell_unittest_target")); #endif base::CommandLine child_command_line(target_path); @@ -88,16 +89,20 @@ mojo::shell::mojom::CapabilityFilter::New()); mojo::Array<mojo::String> test_interfaces; test_interfaces.push_back( - mojo::shell::test::mojom::CreateInstanceForHandleTest::Name_); - filter->filter.insert("mojo:application_manager_unittest", - std::move(test_interfaces)); + mojo::shell::test::mojom::CreateInstanceTest::Name_); + filter->filter.insert("mojo:shell_unittest", std::move(test_interfaces)); - mojo::shell::mojom::ApplicationManagerPtr application_manager; - connector->ConnectToInterface("mojo:shell", &application_manager); - application_manager->CreateInstanceForHandle( - mojo::ScopedHandle(mojo::Handle(pipe.release().value())), - "exe:application_manager_unittest_target", std::move(filter), - std::move(request)); + mojo::shell::mojom::ShellClientFactoryPtr factory; + factory.Bind(mojo::InterfacePtrInfo<mojo::shell::mojom::ShellClientFactory>( + std::move(pipe), 0u)); + + mojo::shell::mojom::ShellPtr shell; + connector->ConnectToInterface("mojo:shell", &shell); + shell->CreateInstance(std::move(factory), "exe:shell_unittest_target", + mojo::shell::mojom::kInheritUserID, std::move(filter), + std::move(request), + base::Bind(&Driver::OnConnectionCompleted, + base::Unretained(this))); base::LaunchOptions options; #if defined(OS_WIN) @@ -129,6 +134,8 @@ base::MessageLoop::current()->QuitWhenIdle(); } + void OnConnectionCompleted(mojo::shell::mojom::ConnectResult result) {} + base::Process target_; mojo::BindingSet<mojo::shell::test::mojom::Driver> bindings_; base::WeakPtrFactory<Driver> weak_factory_;
diff --git a/mojo/shell/tests/shell/driver_manifest.json b/mojo/shell/tests/shell/driver_manifest.json new file mode 100644 index 0000000..04a394a --- /dev/null +++ b/mojo/shell/tests/shell/driver_manifest.json
@@ -0,0 +1,5 @@ +{ + "name": "exe:shell_unittest_driver", + "display_name": "Shell Unittest: Driver", + "capabilities": { "*": [ "*" ] } +}
diff --git a/mojo/shell/tests/application_manager/application_manager_unittest.cc b/mojo/shell/tests/shell/shell_unittest.cc similarity index 70% rename from mojo/shell/tests/application_manager/application_manager_unittest.cc rename to mojo/shell/tests/shell/shell_unittest.cc index c4279aa6..e76142a 100644 --- a/mojo/shell/tests/application_manager/application_manager_unittest.cc +++ b/mojo/shell/tests/shell/shell_unittest.cc
@@ -15,41 +15,41 @@ #include "mojo/shell/public/cpp/interface_factory.h" #include "mojo/shell/public/cpp/shell_client.h" #include "mojo/shell/public/cpp/shell_test.h" -#include "mojo/shell/public/interfaces/application_manager.mojom.h" -#include "mojo/shell/tests/application_manager/application_manager_unittest.mojom.h" +#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/tests/shell/shell_unittest.mojom.h" namespace mojo { namespace shell { namespace { -class ApplicationManagerTestClient +class ShellTestClient : public mojo::test::ShellTestClient, - public InterfaceFactory<test::mojom::CreateInstanceForHandleTest>, - public test::mojom::CreateInstanceForHandleTest { + public InterfaceFactory<test::mojom::CreateInstanceTest>, + public test::mojom::CreateInstanceTest { public: - explicit ApplicationManagerTestClient(mojo::test::ShellTest* test) - : ShellTestClient(test), + explicit ShellTestClient(mojo::test::ShellTest* test) + : mojo::test::ShellTestClient(test), target_id_(mojom::Connector::kInvalidApplicationID), binding_(this) {} - ~ApplicationManagerTestClient() override {} + ~ShellTestClient() override {} uint32_t target_id() const { return target_id_; } private: // mojo::ShellClient: bool AcceptConnection(Connection* connection) override { - connection->AddInterface<test::mojom::CreateInstanceForHandleTest>(this); + connection->AddInterface<test::mojom::CreateInstanceTest>(this); return true; } - // InterfaceFactory<test::mojom::CreateInstanceForHandleTest>: + // InterfaceFactory<test::mojom::CreateInstanceTest>: void Create( Connection* connection, - test::mojom::CreateInstanceForHandleTestRequest request) override { + test::mojom::CreateInstanceTestRequest request) override { binding_.Bind(std::move(request)); } - // test::mojom::CreateInstanceForHandleTest: + // test::mojom::CreateInstanceTest: void SetTargetID(uint32_t target_id) override { target_id_ = target_id; base::MessageLoop::current()->QuitWhenIdle(); @@ -57,21 +57,21 @@ uint32_t target_id_; - Binding<test::mojom::CreateInstanceForHandleTest> binding_; + Binding<test::mojom::CreateInstanceTest> binding_; - DISALLOW_COPY_AND_ASSIGN(ApplicationManagerTestClient); + DISALLOW_COPY_AND_ASSIGN(ShellTestClient); }; } // namespace -class ApplicationManagerTest : public mojo::test::ShellTest, - public mojom::InstanceListener { +class ShellTest : public mojo::test::ShellTest, + public mojom::InstanceListener { public: - ApplicationManagerTest() - : ShellTest("mojo:application_manager_unittest"), + ShellTest() + : mojo::test::ShellTest("mojo:shell_unittest"), shell_client_(nullptr), binding_(this) {} - ~ApplicationManagerTest() override {} + ~ShellTest() override {} void OnDriverQuit() { base::MessageLoop::current()->QuitNow(); @@ -88,11 +88,10 @@ }; void AddListenerAndWaitForApplications() { - mojom::ApplicationManagerPtr application_manager; - connector()->ConnectToInterface("mojo:shell", &application_manager); + mojom::ShellPtr shell; + connector()->ConnectToInterface("mojo:shell", &shell); - application_manager->AddInstanceListener( - binding_.CreateInterfacePtrAndBind()); + shell->AddInstanceListener(binding_.CreateInterfacePtrAndBind()); binding_.WaitForIncomingMethodCall(); } @@ -120,7 +119,7 @@ private: // test::ShellTest: scoped_ptr<ShellClient> CreateShellClient() override { - shell_client_ = new ApplicationManagerTestClient(this); + shell_client_ = new ShellTestClient(this); return make_scoped_ptr(shell_client_); } @@ -152,26 +151,26 @@ } } - ApplicationManagerTestClient* shell_client_; + ShellTestClient* shell_client_; Binding<mojom::InstanceListener> binding_; std::vector<InstanceInfo> instances_; std::vector<InstanceInfo> initial_instances_; - DISALLOW_COPY_AND_ASSIGN(ApplicationManagerTest); + DISALLOW_COPY_AND_ASSIGN(ShellTest); }; -TEST_F(ApplicationManagerTest, CreateInstanceForHandle) { +TEST_F(ShellTest, CreateInstance) { AddListenerAndWaitForApplications(); // 1. Launch a process. (Actually, have the runner launch a process that // launches a process.) mojo::shell::test::mojom::DriverPtr driver; scoped_ptr<Connection> connection = - connector()->Connect("exe:application_manager_unittest_driver"); + connector()->Connect("exe:shell_unittest_driver"); connection->GetInterface(&driver); // 2. Wait for the target to connect to us. (via - // mojo:application_manager_unittest) + // mojo:shell_unittest) base::MessageLoop::current()->Run(); uint32_t remote_id = mojom::Connector::kInvalidApplicationID; @@ -180,7 +179,7 @@ // 3. Validate that this test suite's name was received from the application // manager. - EXPECT_TRUE(ContainsInstanceWithName("mojo:application_manager_unittest")); + EXPECT_TRUE(ContainsInstanceWithName("mojo:shell_unittest")); // 4. Validate that the right applications/processes were created. // Note that the target process will be created even if the tests are @@ -189,19 +188,19 @@ { auto& instance = instances().front(); EXPECT_EQ(remote_id, instance.id); - EXPECT_EQ("exe:application_manager_unittest_driver", instance.name); + EXPECT_EQ("exe:shell_unittest_driver", instance.name); EXPECT_NE(base::kNullProcessId, instance.pid); } { auto& instance = instances().back(); // We learn about the target process id via a ping from it. EXPECT_EQ(target_id(), instance.id); - EXPECT_EQ("exe:application_manager_unittest_target", instance.name); + EXPECT_EQ("exe:shell_unittest_target", instance.name); EXPECT_NE(base::kNullProcessId, instance.pid); } driver.set_connection_error_handler( - base::Bind(&ApplicationManagerTest::OnDriverQuit, + base::Bind(&ShellTest::OnDriverQuit, base::Unretained(this))); driver->QuitDriver(); base::MessageLoop::current()->Run();
diff --git a/mojo/shell/tests/application_manager/application_manager_unittest.mojom b/mojo/shell/tests/shell/shell_unittest.mojom similarity index 86% rename from mojo/shell/tests/application_manager/application_manager_unittest.mojom rename to mojo/shell/tests/shell/shell_unittest.mojom index c57eb40..bee0368 100644 --- a/mojo/shell/tests/application_manager/application_manager_unittest.mojom +++ b/mojo/shell/tests/shell/shell_unittest.mojom
@@ -4,7 +4,7 @@ module mojo.shell.test.mojom; -interface CreateInstanceForHandleTest { +interface CreateInstanceTest { SetTargetID(uint32 target_id); };
diff --git a/mojo/shell/tests/shell/shell_unittest_manifest.json b/mojo/shell/tests/shell/shell_unittest_manifest.json new file mode 100644 index 0000000..02ec805 --- /dev/null +++ b/mojo/shell/tests/shell/shell_unittest_manifest.json
@@ -0,0 +1,5 @@ +{ + "name": "mojo:shell_unittest", + "display_name": "Shell Unittest", + "capabilities": { "*": [ "*" ] } +}
diff --git a/mojo/shell/tests/application_manager/target.cc b/mojo/shell/tests/shell/target.cc similarity index 72% rename from mojo/shell/tests/application_manager/target.cc rename to mojo/shell/tests/shell/target.cc index 25aba82ba..3f75dc9 100644 --- a/mojo/shell/tests/application_manager/target.cc +++ b/mojo/shell/tests/shell/target.cc
@@ -10,9 +10,9 @@ #include "mojo/shell/public/cpp/shell_client.h" #include "mojo/shell/runner/child/test_native_main.h" #include "mojo/shell/runner/init.h" -#include "mojo/shell/tests/application_manager/application_manager_unittest.mojom.h" +#include "mojo/shell/tests/shell/shell_unittest.mojom.h" -using mojo::shell::test::mojom::CreateInstanceForHandleTestPtr; +using mojo::shell::test::mojom::CreateInstanceTestPtr; namespace { @@ -24,10 +24,9 @@ private: // mojo::ShellClient: void Initialize(mojo::Connector* connector, const std::string& name, - uint32_t id, uint32_t user_id) override { - CreateInstanceForHandleTestPtr service; - connector->ConnectToInterface("mojo:application_manager_unittest", - &service); + const std::string& user_id, uint32_t id) override { + CreateInstanceTestPtr service; + connector->ConnectToInterface("mojo:shell_unittest", &service); service->SetTargetID(id); }
diff --git a/net/BUILD.gn b/net/BUILD.gn index 618d6e4c..4961769 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1744,155 +1744,181 @@ # Fuzzers -fuzzer_test("parse_proxy_list_pac_fuzzer") { +source_set("net_fuzzer_test_support") { + testonly = true + + sources = [ + "base/fuzzer_test_support.cc", + ] + deps = [ + "//base", + "//base:i18n", + ] +} + +fuzzer_test("net_parse_proxy_list_pac_fuzzer") { sources = [ "proxy/parse_proxy_list_pac_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("parse_proxy_list_fuzzer") { +fuzzer_test("net_parse_proxy_list_fuzzer") { sources = [ "proxy/parse_proxy_list_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("parse_proxy_bypass_rules_fuzzer") { +fuzzer_test("net_parse_proxy_bypass_rules_fuzzer") { sources = [ "proxy/parse_proxy_bypass_rules_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("parse_proxy_rules_fuzzer") { +fuzzer_test("net_parse_proxy_rules_fuzzer") { sources = [ "proxy/parse_proxy_rules_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("parse_data_url_fuzzer") { +fuzzer_test("net_parse_data_url_fuzzer") { sources = [ "base/parse_data_url_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", "//net", ] } -fuzzer_test("sniff_mime_type_fuzzer") { +fuzzer_test("net_sniff_mime_type_fuzzer") { sources = [ "base/sniff_mime_type_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", "//net", ] } -fuzzer_test("parse_ip_pattern_fuzzer") { +fuzzer_test("net_parse_ip_pattern_fuzzer") { sources = [ "base/parse_ip_pattern_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("get_domain_and_registry_fuzzer") { +fuzzer_test("net_get_domain_and_registry_fuzzer") { sources = [ "base/registry_controlled_domains/get_domain_and_registry_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", - "//base:i18n", "//net", ] } -fuzzer_test("parse_cookie_line_fuzzer") { +fuzzer_test("net_parse_cookie_line_fuzzer") { sources = [ "cookies/parse_cookie_line_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("dns_record_fuzzer") { +fuzzer_test("net_dns_record_fuzzer") { sources = [ "dns/dns_record_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", "//net", ] } -fuzzer_test("ftp_ctrl_response_fuzzer") { +fuzzer_test("net_ftp_ctrl_response_fuzzer") { sources = [ "ftp/ftp_ctrl_response_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", "//net", ] } -fuzzer_test("ftp_directory_listing_fuzzer") { +fuzzer_test("net_ftp_directory_listing_fuzzer") { sources = [ "ftp/ftp_directory_listing_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", - "//base:i18n", "//net", ] } -fuzzer_test("unescape_url_component_fuzzer") { +fuzzer_test("net_unescape_url_component_fuzzer") { sources = [ "base/unescape_url_component_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", "//net", ] } -fuzzer_test("websocket_frame_parser_fuzzer") { +fuzzer_test("net_websocket_frame_parser_fuzzer") { sources = [ "websockets/websocket_frame_parser_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("http_chunked_decoder_fuzzer") { +fuzzer_test("net_http_chunked_decoder_fuzzer") { sources = [ "http/http_chunked_decoder_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//net", ] } -fuzzer_test("quic_crypto_framer_parse_message_fuzzer") { +fuzzer_test("net_quic_crypto_framer_parse_message_fuzzer") { sources = [ "quic/quic_crypto_framer_parse_message_fuzzer.cc", ] deps = [ + ":net_fuzzer_test_support", "//base", "//net", ]
diff --git a/net/DEPS b/net/DEPS index cddc7f0..88c82c8 100644 --- a/net/DEPS +++ b/net/DEPS
@@ -61,11 +61,7 @@ "+third_party/brotli", ], - "get_domain_and_registry_fuzzer.cc": [ - "+base/i18n", - ], - - "ftp_directory_listing_fuzzer.cc": [ + "fuzzer_test_support.cc": [ "+base/i18n", ], }
diff --git a/net/base/fuzzer_test_support.cc b/net/base/fuzzer_test_support.cc new file mode 100644 index 0000000..1c185c6 --- /dev/null +++ b/net/base/fuzzer_test_support.cc
@@ -0,0 +1,25 @@ +// 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 "base/at_exit.h" +#include "base/i18n/icu_util.h" + +namespace { + +// This translation unit provides a static initializer to set up ICU. +// +// ICU is used internally by GURL, which is used throughout the //net code. +// Initializing ICU is important to prevent fuzztests from asserting when +// handling non-ASCII urls. +// +// Note that in general static initializers are not allowed, however this is +// just being used by test code. +struct InitICU { + InitICU() { CHECK(base::i18n::InitializeICU()); } + base::AtExitManager at_exit_manager; +}; + +InitICU* init_icu = new InitICU(); + +} // namespace
diff --git a/net/base/ip_address.cc b/net/base/ip_address.cc index 170be40..82e250aa 100644 --- a/net/base/ip_address.cc +++ b/net/base/ip_address.cc
@@ -74,6 +74,19 @@ return true; } +// static +IPAddress IPAddress::IPv4Localhost() { + static const uint8_t kLocalhostIPv4[] = {127, 0, 0, 1}; + return IPAddress(kLocalhostIPv4); +} + +// static +IPAddress IPAddress::IPv6Localhost() { + static const uint8_t kLocalhostIPv6[] = {0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1}; + return IPAddress(kLocalhostIPv6); +} + bool IPAddress::operator==(const IPAddress& that) const { return ip_address_ == that.ip_address_; }
diff --git a/net/base/ip_address.h b/net/base/ip_address.h index f1f7480..2fb54b4 100644 --- a/net/base/ip_address.h +++ b/net/base/ip_address.h
@@ -87,6 +87,12 @@ // Returns the underlying byte vector. const std::vector<uint8_t>& bytes() const { return ip_address_; }; + // Returns an IPAddress instance representing the 127.0.0.1 address. + static IPAddress IPv4Localhost(); + + // Returns an IPAddress instance representing the ::1 address. + static IPAddress IPv6Localhost(); + bool operator==(const IPAddress& that) const; bool operator!=(const IPAddress& that) const; bool operator<(const IPAddress& that) const; @@ -133,6 +139,16 @@ const IPAddress& ip_prefix, size_t prefix_length_in_bits); +// Checks whether |address| starts with |prefix|. This provides similar +// functionality as IPAddressMatchesPrefix() but doesn't perform automatic IPv4 +// to IPv4MappedIPv6 conversions and only checks against full bytes. +template <size_t N> +bool IPAddressStartsWith(const IPAddress& address, const uint8_t (&prefix)[N]) { + if (address.size() < N) + return false; + return std::equal(prefix, prefix + N, address.bytes().begin()); +} + } // namespace net #endif // NET_BASE_IP_ADDRESS_NET_H_
diff --git a/net/base/ip_address_unittest.cc b/net/base/ip_address_unittest.cc index b08d10a..dffb905 100644 --- a/net/base/ip_address_unittest.cc +++ b/net/base/ip_address_unittest.cc
@@ -228,6 +228,46 @@ EXPECT_EQ(expected, result); } +TEST(IPAddressTest, IPAddressStartsWith) { + IPAddress ipv4_address(192, 168, 10, 5); + + uint8_t ipv4_prefix1[] = {192, 168, 10}; + EXPECT_TRUE(IPAddressStartsWith(ipv4_address, ipv4_prefix1)); + + uint8_t ipv4_prefix3[] = {192, 168, 10, 5}; + EXPECT_TRUE(IPAddressStartsWith(ipv4_address, ipv4_prefix3)); + + uint8_t ipv4_prefix2[] = {192, 168, 10, 10}; + EXPECT_FALSE(IPAddressStartsWith(ipv4_address, ipv4_prefix2)); + + // Prefix is longer than the address. + uint8_t ipv4_prefix4[] = {192, 168, 10, 10, 0}; + EXPECT_FALSE(IPAddressStartsWith(ipv4_address, ipv4_prefix4)); + + IPAddress ipv6_address; + EXPECT_TRUE(ipv6_address.AssignFromIPLiteral("2a00:1450:400c:c09::64")); + + uint8_t ipv6_prefix1[] = {42, 0, 20, 80, 64, 12, 12, 9}; + EXPECT_TRUE(IPAddressStartsWith(ipv6_address, ipv6_prefix1)); + + uint8_t ipv6_prefix2[] = {41, 0, 20, 80, 64, 12, 12, 9, + 0, 0, 0, 0, 0, 0, 100}; + EXPECT_FALSE(IPAddressStartsWith(ipv6_address, ipv6_prefix2)); + + uint8_t ipv6_prefix3[] = {42, 0, 20, 80, 64, 12, 12, 9, + 0, 0, 0, 0, 0, 0, 0, 100}; + EXPECT_TRUE(IPAddressStartsWith(ipv6_address, ipv6_prefix3)); + + uint8_t ipv6_prefix4[] = {42, 0, 20, 80, 64, 12, 12, 9, + 0, 0, 0, 0, 0, 0, 0, 0}; + EXPECT_FALSE(IPAddressStartsWith(ipv6_address, ipv6_prefix4)); + + // Prefix is longer than the address. + uint8_t ipv6_prefix5[] = {42, 0, 20, 80, 64, 12, 12, 9, 0, + 0, 0, 0, 0, 0, 0, 0, 10}; + EXPECT_FALSE(IPAddressStartsWith(ipv6_address, ipv6_prefix5)); +} + } // anonymous namespace } // namespace net
diff --git a/net/base/registry_controlled_domains/get_domain_and_registry_fuzzer.cc b/net/base/registry_controlled_domains/get_domain_and_registry_fuzzer.cc index 8b749c1c..e71c7dc2 100644 --- a/net/base/registry_controlled_domains/get_domain_and_registry_fuzzer.cc +++ b/net/base/registry_controlled_domains/get_domain_and_registry_fuzzer.cc
@@ -5,20 +5,10 @@ #include <stddef.h> #include <stdint.h> -#include "base/at_exit.h" -#include "base/i18n/icu_util.h" #include "base/strings/string_piece.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/gurl.h" -// Initialize ICU. -struct InitICU { - InitICU() { CHECK(base::i18n::InitializeICU()); } - base::AtExitManager at_exit_manager; -}; - -InitICU* init_icu = new InitICU(); - // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { // Call GetDomainAndRegistry() twice - once with each filter type to ensure
diff --git a/net/cookies/canonical_cookie.cc b/net/cookies/canonical_cookie.cc index fff3fa44..0a5e794f 100644 --- a/net/cookies/canonical_cookie.cc +++ b/net/cookies/canonical_cookie.cc
@@ -47,6 +47,7 @@ #include "base/format_macros.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" +#include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "net/cookies/cookie_util.h" #include "net/cookies/parsed_cookie.h" @@ -349,15 +350,14 @@ // was longer, the same length, or shorter than the length of the url path. // I think the approach below is simpler. - // Make sure the cookie path is a prefix of the url path. If the - // url path is shorter than the cookie path, then the cookie path - // can't be a prefix. - if (url_path.find(path_) != 0) + // Make sure the cookie path is a prefix of the url path. If the url path is + // shorter than the cookie path, then the cookie path can't be a prefix. + if (!base::StartsWith(url_path, path_, base::CompareCase::SENSITIVE)) return false; - // Now we know that url_path is >= cookie_path, and that cookie_path - // is a prefix of url_path. If they are the are the same length then - // they are identical, otherwise we need an additional check: + // |url_path| is >= |path_|, and |path_| is a prefix of |url_path|. If they + // are the are the same length then they are identical, otherwise need an + // additional check: // In order to avoid in correctly matching a cookie path of /blah // with a request path of '/blahblah/', we need to make sure that either @@ -365,8 +365,9 @@ // in the url path. Since we know that the url path length is greater // than the cookie path length, it's safe to index one byte past. if (path_.length() != url_path.length() && path_.back() != '/' && - url_path[path_.length()] != '/') + url_path[path_.length()] != '/') { return false; + } return true; }
diff --git a/net/cookies/cookie_monster.cc b/net/cookies/cookie_monster.cc index 1d38146..bbec7b0 100644 --- a/net/cookies/cookie_monster.cc +++ b/net/cookies/cookie_monster.cc
@@ -1221,13 +1221,12 @@ FindCookiesForHostAndDomain(url, options, &cookies); std::set<CanonicalCookie*> matching_cookies; - for (std::vector<CanonicalCookie*>::const_iterator it = cookies.begin(); - it != cookies.end(); ++it) { - if ((*it)->Name() != cookie_name) + for (const auto& cookie : cookies) { + if (cookie->Name() != cookie_name) continue; - if (url.path().find((*it)->Path())) + if (!cookie->IsOnPath(url.path())) continue; - matching_cookies.insert(*it); + matching_cookies.insert(cookie); } for (CookieMap::iterator it = cookies_.begin(); it != cookies_.end();) {
diff --git a/net/cookies/cookie_monster_store_test.cc b/net/cookies/cookie_monster_store_test.cc index a3c1a94..3920c9be 100644 --- a/net/cookies/cookie_monster_store_test.cc +++ b/net/cookies/cookie_monster_store_test.cc
@@ -68,8 +68,6 @@ void MockPersistentCookieStore::UpdateCookieAccessTime( const CanonicalCookie& cookie) { - commands_.push_back( - CookieStoreCommand(CookieStoreCommand::UPDATE_ACCESS_TIME, cookie)); } void MockPersistentCookieStore::DeleteCookie(const CanonicalCookie& cookie) {
diff --git a/net/cookies/cookie_monster_store_test.h b/net/cookies/cookie_monster_store_test.h index 686bb07a..77fef31 100644 --- a/net/cookies/cookie_monster_store_test.h +++ b/net/cookies/cookie_monster_store_test.h
@@ -53,8 +53,10 @@ // Describes a call to one of the 3 functions of PersistentCookieStore. struct CookieStoreCommand { enum Type { + // UPDATE_ACCESS_TIME is not included in this list, because get cookie + // commands may or may not end updating the access time, unless they have + // the option set not to do so. ADD, - UPDATE_ACCESS_TIME, REMOVE, };
diff --git a/net/cookies/cookie_monster_unittest.cc b/net/cookies/cookie_monster_unittest.cc index a92f2be..88f5cbd 100644 --- a/net/cookies/cookie_monster_unittest.cc +++ b/net/cookies/cookie_monster_unittest.cc
@@ -1422,27 +1422,6 @@ EXPECT_EQ("A1", cookies[5].Value()); } -TEST_F(CookieMonsterTest, DeleteCookieByName) { - scoped_refptr<CookieMonster> cm(new CookieMonster(NULL, NULL)); - - EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A1; path=/")); - EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A2; path=/foo")); - EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A3; path=/bar")); - EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B1; path=/")); - EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B2; path=/foo")); - EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B3; path=/bar")); - - DeleteCookie(cm.get(), http_www_google_.AppendPath("foo/bar"), "A"); - - CookieList cookies = GetAllCookies(cm.get()); - size_t expected_size = 4; - EXPECT_EQ(expected_size, cookies.size()); - for (CookieList::iterator it = cookies.begin(); it != cookies.end(); ++it) { - EXPECT_NE("A1", it->Value()); - EXPECT_NE("A2", it->Value()); - } -} - // Tests importing from a persistent cookie store that contains duplicate // equivalent cookies. This situation should be handled by removing the // duplicate cookie (both from the in-memory cache, and from the backing store).
diff --git a/net/cookies/cookie_store_unittest.h b/net/cookies/cookie_store_unittest.h index 141cce5..7198f508 100644 --- a/net/cookies/cookie_store_unittest.h +++ b/net/cookies/cookie_store_unittest.h
@@ -1300,6 +1300,34 @@ ASSERT_TRUE(++it == cookies.end()); } +TYPED_TEST_P(CookieStoreTest, DeleteCookieAsync) { + scoped_refptr<CookieStore> cs(this->GetCookieStore()); + + EXPECT_TRUE( + this->SetCookie(cs.get(), this->http_www_google_.url(), "A=A1; path=/")); + EXPECT_TRUE(this->SetCookie(cs.get(), this->http_www_google_.url(), + "A=A2; path=/foo")); + EXPECT_TRUE(this->SetCookie(cs.get(), this->http_www_google_.url(), + "A=A3; path=/bar")); + EXPECT_TRUE( + this->SetCookie(cs.get(), this->http_www_google_.url(), "B=B1; path=/")); + EXPECT_TRUE(this->SetCookie(cs.get(), this->http_www_google_.url(), + "B=B2; path=/foo")); + EXPECT_TRUE(this->SetCookie(cs.get(), this->http_www_google_.url(), + "B=B3; path=/bar")); + + this->DeleteCookie(cs.get(), this->http_www_google_.AppendPath("foo/bar"), + "A"); + + CookieList cookies = this->GetAllCookies(cs.get()); + size_t expected_size = 4; + EXPECT_EQ(expected_size, cookies.size()); + for (const auto& cookie : cookies) { + EXPECT_NE("A1", cookie.Value()); + EXPECT_NE("A2", cookie.Value()); + } +} + TYPED_TEST_P(CookieStoreTest, DeleteCanonicalCookieAsync) { scoped_refptr<CookieStore> cs(this->GetCookieStore()); @@ -1394,6 +1422,7 @@ OverwritePersistentCookie, CookieOrdering, GetAllCookiesAsync, + DeleteCookieAsync, DeleteCanonicalCookieAsync, DeleteSessionCookie);
diff --git a/net/dns/dns_config_service_posix.cc b/net/dns/dns_config_service_posix.cc index ab84b22..aaa12b0 100644 --- a/net/dns/dns_config_service_posix.cc +++ b/net/dns/dns_config_service_posix.cc
@@ -18,6 +18,7 @@ #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "base/time/time.h" +#include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/dns/dns_hosts.h" #include "net/dns/dns_protocol.h" @@ -172,18 +173,18 @@ if (dns1_string.length() == 0 && dns2_string.length() == 0) return CONFIG_PARSE_POSIX_NO_NAMESERVERS; - IPAddressNumber dns1_number, dns2_number; - bool parsed1 = ParseIPLiteralToNumber(dns1_string, &dns1_number); - bool parsed2 = ParseIPLiteralToNumber(dns2_string, &dns2_number); + IPAddress dns1_address, dns2_address; + bool parsed1 = dns1_address.AssignFromIPLiteral(dns1_string); + bool parsed2 = dns2_address.AssignFromIPLiteral(dns2_string); if (!parsed1 && !parsed2) return CONFIG_PARSE_POSIX_BAD_ADDRESS; if (parsed1) { - IPEndPoint dns1(dns1_number, dns_protocol::kDefaultPort); + IPEndPoint dns1(dns1_address, dns_protocol::kDefaultPort); dns_config->nameservers.push_back(dns1); } if (parsed2) { - IPEndPoint dns2(dns2_number, dns_protocol::kDefaultPort); + IPEndPoint dns2(dns2_address, dns_protocol::kDefaultPort); dns_config->nameservers.push_back(dns2); } @@ -541,9 +542,8 @@ // If any name server is 0.0.0.0, assume the configuration is invalid. // TODO(szym): Measure how often this happens. http://crbug.com/125599 - const IPAddressNumber kEmptyAddress(kIPv4AddressSize); for (unsigned i = 0; i < dns_config->nameservers.size(); ++i) { - if (dns_config->nameservers[i].address().bytes() == kEmptyAddress) + if (dns_config->nameservers[i].address().IsZero()) return CONFIG_PARSE_POSIX_NULL_ADDRESS; } return CONFIG_PARSE_POSIX_OK;
diff --git a/net/dns/dns_config_service_posix_unittest.cc b/net/dns/dns_config_service_posix_unittest.cc index 04384d4..38c5cb6 100644 --- a/net/dns/dns_config_service_posix_unittest.cc +++ b/net/dns/dns_config_service_posix_unittest.cc
@@ -9,6 +9,7 @@ #include "base/sys_byteorder.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" +#include "net/base/ip_address.h" #include "net/dns/dns_config_service_posix.h" #include "net/dns/dns_protocol.h" @@ -117,8 +118,8 @@ config->nameservers.clear(); for (unsigned i = 0; i < arraysize(kNameserversIPv4) && i < MAXNS; ++i) { - IPAddressNumber ip; - ParseIPLiteralToNumber(kNameserversIPv4[i], &ip); + IPAddress ip; + EXPECT_TRUE(ip.AssignFromIPLiteral(kNameserversIPv4[i])); config->nameservers.push_back(IPEndPoint(ip, NS_DEFAULTPORT + i)); } @@ -126,8 +127,8 @@ for (unsigned i = 0; i < arraysize(kNameserversIPv6) && i < MAXNS; ++i) { if (!kNameserversIPv6[i]) continue; - IPAddressNumber ip; - ParseIPLiteralToNumber(kNameserversIPv6[i], &ip); + IPAddress ip; + EXPECT_TRUE(ip.AssignFromIPLiteral(kNameserversIPv6[i])); config->nameservers[i] = IPEndPoint(ip, NS_DEFAULTPORT - i); } #endif @@ -211,11 +212,11 @@ } void MockDNSConfig(const char* dns_server) { - IPAddressNumber dns_number; - ASSERT_TRUE(ParseIPLiteralToNumber(dns_server, &dns_number)); + IPAddress dns_address; + ASSERT_TRUE(dns_address.AssignFromIPLiteral(dns_server)); test_config_.nameservers.clear(); test_config_.nameservers.push_back( - IPEndPoint(dns_number, dns_protocol::kDefaultPort)); + IPEndPoint(dns_address, dns_protocol::kDefaultPort)); service_->SetDnsConfigForTesting(&test_config_); }
diff --git a/net/dns/dns_config_service_unittest.cc b/net/dns/dns_config_service_unittest.cc index aa4b3c8..16d1c896 100644 --- a/net/dns/dns_config_service_unittest.cc +++ b/net/dns/dns_config_service_unittest.cc
@@ -42,9 +42,8 @@ if (server_str.empty()) continue; - IPAddressNumber address; - bool parsed = ParseIPLiteralToNumber(server_str, &address); - EXPECT_TRUE(parsed); + IPAddress address; + EXPECT_TRUE(address.AssignFromIPLiteral(server_str)); servers.push_back(IPEndPoint(address, dns_protocol::kDefaultPort)); } @@ -157,9 +156,8 @@ // Generate a config using the given seed.. DnsConfig MakeConfig(unsigned seed) { DnsConfig config; - IPAddressNumber ip; - CHECK(ParseIPLiteralToNumber("1.2.3.4", &ip)); - config.nameservers.push_back(IPEndPoint(ip, seed & 0xFFFF)); + config.nameservers.push_back( + IPEndPoint(IPAddress(1, 2, 3, 4), seed & 0xFFFF)); EXPECT_TRUE(config.IsValid()); return config; }
diff --git a/net/dns/dns_config_service_win.cc b/net/dns/dns_config_service_win.cc index 0f085f4..35358f41 100644 --- a/net/dns/dns_config_service_win.cc +++ b/net/dns/dns_config_service_win.cc
@@ -26,6 +26,7 @@ #include "base/win/registry.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" +#include "net/base/ip_address.h" #include "net/base/network_change_notifier.h" #include "net/dns/dns_hosts.h" #include "net/dns/dns_protocol.h" @@ -220,13 +221,8 @@ // Default address of "localhost" and local computer name can be overridden // by the HOSTS file, but if it's not there, then we need to fill it in. HostsParseWinResult AddLocalhostEntries(DnsHosts* hosts) { - const unsigned char kIPv4Localhost[] = { 127, 0, 0, 1 }; - const unsigned char kIPv6Localhost[] = { 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 1 }; - IPAddressNumber loopback_ipv4(kIPv4Localhost, - kIPv4Localhost + arraysize(kIPv4Localhost)); - IPAddressNumber loopback_ipv6(kIPv6Localhost, - kIPv6Localhost + arraysize(kIPv6Localhost)); + IPAddress loopback_ipv4 = IPAddress::IPv4Localhost(); + IPAddress loopback_ipv6 = IPAddress::IPv6Localhost(); // This does not override any pre-existing entries from the HOSTS file. hosts->insert(std::make_pair(DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4), @@ -280,12 +276,10 @@ } if (!have_ipv4 && (ipe.GetFamily() == ADDRESS_FAMILY_IPV4)) { have_ipv4 = true; - (*hosts)[DnsHostsKey(localname, ADDRESS_FAMILY_IPV4)] = - ipe.address().bytes(); + (*hosts)[DnsHostsKey(localname, ADDRESS_FAMILY_IPV4)] = ipe.address(); } else if (!have_ipv6 && (ipe.GetFamily() == ADDRESS_FAMILY_IPV6)) { have_ipv6 = true; - (*hosts)[DnsHostsKey(localname, ADDRESS_FAMILY_IPV6)] = - ipe.address().bytes(); + (*hosts)[DnsHostsKey(localname, ADDRESS_FAMILY_IPV6)] = ipe.address(); } } } @@ -332,15 +326,12 @@ // Returns true iff |address| is DNS address from IPv6 stateless discovery, // i.e., matches fec0:0:0:ffff::{1,2,3}. // http://tools.ietf.org/html/draft-ietf-ipngwg-dns-discovery -bool IsStatelessDiscoveryAddress(const IPAddressNumber& address) { - if (address.size() != kIPv6AddressSize) +bool IsStatelessDiscoveryAddress(const IPAddress& address) { + if (!address.IsIPv6()) return false; - const uint8_t kPrefix[] = { - 0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }; - return std::equal(kPrefix, kPrefix + arraysize(kPrefix), - address.begin()) && (address.back() < 4); + const uint8_t kPrefix[] = {0xfe, 0xc0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + return IPAddressStartsWith(address, kPrefix) && (address.bytes().back() < 4); } // Returns the path to the HOSTS file. @@ -514,7 +505,7 @@ IPEndPoint ipe; if (ipe.FromSockAddr(address->Address.lpSockaddr, address->Address.iSockaddrLength)) { - if (IsStatelessDiscoveryAddress(ipe.address().bytes())) + if (IsStatelessDiscoveryAddress(ipe.address())) continue; // Override unset port. if (!ipe.port())
diff --git a/net/dns/dns_config_service_win_unittest.cc b/net/dns/dns_config_service_win_unittest.cc index 4568db4..87be751 100644 --- a/net/dns/dns_config_service_win_unittest.cc +++ b/net/dns/dns_config_service_win_unittest.cc
@@ -6,6 +6,7 @@ #include "base/logging.h" #include "base/win/windows_version.h" +#include "net/base/ip_address.h" #include "net/dns/dns_protocol.h" #include "testing/gtest/include/gtest/gtest.h" @@ -96,8 +97,8 @@ // Note that |address| is moving backwards. address = address->Next = address - 1; } - IPAddressNumber ip; - CHECK(ParseIPLiteralToNumber(info.dns_server_addresses[j], &ip)); + IPAddress ip; + CHECK(ip.AssignFromIPLiteral(info.dns_server_addresses[j])); IPEndPoint ipe = IPEndPoint(ip, info.ports[j]); address->Address.lpSockaddr = reinterpret_cast<LPSOCKADDR>(storage + num_addresses); @@ -173,8 +174,8 @@ // Default settings for the rest. std::vector<IPEndPoint> expected_nameservers; for (size_t j = 0; !t.expected_nameservers[j].empty(); ++j) { - IPAddressNumber ip; - ASSERT_TRUE(ParseIPLiteralToNumber(t.expected_nameservers[j], &ip)); + IPAddress ip; + ASSERT_TRUE(ip.AssignFromIPLiteral(t.expected_nameservers[j])); uint16_t port = t.expected_ports[j]; if (!port) port = dns_protocol::kDefaultPort;
diff --git a/net/dns/dns_hosts.cc b/net/dns/dns_hosts.cc index a4f293f6..098c617 100644 --- a/net/dns/dns_hosts.cc +++ b/net/dns/dns_hosts.cc
@@ -134,7 +134,7 @@ CHECK(dns_hosts); StringPiece ip_text; - IPAddressNumber ip; + IPAddress ip; AddressFamily family = ADDRESS_FAMILY_IPV4; HostsParser parser(contents, comma_mode); while (parser.Advance()) { @@ -144,11 +144,11 @@ // the same IP address (usually 127.0.0.1). Don't bother parsing the IP // again if it's the same as the one above it. if (new_ip_text != ip_text) { - IPAddressNumber new_ip; - if (ParseIPLiteralToNumber(parser.token().as_string(), &new_ip)) { + IPAddress new_ip; + if (new_ip.AssignFromIPLiteral(parser.token())) { ip_text = new_ip_text; - ip.swap(new_ip); - family = (ip.size() == 4) ? ADDRESS_FAMILY_IPV4 : ADDRESS_FAMILY_IPV6; + ip = new_ip; + family = (ip.IsIPv4()) ? ADDRESS_FAMILY_IPV4 : ADDRESS_FAMILY_IPV6; } else { parser.SkipRestOfLine(); } @@ -156,7 +156,7 @@ } else { DnsHostsKey key(parser.token().as_string(), family); key.first = base::ToLowerASCII(key.first); - IPAddressNumber* mapped_ip = &(*dns_hosts)[key]; + IPAddress* mapped_ip = &(*dns_hosts)[key]; if (mapped_ip->empty()) *mapped_ip = ip; // else ignore this entry (first hit counts)
diff --git a/net/dns/dns_hosts.h b/net/dns/dns_hosts.h index 0b9edc2..2ce7c52 100644 --- a/net/dns/dns_hosts.h +++ b/net/dns/dns_hosts.h
@@ -15,7 +15,7 @@ #include "base/containers/hash_tables.h" #include "base/files/file_path.h" #include "net/base/address_family.h" -#include "net/base/ip_address_number.h" +#include "net/base/ip_address.h" #include "net/base/net_export.h" namespace net { @@ -57,11 +57,11 @@ // 10.0.0.1 localhost // The expected resolution of localhost is 127.0.0.1. #if !defined(OS_ANDROID) -typedef base::hash_map<DnsHostsKey, IPAddressNumber> DnsHosts; +typedef base::hash_map<DnsHostsKey, IPAddress> DnsHosts; #else // Android's hash_map doesn't support ==, so fall back to map. (Chromium on // Android doesn't use the built-in DNS resolver anyway, so it's irrelevant.) -typedef std::map<DnsHostsKey, IPAddressNumber> DnsHosts; +typedef std::map<DnsHostsKey, IPAddress> DnsHosts; #endif // Parses |contents| (as read from /etc/hosts or equivalent) and stores results
diff --git a/net/dns/dns_hosts_unittest.cc b/net/dns/dns_hosts_unittest.cc index 1bce190..9e52f0e2 100644 --- a/net/dns/dns_hosts_unittest.cc +++ b/net/dns/dns_hosts_unittest.cc
@@ -4,6 +4,7 @@ #include "net/dns/dns_hosts.h" +#include "net/base/ip_address.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -21,9 +22,9 @@ DnsHosts* expected_hosts_out) { for (size_t i = 0; i < num_entries; ++i) { DnsHostsKey key(entries[i].host, entries[i].family); - IPAddressNumber& ip_ref = (*expected_hosts_out)[key]; + IPAddress& ip_ref = (*expected_hosts_out)[key]; ASSERT_TRUE(ip_ref.empty()); - ASSERT_TRUE(ParseIPLiteralToNumber(entries[i].ip, &ip_ref)); + ASSERT_TRUE(ip_ref.AssignFromIPLiteral(entries[i].ip)); ASSERT_EQ(ip_ref.size(), (entries[i].family == ADDRESS_FAMILY_IPV4) ? 4u : 16u); }
diff --git a/net/dns/dns_session_unittest.cc b/net/dns/dns_session_unittest.cc index b2a09f1..1c65c67 100644 --- a/net/dns/dns_session_unittest.cc +++ b/net/dns/dns_session_unittest.cc
@@ -11,6 +11,7 @@ #include "base/memory/scoped_ptr.h" #include "base/rand_util.h" #include "base/stl_util.h" +#include "net/base/ip_address.h" #include "net/dns/dns_protocol.h" #include "net/dns/dns_socket_pool.h" #include "net/log/net_log.h" @@ -113,12 +114,9 @@ void DnsSessionTest::Initialize(unsigned num_servers) { CHECK(num_servers < 256u); config_.nameservers.clear(); - IPAddressNumber dns_ip; - bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip); - EXPECT_TRUE(rv); for (unsigned char i = 0; i < num_servers; ++i) { - dns_ip[3] = i; - IPEndPoint dns_endpoint(dns_ip, dns_protocol::kDefaultPort); + IPEndPoint dns_endpoint(IPAddress(192, 168, 1, i), + dns_protocol::kDefaultPort); config_.nameservers.push_back(dns_endpoint); }
diff --git a/net/dns/dns_transaction.cc b/net/dns/dns_transaction.cc index 8eebb8c6..f726bd2 100644 --- a/net/dns/dns_transaction.cc +++ b/net/dns/dns_transaction.cc
@@ -28,6 +28,7 @@ #include "base/values.h" #include "net/base/completion_callback.h" #include "net/base/io_buffer.h" +#include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/dns/dns_protocol.h" @@ -57,8 +58,8 @@ } bool IsIPLiteral(const std::string& hostname) { - IPAddressNumber ip; - return ParseIPLiteralToNumber(hostname, &ip); + IPAddress ip; + return ip.AssignFromIPLiteral(hostname); } scoped_ptr<base::Value> NetLogStartCallback(
diff --git a/net/dns/dns_transaction_unittest.cc b/net/dns/dns_transaction_unittest.cc index 7b906ba..2f8e6755 100644 --- a/net/dns/dns_transaction_unittest.cc +++ b/net/dns/dns_transaction_unittest.cc
@@ -14,6 +14,7 @@ #include "base/rand_util.h" #include "base/sys_byteorder.h" #include "base/test/test_timeouts.h" +#include "net/base/ip_address.h" #include "net/dns/dns_protocol.h" #include "net/dns/dns_query.h" #include "net/dns/dns_response.h" @@ -333,15 +334,9 @@ void ConfigureNumServers(unsigned num_servers) { CHECK_LE(num_servers, 255u); config_.nameservers.clear(); - IPAddressNumber dns_ip; - { - bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip); - EXPECT_TRUE(rv); - } for (unsigned i = 0; i < num_servers; ++i) { - dns_ip[3] = i; - config_.nameservers.push_back(IPEndPoint(dns_ip, - dns_protocol::kDefaultPort)); + config_.nameservers.push_back( + IPEndPoint(IPAddress(192, 168, 1, i), dns_protocol::kDefaultPort)); } }
diff --git a/net/dns/host_resolver_impl.cc b/net/dns/host_resolver_impl.cc index af91b09..bc1617c 100644 --- a/net/dns/host_resolver_impl.cc +++ b/net/dns/host_resolver_impl.cc
@@ -39,6 +39,7 @@ #include "net/base/address_family.h" #include "net/base/address_list.h" #include "net/base/host_port_pair.h" +#include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/url_util.h" @@ -167,7 +168,7 @@ // possible to navigate to http://127.0.53.53/ directly. // // For more details: https://www.icann.org/news/announcement-2-2014-08-01-en -const unsigned char kIcanNameCollisionIp[] = {127, 0, 53, 53}; +const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53}; void UmaAsyncDnsResolveStatus(DnsResolveStatus result) { UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus", @@ -195,8 +196,7 @@ } // Attempts to connect a UDP socket to |dest|:53. -bool IsGloballyReachable(const IPAddressNumber& dest, - const BoundNetLog& net_log) { +bool IsGloballyReachable(const IPAddress& dest, const BoundNetLog& net_log) { // TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed. tracked_objects::ScopedTracker tracking_profile_1( FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable")); @@ -215,16 +215,17 @@ if (rv != OK) return false; DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily()); - const IPAddressNumber& address = endpoint.address().bytes(); - bool is_link_local = (address[0] == 0xFE) && ((address[1] & 0xC0) == 0x80); + const IPAddress& address = endpoint.address(); + + bool is_link_local = + (address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80); if (is_link_local) return false; + const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0}; - bool is_teredo = std::equal(kTeredoPrefix, - kTeredoPrefix + arraysize(kTeredoPrefix), - address.begin()); - if (is_teredo) + if (IPAddressStartsWith(address, kTeredoPrefix)) return false; + return true; } @@ -299,10 +300,10 @@ // Returns true if |addresses| contains only IPv4 loopback addresses. bool IsAllIPv4Loopback(const AddressList& addresses) { for (unsigned i = 0; i < addresses.size(); ++i) { - const IPAddressNumber& address = addresses[i].address().bytes(); + const IPAddress& address = addresses[i].address(); switch (addresses[i].GetFamily()) { case ADDRESS_FAMILY_IPV4: - if (address[0] != 127) + if (address.bytes()[0] != 127) return false; break; case ADDRESS_FAMILY_IPV6: @@ -493,25 +494,15 @@ bool ResolveLocalHostname(base::StringPiece host, uint16_t port, AddressList* address_list) { - static const unsigned char kLocalhostIPv4[] = {127, 0, 0, 1}; - static const unsigned char kLocalhostIPv6[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; - address_list->clear(); bool is_local6; if (!IsLocalHostname(host, &is_local6)) return false; - address_list->push_back( - IPEndPoint(IPAddressNumber(kLocalhostIPv6, - kLocalhostIPv6 + arraysize(kLocalhostIPv6)), - port)); + address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port)); if (!is_local6) { - address_list->push_back( - IPEndPoint(IPAddressNumber(kLocalhostIPv4, - kLocalhostIPv4 + arraysize(kLocalhostIPv4)), - port)); + address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port)); } return true; @@ -738,9 +729,8 @@ // Fail the resolution if the result contains 127.0.53.53. See the comment // block of kIcanNameCollisionIp for details on why. for (const auto& it : results) { - const IPAddressNumber& cur = it.address().bytes(); - if (cur.size() == arraysize(kIcanNameCollisionIp) && - 0 == memcmp(&cur.front(), kIcanNameCollisionIp, cur.size())) { + const IPAddress& cur = it.address(); + if (cur.IsIPv4() && IPAddressStartsWith(cur, kIcanNameCollisionIp)) { error = ERR_ICANN_NAME_COLLISION; break; } @@ -1939,16 +1929,16 @@ LogStartRequest(source_net_log, info); - IPAddressNumber ip_number; - IPAddressNumber* ip_number_ptr = nullptr; - if (ParseIPLiteralToNumber(info.hostname(), &ip_number)) - ip_number_ptr = &ip_number; + IPAddress ip_address; + IPAddress* ip_address_ptr = nullptr; + if (ip_address.AssignFromIPLiteral(info.hostname())) + ip_address_ptr = &ip_address; // Build a key that identifies the request in the cache and in the // outstanding jobs map. - Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log); + Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log); - int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log); + int rv = ResolveHelper(key, info, ip_address_ptr, addresses, source_net_log); if (rv != ERR_DNS_CACHE_MISS) { LogFinishRequest(source_net_log, info, rv); RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta()); @@ -1994,7 +1984,7 @@ int HostResolverImpl::ResolveHelper(const Key& key, const RequestInfo& info, - const IPAddressNumber* ip_number, + const IPAddress* ip_address, AddressList* addresses, const BoundNetLog& source_net_log) { // The result of |getaddrinfo| for empty hosts is inconsistent across systems. @@ -2004,7 +1994,7 @@ return ERR_NAME_NOT_RESOLVED; int net_error = ERR_UNEXPECTED; - if (ResolveAsIP(key, info, ip_number, &net_error, addresses)) + if (ResolveAsIP(key, info, ip_address, &net_error, addresses)) return net_error; if (ServeFromCache(key, info, &net_error, addresses)) { source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT); @@ -2032,14 +2022,14 @@ // Update the net log and notify registered observers. LogStartRequest(source_net_log, info); - IPAddressNumber ip_number; - IPAddressNumber* ip_number_ptr = nullptr; - if (ParseIPLiteralToNumber(info.hostname(), &ip_number)) - ip_number_ptr = &ip_number; + IPAddress ip_address; + IPAddress* ip_address_ptr = nullptr; + if (ip_address.AssignFromIPLiteral(info.hostname())) + ip_address_ptr = &ip_address; - Key key = GetEffectiveKeyForRequest(info, ip_number_ptr, source_net_log); + Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log); - int rv = ResolveHelper(key, info, ip_number_ptr, addresses, source_net_log); + int rv = ResolveHelper(key, info, ip_address_ptr, addresses, source_net_log); LogFinishRequest(source_net_log, info, rv); return rv; } @@ -2084,27 +2074,22 @@ bool HostResolverImpl::ResolveAsIP(const Key& key, const RequestInfo& info, - const IPAddressNumber* ip_number, + const IPAddress* ip_address, int* net_error, AddressList* addresses) { DCHECK(addresses); DCHECK(net_error); - if (ip_number == nullptr) + if (ip_address == nullptr) return false; - DCHECK_EQ(key.host_resolver_flags & - ~(HOST_RESOLVER_CANONNAME | HOST_RESOLVER_LOOPBACK_ONLY | - HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6), - 0) << " Unhandled flag"; - *net_error = OK; - AddressFamily family = GetAddressFamily(*ip_number); + AddressFamily family = GetAddressFamily(*ip_address); if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED && key.address_family != family) { // Don't return IPv6 addresses for IPv4 queries, and vice versa. *net_error = ERR_NAME_NOT_RESOLVED; } else { - *addresses = AddressList::CreateFromIPAddress(*ip_number, info.port()); + *addresses = AddressList::CreateFromIPAddress(*ip_address, info.port()); if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME) addresses->SetDefaultCanonicalName(); } @@ -2235,7 +2220,7 @@ HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest( const RequestInfo& info, - const IPAddressNumber* ip_number, + const IPAddress* ip_address, const BoundNetLog& net_log) { HostResolverFlags effective_flags = info.host_resolver_flags() | additional_resolver_flags_; @@ -2249,7 +2234,7 @@ // that this query is UNSPECIFIED (see info.address_family() // check above) so the code requesting the resolution should be amenable // to receiving a IPv6 resolution. - ip_number == nullptr) { + ip_address == nullptr) { if (!IsIPv6Reachable(net_log)) { effective_address_family = ADDRESS_FAMILY_IPV4; effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; @@ -2264,9 +2249,8 @@ base::TimeTicks now = base::TimeTicks::Now(); bool cached = true; if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) { - IPAddressNumber address(kIPv6ProbeAddress, - kIPv6ProbeAddress + arraysize(kIPv6ProbeAddress)); - last_ipv6_probe_result_ = IsGloballyReachable(address, net_log); + last_ipv6_probe_result_ = + IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log); last_ipv6_probe_time_ = now; cached = false; }
diff --git a/net/dns/host_resolver_impl.h b/net/dns/host_resolver_impl.h index aa76363..fc3835d 100644 --- a/net/dns/host_resolver_impl.h +++ b/net/dns/host_resolver_impl.h
@@ -16,7 +16,6 @@ #include "base/strings/string_piece.h" #include "base/threading/non_thread_safe.h" #include "base/time/time.h" -#include "net/base/ip_address_number.h" #include "net/base/net_export.h" #include "net/base/network_change_notifier.h" #include "net/dns/host_cache.h" @@ -28,6 +27,7 @@ class AddressList; class BoundNetLog; class DnsClient; +class IPAddress; class NetLog; // For each hostname that is requested, HostResolver creates a @@ -169,7 +169,7 @@ // HOSTS and is not localhost. int ResolveHelper(const Key& key, const RequestInfo& info, - const IPAddressNumber* ip_address, + const IPAddress* ip_address, AddressList* addresses, const BoundNetLog& request_net_log); @@ -177,7 +177,7 @@ // succeeds, returns false otherwise. bool ResolveAsIP(const Key& key, const RequestInfo& info, - const IPAddressNumber* ip_address, + const IPAddress* ip_address, int* net_error, AddressList* addresses); @@ -208,7 +208,7 @@ // "effective" address family by inheriting the resolver's default address // family when the request leaves it unspecified. Key GetEffectiveKeyForRequest(const RequestInfo& info, - const IPAddressNumber* ip_number, + const IPAddress* ip_address, const BoundNetLog& net_log); // Probes IPv6 support and returns true if IPv6 support is enabled.
diff --git a/net/dns/host_resolver_impl_unittest.cc b/net/dns/host_resolver_impl_unittest.cc index 3d30dbe..4fc4474 100644 --- a/net/dns/host_resolver_impl_unittest.cc +++ b/net/dns/host_resolver_impl_unittest.cc
@@ -26,6 +26,7 @@ #include "base/thread_task_runner_handle.h" #include "base/time/time.h" #include "net/base/address_list.h" +#include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/dns/dns_client.h" #include "net/dns/dns_test_util.h" @@ -189,8 +190,8 @@ bool AddressListContains(const AddressList& list, const std::string& address, uint16_t port) { - IPAddressNumber ip; - bool rv = ParseIPLiteralToNumber(address, &ip); + IPAddress ip; + bool rv = ip.AssignFromIPLiteral(address); DCHECK(rv); return std::find(list.begin(), list.end(), @@ -446,9 +447,6 @@ } }; -const unsigned char kLocalhostIPv4[] = {127, 0, 0, 1}; -const unsigned char kLocalhostIPv6[] = - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; const uint16_t kLocalhostLookupPort = 80; bool HasEndpoint(const IPEndPoint& endpoint, const AddressList& addresses) { @@ -460,14 +458,8 @@ } void TestBothLoopbackIPs(const std::string& host) { - IPEndPoint localhost_ipv4( - IPAddressNumber(kLocalhostIPv4, - kLocalhostIPv4 + arraysize(kLocalhostIPv4)), - kLocalhostLookupPort); - IPEndPoint localhost_ipv6( - IPAddressNumber(kLocalhostIPv6, - kLocalhostIPv6 + arraysize(kLocalhostIPv6)), - kLocalhostLookupPort); + IPEndPoint localhost_ipv4(IPAddress::IPv4Localhost(), kLocalhostLookupPort); + IPEndPoint localhost_ipv6(IPAddress::IPv6Localhost(), kLocalhostLookupPort); AddressList addresses; EXPECT_TRUE(ResolveLocalHostname(host, kLocalhostLookupPort, &addresses)); @@ -477,10 +469,7 @@ } void TestIPv6LoopbackOnly(const std::string& host) { - IPEndPoint localhost_ipv6( - IPAddressNumber(kLocalhostIPv6, - kLocalhostIPv6 + arraysize(kLocalhostIPv6)), - kLocalhostLookupPort); + IPEndPoint localhost_ipv6(IPAddress::IPv6Localhost(), kLocalhostLookupPort); AddressList addresses; EXPECT_TRUE(ResolveLocalHostname(host, kLocalhostLookupPort, &addresses)); @@ -673,6 +662,22 @@ EXPECT_TRUE(req5->HasOneAddress("::1", 80)); } +TEST_F(HostResolverImplTest, ResolveIPLiteralWithHostResolverSystemOnly) { + const char kIpLiteral[] = "178.78.32.1"; + // Add a mapping to tell if the resolver proc was called (if it was called, + // then the result will be the remapped value. Otherwise it will be the IP + // literal). + proc_->AddRuleForAllFamilies(kIpLiteral, "183.45.32.1"); + + HostResolver::RequestInfo info_bypass(HostPortPair(kIpLiteral, 80)); + info_bypass.set_host_resolver_flags(HOST_RESOLVER_SYSTEM_ONLY); + + Request* req = CreateRequest(info_bypass, MEDIUM); + EXPECT_EQ(OK, req->Resolve()); + + EXPECT_TRUE(req->HasAddress(kIpLiteral, 80)); +} + TEST_F(HostResolverImplTest, EmptyListMeansNameNotResolved) { proc_->AddRuleForAllFamilies("just.testing", ""); proc_->SignalMultiple(1u); @@ -1447,10 +1452,7 @@ } DnsConfig CreateValidDnsConfig() { - IPAddressNumber dns_ip; - bool rv = ParseIPLiteralToNumber("192.168.1.0", &dns_ip); - EXPECT_TRUE(rv); - + IPAddress dns_ip(192, 168, 1, 0); DnsConfig config; config.nameservers.push_back(IPEndPoint(dns_ip, dns_protocol::kDefaultPort)); EXPECT_TRUE(config.IsValid()); @@ -1687,9 +1689,8 @@ EXPECT_EQ(ERR_IO_PENDING, req0->Resolve()); EXPECT_EQ(ERR_NAME_NOT_RESOLVED, req0->WaitForResult()); - IPAddressNumber local_ipv4, local_ipv6; - ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4)); - ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6)); + IPAddress local_ipv4 = IPAddress::IPv4Localhost(); + IPAddress local_ipv6 = IPAddress::IPv6Localhost(); DnsHosts hosts; hosts[DnsHostsKey("nx_ipv4", ADDRESS_FAMILY_IPV4)] = local_ipv4; @@ -1878,9 +1879,8 @@ // Configure DnsClient with dual-host HOSTS file. DnsConfig config_hosts = CreateValidDnsConfig(); DnsHosts hosts; - IPAddressNumber local_ipv4, local_ipv6; - ASSERT_TRUE(ParseIPLiteralToNumber("127.0.0.1", &local_ipv4)); - ASSERT_TRUE(ParseIPLiteralToNumber("::1", &local_ipv6)); + IPAddress local_ipv4 = IPAddress::IPv4Localhost(); + IPAddress local_ipv6 = IPAddress::IPv6Localhost(); if (saw_ipv4) hosts[DnsHostsKey("localhost", ADDRESS_FAMILY_IPV4)] = local_ipv4; if (saw_ipv6)
diff --git a/net/dns/host_resolver_mojo_unittest.cc b/net/dns/host_resolver_mojo_unittest.cc index c0d05a7..a210d78 100644 --- a/net/dns/host_resolver_mojo_unittest.cc +++ b/net/dns/host_resolver_mojo_unittest.cc
@@ -9,6 +9,7 @@ #include "mojo/public/cpp/bindings/binding.h" #include "net/base/address_list.h" +#include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/base/request_priority.h" #include "net/base/test_completion_callback.h" @@ -174,11 +175,10 @@ TEST_F(HostResolverMojoTest, Basic) { AddressList address_list; - IPAddressNumber address_number; - ASSERT_TRUE(ParseIPLiteralToNumber("1.2.3.4", &address_number)); - address_list.push_back(IPEndPoint(address_number, 12345)); + IPAddress address(1, 2, 3, 4); + address_list.push_back(IPEndPoint(address, 12345)); address_list.push_back( - IPEndPoint(ConvertIPv4NumberToIPv6Number(address_number), 12345)); + IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 12345)); mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); HostResolver::RequestInfo request_info( HostPortPair::FromString("example.com:12345")); @@ -198,11 +198,10 @@ TEST_F(HostResolverMojoTest, ResolveCachedResult) { AddressList address_list; - IPAddressNumber address_number; - ASSERT_TRUE(ParseIPLiteralToNumber("1.2.3.4", &address_number)); - address_list.push_back(IPEndPoint(address_number, 12345)); + IPAddress address(1, 2, 3, 4); + address_list.push_back(IPEndPoint(address, 12345)); address_list.push_back( - IPEndPoint(ConvertIPv4NumberToIPv6Number(address_number), 12345)); + IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 12345)); mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); HostResolver::RequestInfo request_info( HostPortPair::FromString("example.com:12345")); @@ -215,9 +214,9 @@ EXPECT_EQ(OK, Resolve(request_info, &result)); ASSERT_EQ(2u, result.size()); address_list.clear(); - address_list.push_back(IPEndPoint(address_number, 6789)); + address_list.push_back(IPEndPoint(address, 6789)); address_list.push_back( - IPEndPoint(ConvertIPv4NumberToIPv6Number(address_number), 6789)); + IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 6789)); EXPECT_EQ(address_list[0], result[0]); EXPECT_EQ(address_list[1], result[1]); EXPECT_EQ(1u, mock_resolver_->requests().size()); @@ -234,9 +233,8 @@ TEST_F(HostResolverMojoTest, Multiple) { AddressList address_list; - IPAddressNumber address_number; - ASSERT_TRUE(ParseIPLiteralToNumber("1.2.3.4", &address_number)); - address_list.push_back(IPEndPoint(address_number, 12345)); + IPAddress address(1, 2, 3, 4); + address_list.push_back(IPEndPoint(address, 12345)); mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); mock_resolver_->AddAction( HostResolverAction::ReturnError(ERR_NAME_NOT_RESOLVED)); @@ -359,11 +357,10 @@ TEST_F(HostResolverMojoTest, ResolveFromCache_Hit) { AddressList address_list; - IPAddressNumber address_number; - ASSERT_TRUE(ParseIPLiteralToNumber("1.2.3.4", &address_number)); - address_list.push_back(IPEndPoint(address_number, 12345)); + IPAddress address(1, 2, 3, 4); + address_list.push_back(IPEndPoint(address, 12345)); address_list.push_back( - IPEndPoint(ConvertIPv4NumberToIPv6Number(address_number), 12345)); + IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 12345)); mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); HostResolver::RequestInfo request_info( HostPortPair::FromString("example.com:12345")); @@ -382,11 +379,10 @@ TEST_F(HostResolverMojoTest, ResolveFromCache_CacheNotAllowed) { AddressList address_list; - IPAddressNumber address_number; - ASSERT_TRUE(ParseIPLiteralToNumber("1.2.3.4", &address_number)); - address_list.push_back(IPEndPoint(address_number, 12345)); + IPAddress address(1, 2, 3, 4); + address_list.push_back(IPEndPoint(address, 12345)); address_list.push_back( - IPEndPoint(ConvertIPv4NumberToIPv6Number(address_number), 12345)); + IPEndPoint(ConvertIPv4ToIPv4MappedIPv6(address), 12345)); mock_resolver_->AddAction(HostResolverAction::ReturnResult(address_list)); HostResolver::RequestInfo request_info( HostPortPair::FromString("example.com:12345"));
diff --git a/net/dns/mdns_client.cc b/net/dns/mdns_client.cc index 109a836..64e0d75 100644 --- a/net/dns/mdns_client.cc +++ b/net/dns/mdns_client.cc
@@ -4,6 +4,7 @@ #include "net/dns/mdns_client.h" +#include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/base/network_interfaces.h" #include "net/dns/dns_protocol.h" @@ -17,9 +18,8 @@ const char kMDnsMulticastGroupIPv6[] = "FF02::FB"; IPEndPoint GetMDnsIPEndPoint(const char* address) { - IPAddressNumber multicast_group_number; - bool success = ParseIPLiteralToNumber(address, - &multicast_group_number); + IPAddress multicast_group_number; + bool success = multicast_group_number.AssignFromIPLiteral(address); DCHECK(success); return IPEndPoint(multicast_group_number, dns_protocol::kDefaultPortMulticast); @@ -28,7 +28,7 @@ int Bind(const IPEndPoint& multicast_addr, uint32_t interface_index, DatagramServerSocket* socket) { - IPAddressNumber address_any(multicast_addr.address().size()); + IPAddress address_any(std::vector<uint8_t>(multicast_addr.address().size())); IPEndPoint bind_endpoint(address_any, multicast_addr.port()); socket->AllowAddressReuse();
diff --git a/net/dns/mdns_client_unittest.cc b/net/dns/mdns_client_unittest.cc index ae1a8d91..b8f38cf 100644 --- a/net/dns/mdns_client_unittest.cc +++ b/net/dns/mdns_client_unittest.cc
@@ -15,6 +15,7 @@ #include "base/time/clock.h" #include "base/time/default_clock.h" #include "base/timer/mock_timer.h" +#include "net/base/ip_address.h" #include "net/base/rand_callback.h" #include "net/base/test_completion_callback.h" #include "net/dns/mdns_client_impl.h" @@ -930,13 +931,13 @@ ACTION_P(SaveIPAddress, ip_container) { ::testing::StaticAssertTypeEq<const RecordParsed*, arg1_type>(); - ::testing::StaticAssertTypeEq<IPAddressNumber*, ip_container_type>(); + ::testing::StaticAssertTypeEq<IPAddress*, ip_container_type>(); *ip_container = arg1->template rdata<ARecordRdata>()->address(); } TEST_F(MDnsTest, DoubleRecordDisagreeing) { - IPAddressNumber address; + IPAddress address; StrictMock<MockListenerDelegate> delegate_privet; scoped_ptr<MDnsListener> listener_privet = test_client_->CreateListener( @@ -951,7 +952,7 @@ SimulatePacketReceive(kCorruptedPacketDoubleRecord, sizeof(kCorruptedPacketDoubleRecord)); - EXPECT_EQ("2.3.4.5", IPAddressToString(address)); + EXPECT_EQ("2.3.4.5", address.ToString()); } TEST_F(MDnsTest, NsecWithListener) {
diff --git a/net/dns/mock_host_resolver.cc b/net/dns/mock_host_resolver.cc index b97c51b..b734cd3 100644 --- a/net/dns/mock_host_resolver.cc +++ b/net/dns/mock_host_resolver.cc
@@ -17,6 +17,7 @@ #include "base/strings/string_util.h" #include "base/thread_task_runner_handle.h" #include "base/threading/platform_thread.h" +#include "net/base/ip_address.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/test_completion_callback.h" @@ -44,12 +45,12 @@ addrlist->set_canonical_name(canonical_name); for (const base::StringPiece& address : base::SplitStringPiece( host_list, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { - IPAddressNumber ip_number; - if (!ParseIPLiteralToNumber(address, &ip_number)) { + IPAddress ip_address; + if (!ip_address.AssignFromIPLiteral(address)) { LOG(WARNING) << "Not a supported IP literal: " << address.as_string(); return ERR_UNEXPECTED; } - addrlist->push_back(IPEndPoint(ip_number, 0)); + addrlist->push_back(IPEndPoint(ip_address, 0)); } return OK; } @@ -154,15 +155,15 @@ int MockHostResolverBase::ResolveFromIPLiteralOrCache(const RequestInfo& info, AddressList* addresses) { - IPAddressNumber ip; - if (ParseIPLiteralToNumber(info.hostname(), &ip)) { + IPAddress ip_address; + if (ip_address.AssignFromIPLiteral(info.hostname())) { // This matches the behavior HostResolverImpl. if (info.address_family() != ADDRESS_FAMILY_UNSPECIFIED && - info.address_family() != GetAddressFamily(ip)) { + info.address_family() != GetAddressFamily(ip_address)) { return ERR_NAME_NOT_RESOLVED; } - *addresses = AddressList::CreateFromIPAddress(ip, info.port()); + *addresses = AddressList::CreateFromIPAddress(ip_address, info.port()); if (info.host_resolver_flags() & HOST_RESOLVER_CANONNAME) addresses->SetDefaultCanonicalName(); return OK; @@ -284,8 +285,8 @@ const std::string& canonical_name) { // Literals are always resolved to themselves by HostResolverImpl, // consequently we do not support remapping them. - IPAddressNumber ip_number; - DCHECK(!ParseIPLiteralToNumber(host_pattern, &ip_number)); + IPAddress ip_address; + DCHECK(!ip_address.AssignFromIPLiteral(host_pattern)); HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY | HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; if (!canonical_name.empty())
diff --git a/net/dns/record_rdata.cc b/net/dns/record_rdata.cc index 2213473..be9d387f 100644 --- a/net/dns/record_rdata.cc +++ b/net/dns/record_rdata.cc
@@ -65,16 +65,12 @@ scoped_ptr<ARecordRdata> ARecordRdata::Create( const base::StringPiece& data, const DnsRecordParser& parser) { - if (data.size() != kIPv4AddressSize) + if (data.size() != IPAddress::kIPv4AddressSize) return scoped_ptr<ARecordRdata>(); scoped_ptr<ARecordRdata> rdata(new ARecordRdata); - - rdata->address_.resize(kIPv4AddressSize); - for (unsigned i = 0; i < kIPv4AddressSize; ++i) { - rdata->address_[i] = data[i]; - } - + rdata->address_ = + IPAddress(reinterpret_cast<const uint8_t*>(data.data()), data.length()); return rdata; } @@ -98,16 +94,12 @@ scoped_ptr<AAAARecordRdata> AAAARecordRdata::Create( const base::StringPiece& data, const DnsRecordParser& parser) { - if (data.size() != kIPv6AddressSize) + if (data.size() != IPAddress::kIPv6AddressSize) return scoped_ptr<AAAARecordRdata>(); scoped_ptr<AAAARecordRdata> rdata(new AAAARecordRdata); - - rdata->address_.resize(kIPv6AddressSize); - for (unsigned i = 0; i < kIPv6AddressSize; ++i) { - rdata->address_[i] = data[i]; - } - + rdata->address_ = + IPAddress(reinterpret_cast<const uint8_t*>(data.data()), data.length()); return rdata; }
diff --git a/net/dns/record_rdata.h b/net/dns/record_rdata.h index 8184edd..fea1f6b 100644 --- a/net/dns/record_rdata.h +++ b/net/dns/record_rdata.h
@@ -14,7 +14,7 @@ #include "base/macros.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_piece.h" -#include "net/base/ip_address_number.h" +#include "net/base/ip_address.h" #include "net/base/net_export.h" #include "net/dns/dns_protocol.h" @@ -83,12 +83,12 @@ bool IsEqual(const RecordRdata* other) const override; uint16_t Type() const override; - const IPAddressNumber& address() const { return address_; } + const IPAddress& address() const { return address_; } private: ARecordRdata(); - IPAddressNumber address_; + IPAddress address_; DISALLOW_COPY_AND_ASSIGN(ARecordRdata); }; @@ -105,12 +105,12 @@ bool IsEqual(const RecordRdata* other) const override; uint16_t Type() const override; - const IPAddressNumber& address() const { return address_; } + const IPAddress& address() const { return address_; } private: AAAARecordRdata(); - IPAddressNumber address_; + IPAddress address_; DISALLOW_COPY_AND_ASSIGN(AAAARecordRdata); };
diff --git a/net/dns/record_rdata_unittest.cc b/net/dns/record_rdata_unittest.cc index d83f497c..5db22e6 100644 --- a/net/dns/record_rdata_unittest.cc +++ b/net/dns/record_rdata_unittest.cc
@@ -5,7 +5,6 @@ #include "net/dns/record_rdata.h" #include "base/memory/scoped_ptr.h" -#include "net/base/ip_address_number.h" #include "net/dns/dns_response.h" #include "testing/gtest/include/gtest/gtest.h" @@ -76,7 +75,7 @@ record_obj = ARecordRdata::Create(record_strpiece, parser); ASSERT_TRUE(record_obj != NULL); - ASSERT_EQ("127.0.0.1", IPAddressToString(record_obj->address())); + ASSERT_EQ("127.0.0.1", record_obj->address().ToString()); ASSERT_TRUE(record_obj->IsEqual(record_obj.get())); } @@ -98,8 +97,7 @@ record_obj = AAAARecordRdata::Create(record_strpiece, parser); ASSERT_TRUE(record_obj != NULL); - ASSERT_EQ("1234:5678::9", - IPAddressToString(record_obj->address())); + ASSERT_EQ("1234:5678::9", record_obj->address().ToString()); ASSERT_TRUE(record_obj->IsEqual(record_obj.get())); }
diff --git a/net/ftp/ftp_directory_listing_fuzzer.cc b/net/ftp/ftp_directory_listing_fuzzer.cc index af99891..459379e 100644 --- a/net/ftp/ftp_directory_listing_fuzzer.cc +++ b/net/ftp/ftp_directory_listing_fuzzer.cc
@@ -8,20 +8,9 @@ #include <string> #include <vector> -#include "base/at_exit.h" -#include "base/i18n/icu_util.h" #include "base/time/time.h" #include "net/ftp/ftp_directory_listing_parser.h" -struct TestCase { - TestCase() { CHECK(base::i18n::InitializeICU()); } - - // used by ICU integration. - base::AtExitManager at_exit_manager; -}; - -TestCase* test_case = new TestCase(); - // Entry point for LibFuzzer. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::string buffer(reinterpret_cast<const char*>(data), size);
diff --git a/net/quic/p2p/quic_p2p_session.cc b/net/quic/p2p/quic_p2p_session.cc index 148efe7..ba7298d 100644 --- a/net/quic/p2p/quic_p2p_session.cc +++ b/net/quic/p2p/quic_p2p_session.cc
@@ -55,6 +55,7 @@ if (delegate_) { delegate_->OnIncomingStream(stream); } + ActivateStream(stream); return stream; }
diff --git a/net/quic/quic_chromium_client_session.cc b/net/quic/quic_chromium_client_session.cc index 63c6d10..47f46bd 100644 --- a/net/quic/quic_chromium_client_session.cc +++ b/net/quic/quic_chromium_client_session.cc
@@ -651,6 +651,7 @@ QuicChromiumClientStream* stream = new QuicChromiumClientStream(id, this, net_log_); stream->CloseWriteSide(); + ActivateStream(stream); ++num_total_streams_; return stream; }
diff --git a/net/quic/quic_client_session_base.cc b/net/quic/quic_client_session_base.cc index 32b3093..7e45d00 100644 --- a/net/quic/quic_client_session_base.cc +++ b/net/quic/quic_client_session_base.cc
@@ -28,16 +28,6 @@ void QuicClientSessionBase::OnCryptoHandshakeEvent(CryptoHandshakeEvent event) { QuicSession::OnCryptoHandshakeEvent(event); - // Set FEC policy for streams immediately after sending CHLO and before any - // more data is sent. - if (!FLAGS_enable_quic_fec || event != ENCRYPTION_FIRST_ESTABLISHED || - !config()->HasSendConnectionOptions() || - !ContainsQuicTag(config()->SendConnectionOptions(), kFHDR)) { - return; - } - // kFHDR config maps to FEC protection always for headers stream. - // TODO(jri): Add crypto stream in addition to headers for kHDR. - headers_stream()->set_fec_policy(FEC_PROTECT_ALWAYS); } void QuicClientSessionBase::OnPromiseHeaders(QuicStreamId stream_id,
diff --git a/net/quic/quic_flags.cc b/net/quic/quic_flags.cc index 66868e71..9878561 100644 --- a/net/quic/quic_flags.cc +++ b/net/quic/quic_flags.cc
@@ -11,11 +11,6 @@ // CHLO. bool FLAGS_use_early_return_when_verifying_chlo = true; -// If true, QUIC connections will support FEC protection of data while sending -// packets, to reduce latency of data delivery to the application. The client -// must also request FEC protection for the server to use FEC. -bool FLAGS_enable_quic_fec = true; - // When true, defaults to BBR congestion control instead of Cubic. bool FLAGS_quic_use_bbr_congestion_control = false; @@ -71,10 +66,6 @@ // even if they are being sent. bool FLAGS_quic_use_new_idle_timeout = true; -// If true, replace QuicFrameList with StreamSequencerBuffer as underlying data -// structure for QuicStreamSequencer bufferring. -bool FLAGS_quic_use_stream_sequencer_buffer = true; - // If true, don't send QUIC packets if the send alarm is set. bool FLAGS_quic_respect_send_alarm2 = true; @@ -96,16 +87,9 @@ // If true, reject any incoming QUIC which does not have the FIXD tag. bool FLAGS_quic_require_fix = true; -// If true, QUIC supports sending trailers from Server to Client. -bool FLAGS_quic_supports_trailers = true; - // If true, headers stream will support receiving PUSH_PROMISE frames. bool FLAGS_quic_supports_push_promise = false; -// Enable counters for incoming/outgoing streams which are used as condition -// check while creating a new stream. -bool FLAGS_quic_distinguish_incoming_outgoing_streams = true; - // If true, QUIC servers will attempt to validate a client's source // address token using the primary config, even if no server config id // is present in the client hello. @@ -153,3 +137,7 @@ // Saves the initial subkey secret in QUIC crypto when deriving keys from the // initial premaster secret. bool FLAGS_quic_save_initial_subkey_secret = true; + +// If true, the QUIC dispatcher will directly send version negotiation packets +// without needing to create a QUIC session first. +bool FLAGS_quic_stateless_version_negotiation = false;
diff --git a/net/quic/quic_flags.h b/net/quic/quic_flags.h index a991a59..a110e578 100644 --- a/net/quic/quic_flags.h +++ b/net/quic/quic_flags.h
@@ -11,7 +11,6 @@ NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_time_loss_detection; NET_EXPORT_PRIVATE extern bool FLAGS_use_early_return_when_verifying_chlo; -NET_EXPORT_PRIVATE extern bool FLAGS_enable_quic_fec; NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_bbr_congestion_control; NET_EXPORT_PRIVATE extern bool FLAGS_quic_allow_bbr; NET_EXPORT_PRIVATE extern int64_t FLAGS_quic_time_wait_list_seconds; @@ -25,16 +24,15 @@ NET_EXPORT_PRIVATE extern bool FLAGS_quic_measure_headers_hol_blocking_time; NET_EXPORT_PRIVATE extern bool FLAGS_quic_disable_pacing; NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_new_idle_timeout; -NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_stream_sequencer_buffer; NET_EXPORT_PRIVATE extern bool FLAGS_quic_respect_send_alarm2; NET_EXPORT_PRIVATE extern bool FLAGS_quic_batch_writes; NET_EXPORT_PRIVATE extern bool FLAGS_quic_block_unencrypted_writes; NET_EXPORT_PRIVATE extern bool FLAGS_quic_never_write_unencrypted_data; NET_EXPORT_PRIVATE extern bool FLAGS_quic_no_unencrypted_fec; NET_EXPORT_PRIVATE extern bool FLAGS_quic_require_fix; -NET_EXPORT_PRIVATE extern bool FLAGS_quic_supports_trailers; +NET_EXPORT_PRIVATE extern bool FLAGS_quic_stateless_version_negotiation; NET_EXPORT_PRIVATE extern bool FLAGS_quic_supports_push_promise; -NET_EXPORT_PRIVATE extern bool FLAGS_quic_distinguish_incoming_outgoing_streams; +NET_EXPORT_PRIVATE extern bool FLAGS_quic_supports_push_promise; NET_EXPORT_PRIVATE extern bool FLAGS_quic_validate_stk_without_scid; NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_rfc7539; NET_EXPORT_PRIVATE extern bool FLAGS_require_strike_register_or_server_nonce;
diff --git a/net/quic/quic_framer.cc b/net/quic/quic_framer.cc index 7d75b8f..ac58d57a 100644 --- a/net/quic/quic_framer.cc +++ b/net/quic/quic_framer.cc
@@ -975,6 +975,7 @@ // If the version from the new packet is the same as the version of this // framer, then the public flags should be set to something we understand. // If not, this raises an error. + last_version_tag_ = version_tag; QuicVersion version = QuicTagToQuicVersion(version_tag); if (version == quic_version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) { set_detailed_error("Illegal public flags value."); @@ -1487,6 +1488,7 @@ } if (num_received_packets > 0) { + ack_frame->received_packet_times.reserve(num_received_packets); uint8_t delta_from_largest_observed; if (!reader->ReadBytes(&delta_from_largest_observed, PACKET_1BYTE_PACKET_NUMBER)) {
diff --git a/net/quic/quic_framer.h b/net/quic/quic_framer.h index 456f2b09..3cc24267 100644 --- a/net/quic/quic_framer.h +++ b/net/quic/quic_framer.h
@@ -369,6 +369,8 @@ // Called when a PATH_CLOSED frame has been sent/received on |path_id|. void OnPathClosed(QuicPathId path_id); + QuicTag last_version_tag() { return last_version_tag_; } + private: friend class test::QuicFramerPeer; @@ -536,6 +538,8 @@ QuicPathId last_path_id_; // Updated by WritePacketHeader. QuicConnectionId last_serialized_connection_id_; + // The last QUIC version tag received. + QuicTag last_version_tag_; // Version of the protocol being used. QuicVersion quic_version_; // This vector contains QUIC versions which we currently support.
diff --git a/net/quic/quic_headers_stream.cc b/net/quic/quic_headers_stream.cc index 922c703..b62717c2 100644 --- a/net/quic/quic_headers_stream.cc +++ b/net/quic/quic_headers_stream.cc
@@ -65,6 +65,10 @@ CloseConnection("SPDY DATA frame received."); } + void OnStreamEnd(SpdyStreamId stream_id) override { + LOG(DFATAL) << "Unimplemented."; + } + void OnStreamPadding(SpdyStreamId stream_id, size_t len) override { CloseConnection("SPDY frame padding received."); }
diff --git a/net/quic/quic_headers_stream_test.cc b/net/quic/quic_headers_stream_test.cc index 15e7c8d..a821fb2 100644 --- a/net/quic/quic_headers_stream_test.cc +++ b/net/quic/quic_headers_stream_test.cc
@@ -42,6 +42,7 @@ MOCK_METHOD4( OnStreamFrameData, void(SpdyStreamId stream_id, const char* data, size_t len, bool fin)); + MOCK_METHOD1(OnStreamEnd, void(SpdyStreamId stream_id)); MOCK_METHOD2(OnStreamPadding, void(SpdyStreamId stream_id, size_t len)); MOCK_METHOD1(OnHeaderFrameStart, SpdyHeadersHandlerInterface*(SpdyStreamId stream_id));
diff --git a/net/quic/quic_http_stream.cc b/net/quic/quic_http_stream.cc index 0a006e2..e733319 100644 --- a/net/quic/quic_http_stream.cc +++ b/net/quic/quic_http_stream.cc
@@ -708,6 +708,13 @@ int QuicHttpStream::ReadAvailableData(IOBuffer* buf, int buf_len) { int rv = stream_->Read(buf, buf_len); + // TODO(rtenneti): Temporary fix for crbug.com/585591. Added a check for null + // |stream_| to fix crash bug. Delete |stream_| check and histogram after fix + // is merged. + bool null_stream = stream_ == nullptr; + UMA_HISTOGRAM_BOOLEAN("Net.QuicReadAvailableData.NullStream", null_stream); + if (null_stream) + return rv; if (stream_->IsDoneReading()) { stream_->SetDelegate(nullptr); stream_->OnFinRead();
diff --git a/net/quic/quic_packet_generator.cc b/net/quic/quic_packet_generator.cc index f9d6ed1..75e1c59 100644 --- a/net/quic/quic_packet_generator.cc +++ b/net/quic/quic_packet_generator.cc
@@ -14,8 +14,6 @@ namespace net { -class QuicAckNotifier; - QuicPacketGenerator::QuicPacketGenerator(QuicConnectionId connection_id, QuicFramer* framer, QuicRandom* random_generator,
diff --git a/net/quic/quic_session.cc b/net/quic/quic_session.cc index e3aad3f..d8ec06c 100644 --- a/net/quic/quic_session.cc +++ b/net/quic/quic_session.cc
@@ -675,12 +675,7 @@ } // Check if the new number of open streams would cause the number of // open streams to exceed the limit. - size_t num_open_incoming_streams = - FLAGS_quic_distinguish_incoming_outgoing_streams - ? GetNumOpenIncomingStreams() - : dynamic_stream_map_.size() - draining_streams_.size() + - locally_closed_streams_highest_offset_.size(); - if (num_open_incoming_streams >= max_open_incoming_streams()) { + if (GetNumOpenIncomingStreams() >= max_open_incoming_streams()) { if (connection()->version() <= QUIC_VERSION_27) { connection()->SendConnectionCloseWithDetails( QUIC_TOO_MANY_OPEN_STREAMS, "Old style stream rejection"); @@ -691,12 +686,7 @@ return nullptr; } - ReliableQuicStream* stream = CreateIncomingDynamicStream(stream_id); - if (stream == nullptr) { - return nullptr; - } - ActivateStream(stream); - return stream; + return CreateIncomingDynamicStream(stream_id); } void QuicSession::set_max_open_incoming_streams(
diff --git a/net/quic/quic_session.h b/net/quic/quic_session.h index b4d71316..601edee 100644 --- a/net/quic/quic_session.h +++ b/net/quic/quic_session.h
@@ -228,13 +228,14 @@ protected: typedef std::unordered_map<QuicStreamId, ReliableQuicStream*> StreamMap; - // Creates a new stream, owned by the caller, to handle a peer-initiated - // stream. Returns nullptr and does error handling if the stream can not be - // created. + // Creates a new stream to handle a peer-initiated stream. + // Caller does not own the returned stream. + // Returns nullptr and does error handling if the stream can not be created. virtual ReliableQuicStream* CreateIncomingDynamicStream(QuicStreamId id) = 0; - // Create a new stream, owned by the caller, to handle a locally-initiated - // stream. Returns nullptr if max streams have already been opened. + // Create a new stream to handle a locally-initiated stream. + // Caller does not own the returned stream. + // Returns nullptr if max streams have already been opened. virtual ReliableQuicStream* CreateOutgoingDynamicStream( SpdyPriority priority) = 0; @@ -253,6 +254,7 @@ // and |stream_id| is a peer-created id, then a new stream is created and // returned. However if |stream_id| is a locally-created id and no such stream // exists, the connection is closed. + // Caller does not own the returned stream. ReliableQuicStream* GetOrCreateDynamicStream(QuicStreamId stream_id); // Performs the work required to close |stream_id|. If |locally_reset|
diff --git a/net/quic/quic_session_test.cc b/net/quic/quic_session_test.cc index d38b32b..a0da6b9 100644 --- a/net/quic/quic_session_test.cc +++ b/net/quic/quic_session_test.cc
@@ -136,7 +136,9 @@ "Too many streams!"); return nullptr; } else { - return new TestStream(id, this); + TestStream* stream = new TestStream(id, this); + ActivateStream(stream); + return stream; } }
diff --git a/net/quic/quic_spdy_stream.cc b/net/quic/quic_spdy_stream.cc index 3c68c130..75b160e 100644 --- a/net/quic/quic_spdy_stream.cc +++ b/net/quic/quic_spdy_stream.cc
@@ -79,9 +79,6 @@ size_t QuicSpdyStream::WriteTrailers( SpdyHeaderBlock trailer_block, QuicAckListenerInterface* ack_notifier_delegate) { - if (!FLAGS_quic_supports_trailers) { - return 0; - } if (fin_sent()) { QUIC_BUG << "Trailers cannot be sent after a FIN."; return 0; @@ -134,8 +131,7 @@ bool QuicSpdyStream::HasBytesToRead() const { bool headers_to_read = !decompressed_headers_.empty(); bool body_to_read = sequencer()->HasBytesToRead(); - bool trailers_to_read = - (FLAGS_quic_supports_trailers && !decompressed_trailers_.empty()); + bool trailers_to_read = !decompressed_trailers_.empty(); return headers_to_read || body_to_read || trailers_to_read; } @@ -157,7 +153,7 @@ } void QuicSpdyStream::OnStreamHeaders(StringPiece headers_data) { - if (!FLAGS_quic_supports_trailers || !headers_decompressed_) { + if (!headers_decompressed_) { headers_data.AppendToString(&decompressed_headers_); } else { DCHECK(!trailers_decompressed_); @@ -171,7 +167,7 @@ } void QuicSpdyStream::OnStreamHeadersComplete(bool fin, size_t frame_len) { - if (!FLAGS_quic_supports_trailers || !headers_decompressed_) { + if (!headers_decompressed_) { OnInitialHeadersComplete(fin, frame_len); } else { OnTrailingHeadersComplete(fin, frame_len); @@ -251,9 +247,6 @@ } bool QuicSpdyStream::FinishedReadingTrailers() const { - if (!FLAGS_quic_supports_trailers) { - return true; - } // If no further trailing headers are expected, and the decompressed trailers // (if any) have been consumed, then reading of trailers is finished. bool no_more_trailers = fin_received() || trailers_decompressed_;
diff --git a/net/quic/quic_spdy_stream.h b/net/quic/quic_spdy_stream.h index e7f640e..65304d66 100644 --- a/net/quic/quic_spdy_stream.h +++ b/net/quic/quic_spdy_stream.h
@@ -107,8 +107,8 @@ // Writes the trailers contained in |trailer_block| to the dedicated // headers stream. Trailers will always have the FIN set. - virtual size_t WriteTrailers(SpdyHeaderBlock trailer_block, - QuicAckListenerInterface* ack_notifier_delegate); + size_t WriteTrailers(SpdyHeaderBlock trailer_block, + QuicAckListenerInterface* ack_notifier_delegate); // Marks |bytes_consumed| of the headers data as consumed. void MarkHeadersConsumed(size_t bytes_consumed);
diff --git a/net/quic/quic_spdy_stream_test.cc b/net/quic/quic_spdy_stream_test.cc index 090ad7c..54ebb8a 100644 --- a/net/quic/quic_spdy_stream_test.cc +++ b/net/quic/quic_spdy_stream_test.cc
@@ -618,7 +618,6 @@ TEST_P(QuicSpdyStreamTest, ReceivingTrailers) { // Test that receiving trailing headers from the peer works, and can be read // from the stream and consumed. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); // Receive initial headers. @@ -648,7 +647,6 @@ TEST_P(QuicSpdyStreamTest, ReceivingTrailersWithoutFin) { // Test that received Trailers must always have the FIN set. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); // Receive initial headers. @@ -669,7 +667,6 @@ TEST_P(QuicSpdyStreamTest, ReceivingTrailersAfterFin) { // If Trailers are sent, neither Headers nor Body should contain a FIN. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); // Receive initial headers with FIN set. @@ -690,7 +687,6 @@ TEST_P(QuicSpdyStreamTest, ReceivingTrailersAfterBodyWithFin) { // If body data are received with a FIN, no trailers should then arrive. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); // Receive initial headers without FIN set. @@ -716,7 +712,6 @@ TEST_P(QuicSpdyStreamTest, ClosingStreamWithNoTrailers) { // Verify that a stream receiving headers, body, and no trailers is correctly // marked as done reading on consumption of headers and body. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); // Receive and consume initial headers with FIN not set. @@ -736,7 +731,6 @@ TEST_P(QuicSpdyStreamTest, WritingTrailersSendsAFin) { // Test that writing trailers will send a FIN, as Trailers are the last thing // to be sent on a stream. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber()) @@ -758,7 +752,6 @@ TEST_P(QuicSpdyStreamTest, WritingTrailersFinalOffset) { // Test that when writing trailers, the trailers that are actually sent to the // peer contain the final offset field indicating last byte of data. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber()) @@ -786,7 +779,6 @@ TEST_P(QuicSpdyStreamTest, WritingTrailersClosesWriteSide) { // Test that if trailers are written after all other data has been written // (headers and body), that this closes the stream for writing. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber()) @@ -812,7 +804,6 @@ TEST_P(QuicSpdyStreamTest, WritingTrailersWithQueuedBytes) { // Test that the stream is not closed for writing when trailers are sent // while there are still body bytes queued. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber()) @@ -840,7 +831,6 @@ TEST_P(QuicSpdyStreamTest, WritingTrailersAfterFIN) { // Test that it is not possible to write Trailers after a FIN has been sent. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); Initialize(kShouldProcessData); EXPECT_CALL(*session_, WritevData(_, _, _, _, _, _)) .Times(AnyNumber())
diff --git a/net/quic/quic_stream_sequencer.cc b/net/quic/quic_stream_sequencer.cc index 18f40a3..113f4ff 100644 --- a/net/quic/quic_stream_sequencer.cc +++ b/net/quic/quic_stream_sequencer.cc
@@ -12,7 +12,6 @@ #include "net/quic/quic_bug_tracker.h" #include "net/quic/quic_clock.h" #include "net/quic/quic_flags.h" -#include "net/quic/quic_frame_list.h" #include "net/quic/quic_protocol.h" #include "net/quic/reliable_quic_stream.h" #include "net/quic/stream_sequencer_buffer.h" @@ -26,20 +25,14 @@ QuicStreamSequencer::QuicStreamSequencer(ReliableQuicStream* quic_stream, const QuicClock* clock) : stream_(quic_stream), + buffered_frames_(kStreamReceiveWindowLimit), close_offset_(numeric_limits<QuicStreamOffset>::max()), blocked_(false), num_frames_received_(0), num_duplicate_frames_received_(0), num_early_frames_received_(0), clock_(clock), - ignore_read_data_(false) { - if (FLAGS_quic_use_stream_sequencer_buffer) { - buffered_frames_.reset( - new StreamSequencerBuffer(kStreamReceiveWindowLimit)); - } else { - buffered_frames_.reset(new QuicFrameList()); - } -} + ignore_read_data_(false) {} QuicStreamSequencer::~QuicStreamSequencer() {} @@ -63,7 +56,7 @@ } } size_t bytes_written; - QuicErrorCode result = buffered_frames_->OnStreamData( + QuicErrorCode result = buffered_frames_.OnStreamData( byte_offset, StringPiece(frame.frame_buffer, frame.frame_length), clock_->ApproximateNow(), &bytes_written); @@ -80,7 +73,7 @@ return; } - if (byte_offset > buffered_frames_->BytesConsumed()) { + if (byte_offset > buffered_frames_.BytesConsumed()) { ++num_early_frames_received_; } @@ -88,7 +81,7 @@ return; } - if (byte_offset == buffered_frames_->BytesConsumed()) { + if (byte_offset == buffered_frames_.BytesConsumed()) { if (ignore_read_data_) { FlushBufferedFrames(); } else { @@ -117,7 +110,7 @@ } DVLOG(1) << "Passing up termination, as we've processed " - << buffered_frames_->BytesConsumed() << " of " << close_offset_ + << buffered_frames_.BytesConsumed() << " of " << close_offset_ << " bytes."; // This will cause the stream to consume the FIN. // Technically it's an error if |num_bytes_consumed| isn't exactly @@ -129,39 +122,39 @@ } else { stream_->OnDataAvailable(); } - buffered_frames_->Clear(); + buffered_frames_.Clear(); return true; } int QuicStreamSequencer::GetReadableRegions(iovec* iov, size_t iov_len) const { DCHECK(!blocked_); - return buffered_frames_->GetReadableRegions(iov, iov_len); + return buffered_frames_.GetReadableRegions(iov, iov_len); } bool QuicStreamSequencer::GetReadableRegion(iovec* iov, QuicTime* timestamp) const { DCHECK(!blocked_); - return buffered_frames_->GetReadableRegion(iov, timestamp); + return buffered_frames_.GetReadableRegion(iov, timestamp); } int QuicStreamSequencer::Readv(const struct iovec* iov, size_t iov_len) { DCHECK(!blocked_); - size_t bytes_read = buffered_frames_->Readv(iov, iov_len); + size_t bytes_read = buffered_frames_.Readv(iov, iov_len); stream_->AddBytesConsumed(bytes_read); return static_cast<int>(bytes_read); } bool QuicStreamSequencer::HasBytesToRead() const { - return buffered_frames_->HasBytesToRead(); + return buffered_frames_.HasBytesToRead(); } bool QuicStreamSequencer::IsClosed() const { - return buffered_frames_->BytesConsumed() >= close_offset_; + return buffered_frames_.BytesConsumed() >= close_offset_; } void QuicStreamSequencer::MarkConsumed(size_t num_bytes_consumed) { DCHECK(!blocked_); - bool result = buffered_frames_->MarkConsumed(num_bytes_consumed); + bool result = buffered_frames_.MarkConsumed(num_bytes_consumed); if (!result) { QUIC_BUG << "Invalid argument to MarkConsumed." << " expect to consume: " << num_bytes_consumed @@ -193,20 +186,20 @@ void QuicStreamSequencer::FlushBufferedFrames() { DCHECK(ignore_read_data_); - size_t bytes_flushed = buffered_frames_->FlushBufferedFrames(); + size_t bytes_flushed = buffered_frames_.FlushBufferedFrames(); DVLOG(1) << "Flushing buffered data at offset " - << buffered_frames_->BytesConsumed() << " length " << bytes_flushed + << buffered_frames_.BytesConsumed() << " length " << bytes_flushed << " for stream " << stream_->id(); stream_->AddBytesConsumed(bytes_flushed); MaybeCloseStream(); } size_t QuicStreamSequencer::NumBytesBuffered() const { - return buffered_frames_->BytesBuffered(); + return buffered_frames_.BytesBuffered(); } QuicStreamOffset QuicStreamSequencer::NumBytesConsumed() const { - return buffered_frames_->BytesConsumed(); + return buffered_frames_.BytesConsumed(); } } // namespace net
diff --git a/net/quic/quic_stream_sequencer.h b/net/quic/quic_stream_sequencer.h index 65d99baa..1d06d2f 100644 --- a/net/quic/quic_stream_sequencer.h +++ b/net/quic/quic_stream_sequencer.h
@@ -11,8 +11,10 @@ #include <string> #include "base/macros.h" -#include "net/quic/quic_frame_list.h" #include "net/quic/quic_protocol.h" +#include "net/quic/stream_sequencer_buffer.h" + +using std::string; namespace net { @@ -114,7 +116,7 @@ ReliableQuicStream* stream_; // Stores received data in offset order. - scoped_ptr<QuicStreamSequencerBufferInterface> buffered_frames_; + StreamSequencerBuffer buffered_frames_; // The offset, if any, we got a stream termination for. When this many bytes // have been processed, the sequencer will be closed.
diff --git a/net/quic/quic_stream_sequencer_test.cc b/net/quic/quic_stream_sequencer_test.cc index a7e08ad..4d0f0c0 100644 --- a/net/quic/quic_stream_sequencer_test.cc +++ b/net/quic/quic_stream_sequencer_test.cc
@@ -57,13 +57,8 @@ static const char kPayload[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; -class QuicStreamSequencerTest : public ::testing::TestWithParam<bool> { +class QuicStreamSequencerTest : public ::testing::Test { public: - void SetUp() override { - FLAGS_quic_use_stream_sequencer_buffer = GetParam(); - sequencer_.reset(new QuicStreamSequencer(&stream_, &clock_)); - } - void ConsumeData(size_t num_bytes) { char buffer[1024]; ASSERT_GT(arraysize(buffer), num_bytes); @@ -77,7 +72,8 @@ QuicStreamSequencerTest() : connection_(new MockConnection(&helper_, Perspective::IS_CLIENT)), session_(connection_), - stream_(&session_, 1) {} + stream_(&session_, 1), + sequencer_(new QuicStreamSequencer(&stream_, &clock_)) {} // Verify that the data in first region match with the expected[0]. bool VerifyReadableRegion(const vector<string>& expected) { @@ -101,27 +97,13 @@ bool VerifyIovecs(iovec* iovecs, size_t num_iovecs, const vector<string>& expected) { - if (!FLAGS_quic_use_stream_sequencer_buffer) { - if (expected.size() != num_iovecs) { - LOG(ERROR) << "Incorrect number of iovecs. Expected: " - << expected.size() << " Actual: " << num_iovecs; + int start_position = 0; + for (size_t i = 0; i < num_iovecs; ++i) { + if (!VerifyIovec(iovecs[i], + expected[0].substr(start_position, iovecs[i].iov_len))) { return false; } - - for (size_t i = 0; i < num_iovecs; ++i) { - if (!VerifyIovec(iovecs[i], expected[i])) { - return false; - } - } - } else { - int start_position = 0; - for (size_t i = 0; i < num_iovecs; ++i) { - if (!VerifyIovec(iovecs[i], expected[0].substr(start_position, - iovecs[i].iov_len))) { - return false; - } - start_position += iovecs[i].iov_len; - } + start_position += iovecs[i].iov_len; } return true; } @@ -172,13 +154,9 @@ scoped_ptr<QuicStreamSequencer> sequencer_; }; -INSTANTIATE_TEST_CASE_P(QuicStreamSequencerTests, - QuicStreamSequencerTest, - ::testing::Values(false, true)); - // TODO(rch): reorder these tests so they build on each other. -TEST_P(QuicStreamSequencerTest, RejectOldFrame) { +TEST_F(QuicStreamSequencerTest, RejectOldFrame) { EXPECT_CALL(stream_, OnDataAvailable()) .WillOnce(testing::Invoke( CreateFunctor(&QuicStreamSequencerTest::ConsumeData, @@ -195,7 +173,7 @@ EXPECT_EQ(0u, NumBufferedBytes()); } -TEST_P(QuicStreamSequencerTest, RejectBufferedFrame) { +TEST_F(QuicStreamSequencerTest, RejectBufferedFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); @@ -208,7 +186,7 @@ EXPECT_EQ(3u, NumBufferedBytes()); } -TEST_P(QuicStreamSequencerTest, FullFrameConsumed) { +TEST_F(QuicStreamSequencerTest, FullFrameConsumed) { EXPECT_CALL(stream_, OnDataAvailable()) .WillOnce(testing::Invoke( CreateFunctor(&QuicStreamSequencerTest::ConsumeData, @@ -219,7 +197,7 @@ EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); } -TEST_P(QuicStreamSequencerTest, BlockedThenFullFrameConsumed) { +TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameConsumed) { sequencer_->SetBlockedUntilFlush(); OnFrame(0, "abc"); @@ -243,7 +221,7 @@ EXPECT_TRUE(sequencer_->IsClosed()); } -TEST_P(QuicStreamSequencerTest, BlockedThenFullFrameAndFinConsumed) { +TEST_F(QuicStreamSequencerTest, BlockedThenFullFrameAndFinConsumed) { sequencer_->SetBlockedUntilFlush(); OnFinFrame(0, "abc"); @@ -261,7 +239,7 @@ EXPECT_EQ(3u, sequencer_->NumBytesConsumed()); } -TEST_P(QuicStreamSequencerTest, EmptyFrame) { +TEST_F(QuicStreamSequencerTest, EmptyFrame) { EXPECT_CALL(stream_, CloseConnectionWithDetails(QUIC_INVALID_STREAM_FRAME, _)); OnFrame(0, ""); @@ -269,14 +247,14 @@ EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } -TEST_P(QuicStreamSequencerTest, EmptyFinFrame) { +TEST_F(QuicStreamSequencerTest, EmptyFinFrame) { EXPECT_CALL(stream_, OnDataAvailable()); OnFinFrame(0, ""); EXPECT_EQ(0u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); } -TEST_P(QuicStreamSequencerTest, PartialFrameConsumed) { +TEST_F(QuicStreamSequencerTest, PartialFrameConsumed) { EXPECT_CALL(stream_, OnDataAvailable()) .WillOnce(testing::Invoke( CreateFunctor(&QuicStreamSequencerTest::ConsumeData, @@ -287,7 +265,7 @@ EXPECT_EQ(2u, sequencer_->NumBytesConsumed()); } -TEST_P(QuicStreamSequencerTest, NextxFrameNotConsumed) { +TEST_F(QuicStreamSequencerTest, NextxFrameNotConsumed) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); @@ -296,14 +274,14 @@ EXPECT_EQ(0, sequencer_->num_early_frames_received()); } -TEST_P(QuicStreamSequencerTest, FutureFrameNotProcessed) { +TEST_F(QuicStreamSequencerTest, FutureFrameNotProcessed) { OnFrame(3, "abc"); EXPECT_EQ(3u, NumBufferedBytes()); EXPECT_EQ(0u, sequencer_->NumBytesConsumed()); EXPECT_EQ(1, sequencer_->num_early_frames_received()); } -TEST_P(QuicStreamSequencerTest, OutOfOrderFrameProcessed) { +TEST_F(QuicStreamSequencerTest, OutOfOrderFrameProcessed) { // Buffer the first OnFrame(6, "ghi"); EXPECT_EQ(3u, NumBufferedBytes()); @@ -328,7 +306,7 @@ EXPECT_EQ(0u, NumBufferedBytes()); } -TEST_P(QuicStreamSequencerTest, BasicHalfCloseOrdered) { +TEST_F(QuicStreamSequencerTest, BasicHalfCloseOrdered) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()) @@ -340,7 +318,7 @@ EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); } -TEST_P(QuicStreamSequencerTest, BasicHalfCloseUnorderedWithFlush) { +TEST_F(QuicStreamSequencerTest, BasicHalfCloseUnorderedWithFlush) { OnFinFrame(6, ""); EXPECT_EQ(6u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); @@ -354,7 +332,7 @@ EXPECT_TRUE(sequencer_->IsClosed()); } -TEST_P(QuicStreamSequencerTest, BasicHalfUnordered) { +TEST_F(QuicStreamSequencerTest, BasicHalfUnordered) { OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); @@ -367,7 +345,7 @@ EXPECT_TRUE(sequencer_->IsClosed()); } -TEST_P(QuicStreamSequencerTest, TerminateWithReadv) { +TEST_F(QuicStreamSequencerTest, TerminateWithReadv) { char buffer[3]; OnFinFrame(3, ""); @@ -384,7 +362,7 @@ EXPECT_TRUE(sequencer_->IsClosed()); } -TEST_P(QuicStreamSequencerTest, MutipleOffsets) { +TEST_F(QuicStreamSequencerTest, MutipleOffsets) { OnFinFrame(3, ""); EXPECT_EQ(3u, QuicStreamSequencerPeer::GetCloseOffset(sequencer_.get())); @@ -439,7 +417,7 @@ // All frames are processed as soon as we have sequential data. // Infinite buffering, so all frames are acked right away. -TEST_P(QuicSequencerRandomTest, RandomFramesNoDroppingNoBackup) { +TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingNoBackup) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()) .Times(AnyNumber()) @@ -458,7 +436,7 @@ EXPECT_EQ(kPayload, output_); } -TEST_P(QuicSequencerRandomTest, RandomFramesNoDroppingBackup) { +TEST_F(QuicSequencerRandomTest, RandomFramesNoDroppingBackup) { char buffer[10]; iovec iov[2]; iov[0].iov_base = &buffer[0]; @@ -504,7 +482,7 @@ } // Same as above, just using a different method for reading. -TEST_P(QuicStreamSequencerTest, MarkConsumed) { +TEST_F(QuicStreamSequencerTest, MarkConsumed) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); @@ -516,24 +494,14 @@ EXPECT_EQ(9u, sequencer_->NumBytesBuffered()); // Peek into the data. - vector<string> expected; - if (FLAGS_quic_use_stream_sequencer_buffer) { - expected = vector<string>{"abcdefghi"}; - } else { - expected = vector<string>{"abc", "def", "ghi"}; - } + vector<string> expected = {"abcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected)); // Consume 1 byte. sequencer_->MarkConsumed(1); EXPECT_EQ(1u, stream_.flow_controller()->bytes_consumed()); // Verify data. - vector<string> expected2; - if (FLAGS_quic_use_stream_sequencer_buffer) { - expected2 = vector<string>{"bcdefghi"}; - } else { - expected2 = vector<string>{"bc", "def", "ghi"}; - } + vector<string> expected2 = {"bcdefghi"}; ASSERT_TRUE(VerifyReadableRegions(expected2)); EXPECT_EQ(8u, sequencer_->NumBytesBuffered()); @@ -541,12 +509,7 @@ sequencer_->MarkConsumed(2); EXPECT_EQ(3u, stream_.flow_controller()->bytes_consumed()); // Verify data. - vector<string> expected3; - if (FLAGS_quic_use_stream_sequencer_buffer) { - expected3 = vector<string>{"defghi"}; - } else { - expected3 = vector<string>{"def", "ghi"}; - } + vector<string> expected3 = {"defghi"}; ASSERT_TRUE(VerifyReadableRegions(expected3)); EXPECT_EQ(6u, sequencer_->NumBytesBuffered()); @@ -559,7 +522,7 @@ EXPECT_EQ(1u, sequencer_->NumBytesBuffered()); } -TEST_P(QuicStreamSequencerTest, MarkConsumedError) { +TEST_F(QuicStreamSequencerTest, MarkConsumedError) { EXPECT_CALL(stream_, OnDataAvailable()); OnFrame(0, "abc"); @@ -578,7 +541,7 @@ " expect to consume: 4, but not enough bytes available."); } -TEST_P(QuicStreamSequencerTest, MarkConsumedWithMissingPacket) { +TEST_F(QuicStreamSequencerTest, MarkConsumedWithMissingPacket) { InSequence s; EXPECT_CALL(stream_, OnDataAvailable()); @@ -587,12 +550,7 @@ // Missing packet: 6, ghi. OnFrame(9, "jkl"); - vector<string> expected; - if (FLAGS_quic_use_stream_sequencer_buffer) { - expected = vector<string>{"abcdef"}; - } else { - expected = vector<string>{"abc", "def"}; - } + vector<string> expected = {"abcdef"}; ASSERT_TRUE(VerifyReadableRegions(expected)); sequencer_->MarkConsumed(6); @@ -646,7 +604,7 @@ QuicStreamFrame(1, false, kBufferedOffset + kBufferedDataLength, data))); } -TEST_P(QuicStreamSequencerTest, DontAcceptOverlappingFrames) { +TEST_F(QuicStreamSequencerTest, DontAcceptOverlappingFrames) { // The peer should never send us non-identical stream frames which contain // overlapping byte ranges - if they do, we close the connection. @@ -659,7 +617,7 @@ sequencer_->OnStreamFrame(frame2); } -TEST_P(QuicStreamSequencerTest, InOrderTimestamps) { +TEST_F(QuicStreamSequencerTest, InOrderTimestamps) { // This test verifies that timestamps returned by // GetReadableRegion() are in the correct sequence when frames // arrive at the sequencer in order. @@ -700,7 +658,7 @@ EXPECT_EQ(0u, sequencer_->NumBytesBuffered()); } -TEST_P(QuicStreamSequencerTest, OutOfOrderTimestamps) { +TEST_F(QuicStreamSequencerTest, OutOfOrderTimestamps) { // This test verifies that timestamps returned by // GetReadableRegion() are in the correct sequence when frames // arrive at the sequencer out of order.
diff --git a/net/quic/test_tools/quic_stream_sequencer_peer.cc b/net/quic/test_tools/quic_stream_sequencer_peer.cc index 290e2ea..1a6eae7 100644 --- a/net/quic/test_tools/quic_stream_sequencer_peer.cc +++ b/net/quic/test_tools/quic_stream_sequencer_peer.cc
@@ -15,7 +15,7 @@ // static size_t QuicStreamSequencerPeer::GetNumBufferedBytes( QuicStreamSequencer* sequencer) { - return sequencer->buffered_frames_->BytesBuffered(); + return sequencer->buffered_frames_.BytesBuffered(); } // static
diff --git a/net/socket/unix_domain_server_socket_posix.h b/net/socket/unix_domain_server_socket_posix.h index 536074c4..7395f058 100644 --- a/net/socket/unix_domain_server_socket_posix.h +++ b/net/socket/unix_domain_server_socket_posix.h
@@ -92,4 +92,4 @@ } // namespace net -#endif // NET_SOCKET_UNIX_DOMAIN_SOCKET_POSIX_H_ +#endif // NET_SOCKET_UNIX_DOMAIN_SERVER_SOCKET_POSIX_H_
diff --git a/net/spdy/buffered_spdy_framer.cc b/net/spdy/buffered_spdy_framer.cc index bdad0db..e76b83d7 100644 --- a/net/spdy/buffered_spdy_framer.cc +++ b/net/spdy/buffered_spdy_framer.cc
@@ -201,6 +201,10 @@ visitor_->OnStreamFrameData(stream_id, data, len, fin); } +void BufferedSpdyFramer::OnStreamEnd(SpdyStreamId stream_id) { + LOG(DFATAL) << "Unimplemented"; +} + void BufferedSpdyFramer::OnStreamPadding(SpdyStreamId stream_id, size_t len) { visitor_->OnStreamPadding(stream_id, len); }
diff --git a/net/spdy/buffered_spdy_framer.h b/net/spdy/buffered_spdy_framer.h index f213998..65460bb 100644 --- a/net/spdy/buffered_spdy_framer.h +++ b/net/spdy/buffered_spdy_framer.h
@@ -181,6 +181,7 @@ const char* data, size_t len, bool fin) override; + void OnStreamEnd(SpdyStreamId stream_id) override; void OnStreamPadding(SpdyStreamId stream_id, size_t len) override; SpdyHeadersHandlerInterface* OnHeaderFrameStart( SpdyStreamId stream_id) override;
diff --git a/net/spdy/mock_spdy_framer_visitor.h b/net/spdy/mock_spdy_framer_visitor.h index 85bf5ba0..d330c262 100644 --- a/net/spdy/mock_spdy_framer_visitor.h +++ b/net/spdy/mock_spdy_framer_visitor.h
@@ -28,6 +28,7 @@ const char* data, size_t len, bool fin)); + MOCK_METHOD1(OnStreamEnd, void(SpdyStreamId stream_id)); MOCK_METHOD2(OnStreamPadding, void(SpdyStreamId stream_id, size_t len)); MOCK_METHOD1(OnHeaderFrameStart, SpdyHeadersHandlerInterface*(SpdyStreamId stream_id));
diff --git a/net/spdy/spdy_framer.h b/net/spdy/spdy_framer.h index ac8543a..6fce783 100644 --- a/net/spdy/spdy_framer.h +++ b/net/spdy/spdy_framer.h
@@ -119,6 +119,10 @@ size_t len, bool fin) = 0; + // Called when the other side has finished sending data on this stream. + // |stream_id| The stream that was receivin data. + virtual void OnStreamEnd(SpdyStreamId stream_id) = 0; + // Called when padding is received (padding length field or padding octets). // |stream_id| The stream receiving data. // |len| The number of padding octets.
diff --git a/net/spdy/spdy_framer_test.cc b/net/spdy/spdy_framer_test.cc index 34a8a21..2dcc855b 100644 --- a/net/spdy/spdy_framer_test.cc +++ b/net/spdy/spdy_framer_test.cc
@@ -97,6 +97,8 @@ LOG(FATAL); } + void OnStreamEnd(SpdyStreamId stream_id) override { LOG(FATAL); } + void OnStreamPadding(SpdyStreamId stream_id, size_t len) override { LOG(FATAL); } @@ -325,6 +327,10 @@ LOG(INFO) << "\", " << len << ")\n"; } + void OnStreamEnd(SpdyStreamId stream_id) override { + LOG(DFATAL) << "Unimplemented."; + } + void OnStreamPadding(SpdyStreamId stream_id, size_t len) override { EXPECT_EQ(header_stream_id_, stream_id); data_bytes_ += len;
diff --git a/net/spdy/spdy_network_transaction_unittest.cc b/net/spdy/spdy_network_transaction_unittest.cc index 0a69b34..c5638680 100644 --- a/net/spdy/spdy_network_transaction_unittest.cc +++ b/net/spdy/spdy_network_transaction_unittest.cc
@@ -2845,20 +2845,18 @@ } TEST_P(SpdyNetworkTransactionTest, ServerPushInvalidAssociatedStreamID0) { - if (spdy_util_.spdy_version() == HTTP2) { - // PUSH_PROMISE with stream id 0 is connection-level error. - // TODO(baranovich): Test session going away. - return; - } - scoped_ptr<SpdyFrame> stream1_syn( spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST, true)); - scoped_ptr<SpdyFrame> stream1_body( - spdy_util_.ConstructSpdyBodyFrame(1, true)); - scoped_ptr<SpdyFrame> stream2_rst( - spdy_util_.ConstructSpdyRstStream(2, RST_STREAM_REFUSED_STREAM)); + scoped_ptr<SpdyFrame> goaway; + if (spdy_util_.spdy_version() == SPDY3) { + goaway.reset(spdy_util_.ConstructSpdyGoAway(0, GOAWAY_PROTOCOL_ERROR, + "Push on even stream id.")); + } else { + goaway.reset(spdy_util_.ConstructSpdyGoAway( + 0, GOAWAY_PROTOCOL_ERROR, "Framer error: 1 (INVALID_CONTROL_FRAME).")); + } MockWrite writes[] = { - CreateMockWrite(*stream1_syn, 0), CreateMockWrite(*stream2_rst, 3), + CreateMockWrite(*stream1_syn, 0), CreateMockWrite(*goaway, 3), }; scoped_ptr<SpdyFrame> @@ -2868,8 +2866,6 @@ MockRead reads[] = { CreateMockRead(*stream1_reply, 1), CreateMockRead(*stream2_syn, 2), - CreateMockRead(*stream1_body, 4), - MockRead(SYNCHRONOUS, ERR_IO_PENDING, 5) // Force a pause }; SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); @@ -3001,6 +2997,142 @@ EXPECT_EQ("HTTP/1.1 200", response.headers->GetStatusLine()); } +// PUSH_PROMISE on a server-initiated stream should trigger GOAWAY. +TEST_P(SpdyNetworkTransactionTest, ServerPushOnPushedStream) { + scoped_ptr<SpdyFrame> stream1_syn( + spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST, true)); + scoped_ptr<SpdyFrame> goaway(spdy_util_.ConstructSpdyGoAway( + 2, GOAWAY_PROTOCOL_ERROR, "Push on even stream id.")); + MockWrite writes[] = { + CreateMockWrite(*stream1_syn, 0), CreateMockWrite(*goaway, 4), + }; + + scoped_ptr<SpdyFrame> stream1_reply( + spdy_util_.ConstructSpdyGetSynReply(NULL, 0, 1)); + scoped_ptr<SpdyFrame> stream2_syn(spdy_util_.ConstructSpdyPush( + nullptr, 0, 2, 1, GetDefaultUrlWithPath("/foo.dat").c_str())); + scoped_ptr<SpdyFrame> stream3_syn(spdy_util_.ConstructSpdyPush( + nullptr, 0, 4, 2, GetDefaultUrlWithPath("/bar.dat").c_str())); + MockRead reads[] = { + CreateMockRead(*stream1_reply, 1), CreateMockRead(*stream2_syn, 2), + CreateMockRead(*stream3_syn, 3), + }; + + SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); + NormalSpdyTransactionHelper helper(CreateGetRequest(), DEFAULT_PRIORITY, + BoundNetLog(), GetParam(), nullptr); + helper.RunToCompletion(&data); +} + +// PUSH_PROMISE on a closed client-initiated stream should trigger RST_STREAM. +TEST_P(SpdyNetworkTransactionTest, ServerPushOnClosedStream) { + scoped_ptr<SpdyFrame> stream1_syn( + spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST, true)); + scoped_ptr<SpdyFrame> rst( + spdy_util_.ConstructSpdyRstStream(2, RST_STREAM_INVALID_STREAM)); + MockWrite writes[] = { + CreateMockWrite(*stream1_syn, 0), CreateMockWrite(*rst, 5), + }; + + scoped_ptr<SpdyFrame> stream1_reply( + spdy_util_.ConstructSpdyGetSynReply(nullptr, 0, 1)); + scoped_ptr<SpdyFrame> stream1_body( + spdy_util_.ConstructSpdyBodyFrame(1, true)); + scoped_ptr<SpdyFrame> stream2_syn(spdy_util_.ConstructSpdyPush( + nullptr, 0, 2, 1, GetDefaultUrlWithPath("/foo.dat").c_str())); + MockRead reads[] = { + CreateMockRead(*stream1_reply, 1), CreateMockRead(*stream1_body, 2), + CreateMockRead(*stream2_syn, 3), MockRead(SYNCHRONOUS, ERR_IO_PENDING, 4), + }; + + SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); + NormalSpdyTransactionHelper helper(CreateGetRequest(), DEFAULT_PRIORITY, + BoundNetLog(), GetParam(), nullptr); + helper.RunPreTestSetup(); + helper.AddData(&data); + + HttpNetworkTransaction* trans = helper.trans(); + + TestCompletionCallback callback; + int rv = + trans->Start(&CreateGetRequest(), callback.callback(), BoundNetLog()); + rv = callback.GetResult(rv); + EXPECT_EQ(OK, rv); + HttpResponseInfo response = *trans->GetResponseInfo(); + EXPECT_TRUE(response.headers.get()); + EXPECT_EQ("HTTP/1.1 200", response.headers->GetStatusLine()); + + EXPECT_TRUE(data.AllReadDataConsumed()); + EXPECT_TRUE(data.AllWriteDataConsumed()); + VerifyStreamsClosed(helper); +} + +// PUSH_PROMISE on a server-initiated stream should trigger GOAWAY even if +// stream is closed. +TEST_P(SpdyNetworkTransactionTest, ServerPushOnClosedPushedStream) { + scoped_ptr<SpdyFrame> stream1_syn( + spdy_util_.ConstructSpdyGet(nullptr, 0, 1, LOWEST, true)); + scoped_ptr<SpdyFrame> goaway(spdy_util_.ConstructSpdyGoAway( + 2, GOAWAY_PROTOCOL_ERROR, "Push on even stream id.")); + MockWrite writes[] = { + CreateMockWrite(*stream1_syn, 0), CreateMockWrite(*goaway, 7), + }; + + scoped_ptr<SpdyFrame> stream1_reply( + spdy_util_.ConstructSpdyGetSynReply(nullptr, 0, 1)); + scoped_ptr<SpdyFrame> stream2_syn(spdy_util_.ConstructSpdyPush( + nullptr, 0, 2, 1, GetDefaultUrlWithPath("/foo.dat").c_str())); + scoped_ptr<SpdyFrame> stream1_body( + spdy_util_.ConstructSpdyBodyFrame(1, true)); + const char kPushedData[] = "pushed"; + scoped_ptr<SpdyFrame> stream2_body(spdy_util_.ConstructSpdyBodyFrame( + 2, kPushedData, strlen(kPushedData), true)); + scoped_ptr<SpdyFrame> stream3_syn(spdy_util_.ConstructSpdyPush( + nullptr, 0, 4, 2, GetDefaultUrlWithPath("/bar.dat").c_str())); + + MockRead reads[] = { + CreateMockRead(*stream1_reply, 1), CreateMockRead(*stream2_syn, 2), + CreateMockRead(*stream1_body, 3), CreateMockRead(*stream2_body, 4), + MockRead(ASYNC, ERR_IO_PENDING, 5), CreateMockRead(*stream3_syn, 6), + }; + + SequencedSocketData data(reads, arraysize(reads), writes, arraysize(writes)); + NormalSpdyTransactionHelper helper(CreateGetRequest(), DEFAULT_PRIORITY, + BoundNetLog(), GetParam(), nullptr); + helper.RunPreTestSetup(); + helper.AddData(&data); + + HttpNetworkTransaction* trans1 = helper.trans(); + TestCompletionCallback callback1; + int rv = + trans1->Start(&CreateGetRequest(), callback1.callback(), BoundNetLog()); + rv = callback1.GetResult(rv); + EXPECT_EQ(OK, rv); + HttpResponseInfo response = *trans1->GetResponseInfo(); + EXPECT_TRUE(response.headers.get()); + EXPECT_EQ("HTTP/1.1 200", response.headers->GetStatusLine()); + + scoped_ptr<HttpNetworkTransaction> trans2( + new HttpNetworkTransaction(DEFAULT_PRIORITY, helper.session())); + TestCompletionCallback callback2; + rv = trans2->Start(&CreateGetPushRequest(), callback2.callback(), + BoundNetLog()); + rv = callback2.GetResult(rv); + EXPECT_EQ(OK, rv); + response = *trans2->GetResponseInfo(); + EXPECT_TRUE(response.headers.get()); + EXPECT_EQ("HTTP/1.1 200", response.headers->GetStatusLine()); + std::string result; + ReadResult(trans2.get(), &result); + EXPECT_EQ(kPushedData, result); + + data.Resume(); + base::RunLoop().RunUntilIdle(); + + EXPECT_TRUE(data.AllReadDataConsumed()); + EXPECT_TRUE(data.AllWriteDataConsumed()); +} + // Verify that various SynReply headers parse correctly through the // HTTP layer. TEST_P(SpdyNetworkTransactionTest, SynReplyHeaders) {
diff --git a/net/spdy/spdy_session.cc b/net/spdy/spdy_session.cc index ed5f16d9..0cff0eb 100644 --- a/net/spdy/spdy_session.cc +++ b/net/spdy/spdy_session.cc
@@ -2622,6 +2622,13 @@ return false; } + // Server-initiated streams must be associated with client-initiated streams. + if ((associated_stream_id & 0x1) != 1) { + LOG(WARNING) << "Received invalid associated stream id " << stream_id; + CloseSessionOnError(ERR_SPDY_PROTOCOL_ERROR, "Push on even stream id."); + return false; + } + if (stream_id <= last_accepted_push_stream_id_) { LOG(WARNING) << "Received push stream id lesser or equal to the last " << "accepted before " << stream_id;
diff --git a/net/tools/quic/end_to_end_test.cc b/net/tools/quic/end_to_end_test.cc index ff07c60..08e2c8b 100644 --- a/net/tools/quic/end_to_end_test.cc +++ b/net/tools/quic/end_to_end_test.cc
@@ -266,7 +266,6 @@ client_supported_versions_ = GetParam().client_supported_versions; server_supported_versions_ = GetParam().server_supported_versions; negotiated_version_ = GetParam().negotiated_version; - FLAGS_enable_quic_fec = GetParam().use_fec; VLOG(1) << "Using Configuration: " << GetParam(); @@ -371,10 +370,6 @@ StartServer(); client_.reset(CreateQuicClient(client_writer_)); - if (GetParam().use_fec) { - // Set FecPolicy to always protect data on all streams. - client_->SetFecPolicy(FEC_PROTECT_ALWAYS); - } static EpollEvent event(EPOLLOUT, false); client_writer_->Initialize( reinterpret_cast<QuicEpollConnectionHelper*>( @@ -998,8 +993,7 @@ client_->client()->WaitForCryptoHandshakeConfirmed(); server_thread_->WaitForCryptoHandshakeConfirmed(); - FecPolicy expected_policy = - GetParam().use_fec ? FEC_PROTECT_ALWAYS : FEC_PROTECT_OPTIONAL; + FecPolicy expected_policy = FEC_PROTECT_OPTIONAL; // Verify that server's FEC configuration is correct. server_thread_->Pause(); @@ -1508,7 +1502,7 @@ // Create a new socket before closing the old one, which will result in a new // ephemeral port. - QuicClientPeer::CreateUDPSocket(client_->client()); + QuicClientPeer::CreateUDPSocketAndBind(client_->client()); // The packet writer needs to be updated to use the new FD. client_->client()->CreateQuicPacketWriter(); @@ -2153,7 +2147,6 @@ TEST_P(EndToEndTest, Trailers) { // Test sending and receiving HTTP/2 Trailers (trailing HEADERS frames). - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); ASSERT_TRUE(Initialize()); client_->client()->WaitForCryptoHandshakeConfirmed(); @@ -2180,8 +2173,55 @@ EXPECT_EQ(trailers, client_->response_trailers()); } -TEST_P(EndToEndTest, ServerPush) { - FLAGS_quic_supports_push_promise = true; +class EndToEndTestServerPush : public EndToEndTest { + protected: + const size_t kNumMaxStreams = 10; + + EndToEndTestServerPush() : EndToEndTest() { + FLAGS_quic_supports_push_promise = true; + FLAGS_quic_different_max_num_open_streams = true; + client_config_.SetMaxStreamsPerConnection(kNumMaxStreams, kNumMaxStreams); + } + + // Add a request with its response and |num_resources| push resources into + // cache. + // If |resource_size| == 0, response body of push resources use default string + // concatenating with resource url. Otherwise, generate a string of + // |resource_size| as body. + void AddRequestAndResponseWithServerPush(string host, + string path, + string response_body, + string* push_urls, + const size_t num_resources, + const size_t resource_size) { + bool use_large_response = resource_size != 0; + string large_resource; + if (use_large_response) { + // Generate a response common body larger than flow control window for + // push response. + test::GenerateBody(&large_resource, resource_size); + } + list<QuicInMemoryCache::ServerPushInfo> push_resources; + for (size_t i = 0; i < num_resources; ++i) { + string url = push_urls[i]; + GURL resource_url(url); + string body = use_large_response + ? large_resource + : "This is server push response body for " + url; + SpdyHeaderBlock response_headers; + response_headers[":version"] = "HTTP/1.1"; + response_headers[":status"] = "200"; + response_headers["content-length"] = IntToString(body.size()); + push_resources.push_back(QuicInMemoryCache::ServerPushInfo( + resource_url, response_headers, kV3LowestPriority, body)); + } + + QuicInMemoryCache::GetInstance()->AddSimpleResponseWithServerPushResources( + host, path, 200, response_body, push_resources); + } +}; + +TEST_P(EndToEndTestServerPush, ServerPush) { ASSERT_TRUE(Initialize()); client_->client()->WaitForCryptoHandshakeConfirmed(); @@ -2189,34 +2229,21 @@ SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2)); SetReorderPercentage(30); - // Add a response with headers, body, and trailers. + // Add a response with headers, body, and push resources. const string kBody = "body content"; - - list<QuicInMemoryCache::ServerPushInfo> push_resources; - + size_t kNumResources = 4; string push_urls[] = { "https://google.com/font.woff", "https://google.com/script.js", "https://fonts.google.com/font.woff", "https://google.com/logo-hires.jpg", }; - for (const string& url : push_urls) { - GURL resource_url(url); - string body = "This is server push response body for " + url; - SpdyHeaderBlock response_headers; - response_headers[":version"] = "HTTP/1.1"; - response_headers[":status"] = "200"; - response_headers["content-length"] = IntToString(body.size()); - push_resources.push_back(QuicInMemoryCache::ServerPushInfo( - resource_url, response_headers, kV3LowestPriority, body)); - } - - QuicInMemoryCache::GetInstance()->AddSimpleResponseWithServerPushResources( - "google.com", "/push_example", 200, kBody, push_resources); + AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody, + push_urls, kNumResources, 0); client_->client()->set_response_listener(new TestResponseListener); DVLOG(1) << "send request for /push_example"; - EXPECT_EQ(kBody, - client_->SendSynchronousRequest("https://google.com/push_example")); + EXPECT_EQ(kBody, client_->SendSynchronousRequest( + "https://example.com/push_example")); for (const string& url : push_urls) { DVLOG(1) << "send request for pushed stream on url " << url; string expected_body = "This is server push response body for " + url; @@ -2226,6 +2253,176 @@ } } +TEST_P(EndToEndTestServerPush, ServerPushUnderLimit) { + // Tests that sending a request which has 4 push resources will trigger server + // to push those 4 resources and client can handle pushed resources and match + // them with requests later. + ASSERT_TRUE(Initialize()); + + client_->client()->WaitForCryptoHandshakeConfirmed(); + + // Set reordering to ensure that body arriving before PUSH_PROMISE is ok. + SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2)); + SetReorderPercentage(30); + + // Add a response with headers, body, and push resources. + const string kBody = "body content"; + size_t const kNumResources = 4; + string push_urls[] = { + "https://example.com/font.woff", "https://example.com/script.js", + "https://fonts.example.com/font.woff", + "https://example.com/logo-hires.jpg", + }; + AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody, + push_urls, kNumResources, 0); + client_->client()->set_response_listener(new TestResponseListener); + + // Send the first request: this will trigger the server to send all the push + // resources associated with this request, and these will be cached by the + // client. + EXPECT_EQ(kBody, client_->SendSynchronousRequest( + "https://example.com/push_example")); + EXPECT_EQ(1u + kNumResources, client_->num_responses()); + + for (string url : push_urls) { + // Sending subsequent requesets will not actually send anything on the wire, + // as the responses are already in the client's cache. + DVLOG(1) << "send request for pushed stream on url " << url; + string expected_body = "This is server push response body for " + url; + string response_body = client_->SendSynchronousRequest(url); + DVLOG(1) << "response body " << response_body; + EXPECT_EQ(expected_body, response_body); + } + // Expect only original request has been sent and push responses have been + // received as normal response. + EXPECT_EQ(1u, client_->num_requests()); +} + +TEST_P(EndToEndTestServerPush, ServerPushOverLimitNonBlocking) { + // Tests that when streams are not blocked by flow control or congestion + // control, pushing even more resources than max number of open outgoing + // streams should still work because all response streams get closed + // immediately after pushing resources. + ASSERT_TRUE(Initialize()); + client_->client()->WaitForCryptoHandshakeConfirmed(); + + // Set reordering to ensure that body arriving before PUSH_PROMISE is ok. + SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2)); + SetReorderPercentage(30); + + // Add a response with headers, body, and push resources. + const string kBody = "body content"; + + // One more resource than max number of outgoing stream of this session. + const size_t kNumResources = 1 + kNumMaxStreams; // 11. + string push_urls[11]; + for (uint32_t i = 0; i < kNumResources; ++i) { + push_urls[i] = "https://example.com/push_resources" + base::UintToString(i); + } + AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody, + push_urls, kNumResources, 0); + client_->client()->set_response_listener(new TestResponseListener); + + // Send the first request: this will trigger the server to send all the push + // resources associated with this request, and these will be cached by the + // client. + EXPECT_EQ(kBody, client_->SendSynchronousRequest( + "https://example.com/push_example")); + // The responses to the original request and all the promised resources + // should have been received. + EXPECT_EQ(12u, client_->num_responses()); + + for (const string& url : push_urls) { + // Sending subsequent requesets will not actually send anything on the wire, + // as the responses are already in the client's cache. + EXPECT_EQ("This is server push response body for " + url, + client_->SendSynchronousRequest(url)); + } + + // Only 1 request should have been sent. + EXPECT_EQ(1u, client_->num_requests()); +} + +TEST_P(EndToEndTestServerPush, ServerPushOverLimitWithBlocking) { + // Tests that when server tries to send more large resources(large enough to + // be blocked by flow control window or congestion control window) than max + // open outgoing streams , server can open upto max number of outgoing + // streams for them, and the rest will be queued up. + + // Reset flow control windows. + size_t kFlowControlWnd = 20 * 1024; // 20KB. + // Response body is larger than 1 flow controlblock window. + size_t kBodySize = kFlowControlWnd * 2; + set_client_initial_stream_flow_control_receive_window(kFlowControlWnd); + // Make sure conntection level flow control window is large enough not to + // block data being sent out though they will be blocked by stream level one. + set_client_initial_session_flow_control_receive_window( + kBodySize * kNumMaxStreams + 1024); + + ASSERT_TRUE(Initialize()); + client_->client()->WaitForCryptoHandshakeConfirmed(); + + // Set reordering to ensure that body arriving before PUSH_PROMISE is ok. + SetPacketSendDelay(QuicTime::Delta::FromMilliseconds(2)); + SetReorderPercentage(30); + + // Add a response with headers, body, and push resources. + const string kBody = "body content"; + + const size_t kNumResources = kNumMaxStreams + 1; + string push_urls[11]; + for (uint32_t i = 0; i < kNumResources; ++i) { + push_urls[i] = "http://example.com/push_resources" + base::UintToString(i); + } + AddRequestAndResponseWithServerPush("example.com", "/push_example", kBody, + push_urls, kNumResources, kBodySize); + + client_->client()->set_response_listener(new TestResponseListener); + + client_->SendRequest("https://example.com/push_example"); + + // Pause after the first response arrives. + while (!client_->response_complete()) { + // Because of priority, the first response arrived should be to original + // request. + client_->WaitForResponse(); + } + + // Check server session to see if it has max number of outgoing streams opened + // though more resources need to be pushed. + server_thread_->Pause(); + QuicDispatcher* dispatcher = + QuicServerPeer::GetDispatcher(server_thread_->server()); + ASSERT_EQ(1u, dispatcher->session_map().size()); + QuicSession* session = dispatcher->session_map().begin()->second; + EXPECT_EQ(kNumMaxStreams, session->GetNumOpenOutgoingStreams()); + server_thread_->Resume(); + + EXPECT_EQ(1u, client_->num_requests()); + EXPECT_EQ(1u, client_->num_responses()); + EXPECT_EQ(kBody, client_->response_body()); + + // "Send" request for a promised resources will not really send out it because + // its response is being pushed(but blocked). And the following ack and + // flow control behavior of SendSynchronousRequests() + // will unblock the stream to finish receiving response. + client_->SendSynchronousRequest(push_urls[0]); + EXPECT_EQ(1u, client_->num_requests()); + EXPECT_EQ(2u, client_->num_responses()); + + // Do same thing for the rest 10 resources. + for (uint32_t i = 1; i < kNumResources; ++i) { + client_->SendSynchronousRequest(push_urls[i]); + } + + // Because of server push, client gets all pushed resources without actually + // sending requests for them. + EXPECT_EQ(1u, client_->num_requests()); + // Including response to original request, 12 responses in total were + // recieved. + EXPECT_EQ(12u, client_->num_responses()); +} + } // namespace } // namespace test } // namespace net
diff --git a/net/tools/quic/quic_client.cc b/net/tools/quic/quic_client.cc index b8472d0..56514ae 100644 --- a/net/tools/quic/quic_client.cc +++ b/net/tools/quic/quic_client.cc
@@ -74,9 +74,10 @@ initialized_(false), packets_dropped_(0), overflow_supported_(false), + use_recvmmsg_(false), store_response_(false), latest_response_code_(-1), - packet_reader_(CreateQuicPacketReader()) {} + packet_reader_(new QuicPacketReader()) {} QuicClient::~QuicClient() { if (connected()) { @@ -93,6 +94,14 @@ bool QuicClient::Initialize() { QuicClientBase::Initialize(); +#if MMSG_MORE + use_recvmmsg_ = true; +#endif + + set_num_sent_client_hellos(0); + set_num_stateless_rejects_received(0); + set_connection_error(QUIC_NO_ERROR); + // If an initial flow control window has not explicitly been set, then use the // same values that Chrome uses. const uint32_t kSessionMaxRecvWindowSize = 15 * 1024 * 1024; // 15 MB @@ -109,7 +118,7 @@ epoll_server_->set_timeout_in_us(50 * 1000); - if (!CreateUDPSocket()) { + if (!CreateUDPSocketAndBind()) { return false; } @@ -129,41 +138,17 @@ } } -bool QuicClient::CreateUDPSocket() { - int address_family = server_address_.GetSockAddrFamily(); - int fd = socket(address_family, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP); +bool QuicClient::CreateUDPSocketAndBind() { + int fd = + QuicSocketUtils::CreateUDPSocket(server_address_, &overflow_supported_); if (fd < 0) { - LOG(ERROR) << "CreateSocket() failed: " << strerror(errno); - return false; - } - - int get_overflow = 1; - int rc = setsockopt(fd, SOL_SOCKET, SO_RXQ_OVFL, &get_overflow, - sizeof(get_overflow)); - if (rc < 0) { - DLOG(WARNING) << "Socket overflow detection not supported"; - } else { - overflow_supported_ = true; - } - - if (!QuicSocketUtils::SetReceiveBufferSize(fd, kDefaultSocketReceiveBuffer)) { - return false; - } - - if (!QuicSocketUtils::SetSendBufferSize(fd, kDefaultSocketReceiveBuffer)) { - return false; - } - - rc = QuicSocketUtils::SetGetAddressInfo(fd, address_family); - if (rc < 0) { - LOG(ERROR) << "IP detection not supported" << strerror(errno); return false; } IPEndPoint client_address; if (bind_to_address_.size() != 0) { client_address = IPEndPoint(bind_to_address_, local_port_); - } else if (address_family == AF_INET) { + } else if (server_address_.GetSockAddrFamily() == AF_INET) { client_address = IPEndPoint(IPAddress(0, 0, 0, 0), local_port_); } else { IPAddress any6; @@ -175,7 +160,8 @@ socklen_t raw_addr_len = sizeof(raw_addr); CHECK(client_address.ToSockAddr(reinterpret_cast<sockaddr*>(&raw_addr), &raw_addr_len)); - rc = bind(fd, reinterpret_cast<const sockaddr*>(&raw_addr), sizeof(raw_addr)); + int rc = + bind(fd, reinterpret_cast<const sockaddr*>(&raw_addr), sizeof(raw_addr)); if (rc < 0) { LOG(ERROR) << "Bind failed: " << strerror(errno); return false; @@ -390,7 +376,7 @@ CleanUpUDPSocket(GetLatestFD()); bind_to_address_ = new_host; - if (!CreateUDPSocket()) { + if (!CreateUDPSocketAndBind()) { return false; } @@ -408,15 +394,16 @@ DCHECK_EQ(fd, GetLatestFD()); if (event->in_events & EPOLLIN) { - while (connected()) { - if ( -#if MMSG_MORE - !ReadAndProcessPackets() -#else - !ReadAndProcessPacket() -#endif - ) { - break; + bool more_to_read = true; + while (connected() && more_to_read) { + if (use_recvmmsg_) { + more_to_read = packet_reader_->ReadAndDispatchPackets( + GetLatestFD(), QuicClient::GetLatestClientAddress().port(), this, + overflow_supported_ ? &packets_dropped_ : nullptr); + } else { + more_to_read = QuicPacketReader::ReadAndDispatchSinglePacket( + GetLatestFD(), QuicClient::GetLatestClientAddress().port(), this, + overflow_supported_ ? &packets_dropped_ : nullptr); } } } @@ -492,53 +479,6 @@ return new QuicDefaultPacketWriter(GetLatestFD()); } -QuicPacketReader* QuicClient::CreateQuicPacketReader() { - // TODO(rtenneti): Add support for QuicPacketReader. - // return new QuicPacketReader(); - return nullptr; -} - -int QuicClient::ReadPacket(char* buffer, - int buffer_len, - IPEndPoint* server_address, - IPAddress* client_ip) { - return QuicSocketUtils::ReadPacket( - GetLatestFD(), buffer, buffer_len, - overflow_supported_ ? &packets_dropped_ : nullptr, client_ip, - server_address); -} - -bool QuicClient::ReadAndProcessPacket() { - // Allocate some extra space so we can send an error if the server goes over - // the limit. - char buf[2 * kMaxPacketSize]; - - IPEndPoint server_address; - IPAddress client_ip; - - int bytes_read = ReadPacket(buf, arraysize(buf), &server_address, &client_ip); - - if (bytes_read < 0) { - return false; - } - - QuicEncryptedPacket packet(buf, bytes_read, false); - - IPEndPoint client_address(client_ip, - QuicClient::GetLatestClientAddress().port()); - - session()->ProcessUdpPacket(client_address, server_address, packet); - return true; -} - -/* -bool QuicClient::ReadAndProcessPackets() { - return packet_reader_->ReadAndDispatchPackets( - GetLatestFD(), QuicClient::GetLatestClientAddress().port(), this, - overflow_supported_ ? &packets_dropped_ : nullptr); -} -*/ - const IPEndPoint QuicClient::GetLatestClientAddress() const { if (fd_address_map_.empty()) { return IPEndPoint();
diff --git a/net/tools/quic/quic_client.h b/net/tools/quic/quic_client.h index 5dff8cfe..8b573552 100644 --- a/net/tools/quic/quic_client.h +++ b/net/tools/quic/quic_client.h
@@ -25,6 +25,7 @@ #include "net/tools/epoll_server/epoll_server.h" #include "net/tools/quic/quic_client_base.h" #include "net/tools/quic/quic_client_session.h" +#include "net/tools/quic/quic_packet_reader.h" #include "net/tools/quic/quic_process_packet_interface.h" namespace net { @@ -32,7 +33,6 @@ class QuicServerId; class QuicEpollConnectionHelper; -class QuicPacketReader; namespace test { class QuicClientPeer; @@ -193,14 +193,7 @@ return &push_promise_index_; } - protected: virtual QuicPacketWriter* CreateQuicPacketWriter(); - virtual QuicPacketReader* CreateQuicPacketReader(); - - virtual int ReadPacket(char* buffer, - int buffer_len, - IPEndPoint* server_address, - IPAddress* client_ip); // If |fd| is an open UDP socket, unregister and close it. Otherwise, do // nothing. @@ -243,19 +236,11 @@ // Used during initialization: creates the UDP socket FD, sets socket options, // and binds the socket to our address. - bool CreateUDPSocket(); + bool CreateUDPSocketAndBind(); // Actually clean up |fd|. void CleanUpUDPSocketImpl(int fd); - // Read a UDP packet and hand it to the framer. - bool ReadAndProcessPacket(); - - // Read available UDP packets up to kNumPacketsPerReadCall - // and hand them to the connection. - // TODO(rtenneti): Add support for ReadAndProcessPackets(). - // bool ReadAndProcessPackets(); - // If the request URL matches a push promise, bypass sending the // request. bool MaybeHandlePromised(const BalsaHeaders& headers, @@ -296,6 +281,9 @@ // because the socket would otherwise overflow. bool overflow_supported_; + // If true, use recvmmsg for reading. + bool use_recvmmsg_; + // If true, store the latest response code, headers, and body. bool store_response_; // HTTP response code from most recent response. @@ -319,7 +307,7 @@ // // TODO(rtenneti): Chromium code doesn't use |packet_reader_|. Add support for // QuicPacketReader - QuicPacketReader* packet_reader_; + scoped_ptr<QuicPacketReader> packet_reader_; std::unique_ptr<ClientQuicDataToResend> push_promise_data_to_resend_;
diff --git a/net/tools/quic/quic_client_base.h b/net/tools/quic/quic_client_base.h index 738eb1ec..206dd1a5 100644 --- a/net/tools/quic/quic_client_base.h +++ b/net/tools/quic/quic_client_base.h
@@ -170,6 +170,14 @@ QuicConnectionHelperInterface* helper() { return helper_.get(); } + void set_num_sent_client_hellos(int num_sent_client_hellos) { + num_sent_client_hellos_ = num_sent_client_hellos; + } + + void set_num_stateless_rejects_received(int num_stateless_rejects_received) { + num_stateless_rejects_received_ = num_stateless_rejects_received; + } + private: // |server_id_| is a tuple (hostname, port, is_https) of the server. QuicServerId server_id_;
diff --git a/net/tools/quic/quic_client_bin.cc b/net/tools/quic/quic_client_bin.cc index 6b31baa..ead19bae 100644 --- a/net/tools/quic/quic_client_bin.cc +++ b/net/tools/quic/quic_client_bin.cc
@@ -160,8 +160,6 @@ settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; CHECK(logging::InitLogging(settings)); - FLAGS_quic_supports_trailers = true; - if (line->HasSwitch("h") || line->HasSwitch("help") || urls.empty()) { const char* help_str = "Usage: quic_client [options] <url>\n"
diff --git a/net/tools/quic/quic_client_session.cc b/net/tools/quic/quic_client_session.cc index ba0f0ed..280f3f8 100644 --- a/net/tools/quic/quic_client_session.cc +++ b/net/tools/quic/quic_client_session.cc
@@ -110,6 +110,7 @@ } QuicSpdyStream* stream = new QuicSpdyClientStream(id, this); stream->CloseWriteSide(); + ActivateStream(stream); return stream; }
diff --git a/net/tools/quic/quic_client_session_test.cc b/net/tools/quic/quic_client_session_test.cc index b6cae394..ac65bf59 100644 --- a/net/tools/quic/quic_client_session_test.cc +++ b/net/tools/quic/quic_client_session_test.cc
@@ -69,7 +69,9 @@ MockQuicSpdyClientStream* CreateIncomingDynamicStream( QuicStreamId id) override { - return new MockQuicSpdyClientStream(id, this); + MockQuicSpdyClientStream* stream = new MockQuicSpdyClientStream(id, this); + ActivateStream(stream); + return stream; } }; @@ -231,28 +233,6 @@ EXPECT_EQ(nullptr, session_->CreateOutgoingDynamicStream(kDefaultPriority)); } -TEST_P(QuicClientSessionTest, SetFecProtectionFromConfig) { - ValueRestore<bool> old_flag(&FLAGS_enable_quic_fec, true); - - // Set FEC config in client's connection options. - QuicTagVector copt; - copt.push_back(kFHDR); - session_->config()->SetConnectionOptionsToSend(copt); - - // Doing the handshake should set up FEC config correctly. - CompleteCryptoHandshake(); - - // Verify that headers stream is always protected and data streams are - // optionally protected. - EXPECT_EQ( - FEC_PROTECT_ALWAYS, - QuicSpdySessionPeer::GetHeadersStream(session_.get())->fec_policy()); - QuicSpdyClientStream* stream = - session_->CreateOutgoingDynamicStream(kDefaultPriority); - ASSERT_TRUE(stream); - EXPECT_EQ(FEC_PROTECT_OPTIONAL, stream->fec_policy()); -} - static bool CheckForDecryptionError(QuicFramer* framer) { return framer->error() == QUIC_DECRYPTION_FAILURE; }
diff --git a/net/tools/quic/quic_client_test.cc b/net/tools/quic/quic_client_test.cc index eed3004..373a2d8 100644 --- a/net/tools/quic/quic_client_test.cc +++ b/net/tools/quic/quic_client_test.cc
@@ -88,9 +88,9 @@ CreateAndInitializeQuicClient(&eps, net::test::kTestPort)); EXPECT_EQ(number_of_open_fds + 1, NumOpenFDs()); // Create more UDP sockets. - EXPECT_TRUE(QuicClientPeer::CreateUDPSocket(client.get())); + EXPECT_TRUE(QuicClientPeer::CreateUDPSocketAndBind(client.get())); EXPECT_EQ(number_of_open_fds + 2, NumOpenFDs()); - EXPECT_TRUE(QuicClientPeer::CreateUDPSocket(client.get())); + EXPECT_TRUE(QuicClientPeer::CreateUDPSocketAndBind(client.get())); EXPECT_EQ(number_of_open_fds + 3, NumOpenFDs()); // Clean up UDP sockets.
diff --git a/net/tools/quic/quic_dispatcher.cc b/net/tools/quic/quic_dispatcher.cc index 28c31a8..9cb1059aa 100644 --- a/net/tools/quic/quic_dispatcher.cc +++ b/net/tools/quic/quic_dispatcher.cc
@@ -90,6 +90,8 @@ bool QuicDispatcher::OnUnauthenticatedPublicHeader( const QuicPacketPublicHeader& header) { + current_connection_id_ = header.connection_id; + // Port zero is only allowed for unidirectional UDP, so is disallowed by QUIC. // Given that we can't even send a reply rejecting the packet, just drop the // packet. @@ -137,12 +139,24 @@ if (framer_.IsSupportedVersion(packet_version)) { version = packet_version; } else { - // Packets set to be processed but having an unsupported version will - // cause a connection to be created. The connection will handle - // sending a version negotiation packet. - // TODO(ianswett): This will malfunction if the full header of the packet - // causes a parsing error when parsed using the server's preferred - // version. + if (FLAGS_quic_stateless_version_negotiation) { + if (ShouldCreateSessionForUnknownVersion(framer_.last_version_tag())) { + return true; + } + // Since the version is not supported, send a version negotiation + // packet and stop processing the current packet. + time_wait_list_manager()->SendVersionNegotiationPacket( + connection_id, supported_versions_, current_server_address_, + current_client_address_); + return false; + } else { + // Packets set to be processed but having an unsupported version will + // cause a connection to be created. The connection will handle + // sending a version negotiation packet. + // TODO(ianswett): This will malfunction if the full header of the + // packet causes a parsing error when parsed using the server's + // preferred version. + } } } // Set the framer's version and continue processing. @@ -334,8 +348,21 @@ DVLOG(1) << QuicUtils::ErrorToString(error); } +bool QuicDispatcher::ShouldCreateSessionForUnknownVersion(QuicTag version_tag) { + return false; +} + bool QuicDispatcher::OnProtocolVersionMismatch( QuicVersion /*received_version*/) { + if (FLAGS_quic_stateless_version_negotiation) { + QUIC_BUG_IF( + !time_wait_list_manager_->IsConnectionIdInTimeWait( + current_connection_id_) && + !ShouldCreateSessionForUnknownVersion(framer_.last_version_tag())) + << "Unexpected version mismatch: " + << QuicUtils::TagToString(framer_.last_version_tag()); + } + // Keep processing after protocol mismatch - this will be dealt with by the // time wait list or connection that we will create. return true;
diff --git a/net/tools/quic/quic_dispatcher.h b/net/tools/quic/quic_dispatcher.h index 6b8f5e5..3a96176a 100644 --- a/net/tools/quic/quic_dispatcher.h +++ b/net/tools/quic/quic_dispatcher.h
@@ -203,6 +203,10 @@ // cleaned up for bug 16950226.) virtual QuicPacketWriter* CreatePerConnectionWriter(); + // Returns true if a session should be created for a connection with an + // unknown version identified by |version_tag|. + virtual bool ShouldCreateSessionForUnknownVersion(QuicTag version_tag); + void SetLastError(QuicErrorCode error); private: @@ -249,6 +253,7 @@ IPEndPoint current_client_address_; IPEndPoint current_server_address_; const QuicEncryptedPacket* current_packet_; + QuicConnectionId current_connection_id_; QuicFramer framer_;
diff --git a/net/tools/quic/quic_dispatcher_test.cc b/net/tools/quic/quic_dispatcher_test.cc index 3064261..169dc63 100644 --- a/net/tools/quic/quic_dispatcher_test.cc +++ b/net/tools/quic/quic_dispatcher_test.cc
@@ -164,6 +164,9 @@ return reinterpret_cast<MockConnection*>(session2_->connection()); } + // Process a packet with an 8 byte connection id, + // 6 byte packet number, default path id, and packet number 1, + // using the first supported version. void ProcessPacket(IPEndPoint client_address, QuicConnectionId connection_id, bool has_version_flag, @@ -174,6 +177,8 @@ PACKET_6BYTE_PACKET_NUMBER); } + // Process a packet with a default path id, and packet number 1, + // using the first supported version. void ProcessPacket(IPEndPoint client_address, QuicConnectionId connection_id, bool has_version_flag, @@ -186,6 +191,7 @@ packet_number_length, kDefaultPathId, 1); } + // Process a packet using the first supported version. void ProcessPacket(IPEndPoint client_address, QuicConnectionId connection_id, bool has_version_flag, @@ -195,9 +201,25 @@ QuicPacketNumberLength packet_number_length, QuicPathId path_id, QuicPacketNumber packet_number) { + ProcessPacket(client_address, connection_id, has_version_flag, + QuicSupportedVersions().front(), data, connection_id_length, + packet_number_length, packet_number); + } + + // Processes a packet. + void ProcessPacket(IPEndPoint client_address, + QuicConnectionId connection_id, + bool has_version_flag, + QuicVersion version, + const string& data, + QuicConnectionIdLength connection_id_length, + QuicPacketNumberLength packet_number_length, + QuicPacketNumber packet_number) { + QuicVersionVector versions(SupportedVersions(version)); scoped_ptr<QuicEncryptedPacket> packet(ConstructEncryptedPacket( - connection_id, has_version_flag, has_multipath_flag, false, path_id, - packet_number, data, connection_id_length, packet_number_length)); + connection_id, has_version_flag, false, false, 0, packet_number, data, + connection_id_length, packet_number_length, &versions)); + data_ = string(packet->data(), packet->length()); dispatcher_.ProcessPacket(server_address_, client_address, *packet); } @@ -254,6 +276,31 @@ ProcessPacket(client_address, 1, false, false, "eep"); } +TEST_F(QuicDispatcherTest, StatelessVersionNegotiation) { + ValueRestore<bool> old_flag(&FLAGS_quic_stateless_version_negotiation, true); + IPEndPoint client_address(net::test::Loopback4(), 1); + server_address_ = IPEndPoint(net::test::Any4(), 5); + + EXPECT_CALL(dispatcher_, CreateQuicSession(1, client_address)).Times(0); + QuicVersion version = static_cast<QuicVersion>(QuicVersionMin() - 1); + ProcessPacket(client_address, 1, true, version, "foo", + PACKET_8BYTE_CONNECTION_ID, PACKET_6BYTE_PACKET_NUMBER, 1); +} + +TEST_F(QuicDispatcherTest, StatefulVersionNegotiation) { + ValueRestore<bool> old_flag(&FLAGS_quic_stateless_version_negotiation, false); + IPEndPoint client_address(net::test::Loopback4(), 1); + server_address_ = IPEndPoint(net::test::Any4(), 5); + + EXPECT_CALL(dispatcher_, CreateQuicSession(1, client_address)) + .WillOnce(testing::Return(CreateSession(&dispatcher_, config_, 1, + client_address, &mock_helper_, + &crypto_config_, &session1_))); + QuicVersion version = static_cast<QuicVersion>(QuicVersionMin() - 1); + ProcessPacket(client_address, 1, true, version, "foo", + PACKET_8BYTE_CONNECTION_ID, PACKET_6BYTE_PACKET_NUMBER, 1); +} + TEST_F(QuicDispatcherTest, Shutdown) { IPEndPoint client_address(net::test::Loopback4(), 1);
diff --git a/net/tools/quic/quic_server.cc b/net/tools/quic/quic_server.cc index 8af7eba..9b14424 100644 --- a/net/tools/quic/quic_server.cc +++ b/net/tools/quic/quic_server.cc
@@ -107,51 +107,18 @@ QuicServer::~QuicServer() {} -bool QuicServer::Listen(const IPEndPoint& address) { - port_ = address.port(); - int address_family = address.GetSockAddrFamily(); - fd_ = socket(address_family, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP); +bool QuicServer::CreateUDPSocketAndListen(const IPEndPoint& address) { + fd_ = QuicSocketUtils::CreateUDPSocket(address, &overflow_supported_); if (fd_ < 0) { LOG(ERROR) << "CreateSocket() failed: " << strerror(errno); return false; } - // Enable the socket option that allows the local address to be - // returned if the socket is bound to more than one address. - int rc = QuicSocketUtils::SetGetAddressInfo(fd_, address_family); - - if (rc < 0) { - LOG(ERROR) << "IP detection not supported" << strerror(errno); - return false; - } - - int get_overflow = 1; - rc = setsockopt(fd_, SOL_SOCKET, SO_RXQ_OVFL, &get_overflow, - sizeof(get_overflow)); - - if (rc < 0) { - DLOG(WARNING) << "Socket overflow detection not supported"; - } else { - overflow_supported_ = true; - } - - // These send and receive buffer sizes are sized for a single connection, - // because the default usage of QuicServer is as a test server with one or - // two clients. Adjust higher for use with many clients. - if (!QuicSocketUtils::SetReceiveBufferSize(fd_, - kDefaultSocketReceiveBuffer)) { - return false; - } - - if (!QuicSocketUtils::SetSendBufferSize(fd_, kDefaultSocketReceiveBuffer)) { - return false; - } - sockaddr_storage raw_addr; socklen_t raw_addr_len = sizeof(raw_addr); CHECK(address.ToSockAddr(reinterpret_cast<sockaddr*>(&raw_addr), &raw_addr_len)); - rc = + int rc = bind(fd_, reinterpret_cast<const sockaddr*>(&raw_addr), sizeof(raw_addr)); if (rc < 0) { LOG(ERROR) << "Bind failed: " << strerror(errno);
diff --git a/net/tools/quic/quic_server.h b/net/tools/quic/quic_server.h index ca2a2b5..49718db 100644 --- a/net/tools/quic/quic_server.h +++ b/net/tools/quic/quic_server.h
@@ -43,7 +43,7 @@ ~QuicServer() override; // Start listening on the specified address. - bool Listen(const IPEndPoint& address); + bool CreateUDPSocketAndListen(const IPEndPoint& address); // Wait up to 50ms, and handle any events which occur. void WaitForEvents(); @@ -130,6 +130,8 @@ // skipped as necessary). QuicVersionVector supported_versions_; + // Point to a QuicPacketReader object on the heap. The reader allocates more + // space than allowed on the stack. scoped_ptr<QuicPacketReader> packet_reader_; DISALLOW_COPY_AND_ASSIGN(QuicServer);
diff --git a/net/tools/quic/quic_server_bin.cc b/net/tools/quic/quic_server_bin.cc index 1b9e15837..a6a3341 100644 --- a/net/tools/quic/quic_server_bin.cc +++ b/net/tools/quic/quic_server_bin.cc
@@ -88,7 +88,7 @@ net::QuicSupportedVersions()); server.SetStrikeRegisterNoStartupPeriod(); - int rc = server.Listen(net::IPEndPoint(ip, FLAGS_port)); + int rc = server.CreateUDPSocketAndListen(net::IPEndPoint(ip, FLAGS_port)); if (rc < 0) { return 1; }
diff --git a/net/tools/quic/quic_server_session_base.cc b/net/tools/quic/quic_server_session_base.cc index 2d083131..63618d41 100644 --- a/net/tools/quic/quic_server_session_base.cc +++ b/net/tools/quic/quic_server_session_base.cc
@@ -71,13 +71,6 @@ } } } - - if (FLAGS_enable_quic_fec && - ContainsQuicTag(config()->ReceivedConnectionOptions(), kFHDR)) { - // kFHDR config maps to FEC protection always for headers stream. - // TODO(jri): Add crypto stream in addition to headers for kHDR. - headers_stream()->set_fec_policy(FEC_PROTECT_ALWAYS); - } } void QuicServerSessionBase::OnConnectionClosed(QuicErrorCode error,
diff --git a/net/tools/quic/quic_server_session_base_test.cc b/net/tools/quic/quic_server_session_base_test.cc index cab37377..1d4ed11 100644 --- a/net/tools/quic/quic_server_session_base_test.cc +++ b/net/tools/quic/quic_server_session_base_test.cc
@@ -83,7 +83,9 @@ if (!ShouldCreateIncomingDynamicStream(id)) { return nullptr; } - return new QuicSimpleServerStream(id, this); + QuicSpdyStream* stream = new QuicSimpleServerStream(id, this); + ActivateStream(stream); + return stream; } QuicSpdyStream* CreateOutgoingDynamicStream(SpdyPriority priority) override { @@ -325,27 +327,6 @@ "ShouldCreateIncomingDynamicStream called when disconnected"); } -TEST_P(QuicServerSessionBaseTest, SetFecProtectionFromConfig) { - ValueRestore<bool> old_flag(&FLAGS_enable_quic_fec, true); - - // Set received config to have FEC connection option. - QuicTagVector copt; - copt.push_back(kFHDR); - QuicConfigPeer::SetReceivedConnectionOptions(session_->config(), copt); - session_->OnConfigNegotiated(); - - // Verify that headers stream is always protected and data streams are - // optionally protected. - EXPECT_EQ( - FEC_PROTECT_ALWAYS, - QuicSpdySessionPeer::GetHeadersStream(session_.get())->fec_policy()); - ReliableQuicStream* stream = - QuicServerSessionBasePeer::GetOrCreateDynamicStream(session_.get(), - kClientDataStreamId1); - ASSERT_TRUE(stream); - EXPECT_EQ(FEC_PROTECT_OPTIONAL, stream->fec_policy()); -} - class MockQuicCryptoServerStream : public QuicCryptoServerStream { public: explicit MockQuicCryptoServerStream(
diff --git a/net/tools/quic/quic_simple_client_bin.cc b/net/tools/quic/quic_simple_client_bin.cc index 2baf3eb..d7f5ef5 100644 --- a/net/tools/quic/quic_simple_client_bin.cc +++ b/net/tools/quic/quic_simple_client_bin.cc
@@ -160,8 +160,6 @@ settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; CHECK(logging::InitLogging(settings)); - FLAGS_quic_supports_trailers = true; - if (line->HasSwitch("h") || line->HasSwitch("help") || urls.empty()) { const char* help_str = "Usage: quic_client [options] <url>\n"
diff --git a/net/tools/quic/quic_simple_server_session.cc b/net/tools/quic/quic_simple_server_session.cc index 5a2619a..e72383a 100644 --- a/net/tools/quic/quic_simple_server_session.cc +++ b/net/tools/quic/quic_simple_server_session.cc
@@ -73,7 +73,9 @@ return nullptr; } - return new QuicSimpleServerStream(id, this); + QuicSpdyStream* stream = new QuicSimpleServerStream(id, this); + ActivateStream(stream); + return stream; } QuicSimpleServerStream* QuicSimpleServerSession::CreateOutgoingDynamicStream(
diff --git a/net/tools/quic/quic_simple_server_session_test.cc b/net/tools/quic/quic_simple_server_session_test.cc index 6dd65dad..e6dcdc9 100644 --- a/net/tools/quic/quic_simple_server_session_test.cc +++ b/net/tools/quic/quic_simple_server_session_test.cc
@@ -282,9 +282,9 @@ } TEST_P(QuicSimpleServerSessionTest, CreateIncomingDynamicStream) { - std::unique_ptr<QuicSpdyStream> stream( + QuicSpdyStream* stream = QuicSimpleServerSessionPeer::CreateIncomingDynamicStream( - session_.get(), kClientDataStreamId1)); + session_.get(), kClientDataStreamId1); EXPECT_NE(nullptr, stream); EXPECT_EQ(kClientDataStreamId1, stream->id()); }
diff --git a/net/tools/quic/quic_socket_utils.cc b/net/tools/quic/quic_socket_utils.cc index 36c5fb4..42141dfa 100644 --- a/net/tools/quic/quic_socket_utils.cc +++ b/net/tools/quic/quic_socket_utils.cc
@@ -223,4 +223,39 @@ errno); } +// static +int QuicSocketUtils::CreateUDPSocket(const IPEndPoint& address, + bool* overflow_supported) { + int address_family = address.GetSockAddrFamily(); + int fd = socket(address_family, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP); + if (fd < 0) { + LOG(ERROR) << "socket() failed: " << strerror(errno); + return -1; + } + + int get_overflow = 1; + int rc = setsockopt(fd, SOL_SOCKET, SO_RXQ_OVFL, &get_overflow, + sizeof(get_overflow)); + if (rc < 0) { + DLOG(WARNING) << "Socket overflow detection not supported"; + } else { + *overflow_supported = true; + } + + if (!QuicSocketUtils::SetReceiveBufferSize(fd, kDefaultSocketReceiveBuffer)) { + return -1; + } + + if (!QuicSocketUtils::SetSendBufferSize(fd, kDefaultSocketReceiveBuffer)) { + return -1; + } + + rc = QuicSocketUtils::SetGetAddressInfo(fd, address_family); + if (rc < 0) { + LOG(ERROR) << "IP detection not supported" << strerror(errno); + return -1; + } + return fd; +} + } // namespace net
diff --git a/net/tools/quic/quic_socket_utils.h b/net/tools/quic/quic_socket_utils.h index 8a0e4420..a464089 100644 --- a/net/tools/quic/quic_socket_utils.h +++ b/net/tools/quic/quic_socket_utils.h
@@ -72,6 +72,12 @@ // Returns the length of the packet info structure used. static size_t SetIpInfoInCmsg(const IPAddress& self_address, cmsghdr* cmsg); + // Creates a UDP socket and sets appropriate socket options for QUIC. + // Returns the created FD if successful, -1 otherwise. + // |overflow_supported| is set to true if the socket supports it. + static int CreateUDPSocket(const IPEndPoint& address, + bool* overflow_supported); + private: DISALLOW_COPY_AND_ASSIGN(QuicSocketUtils); };
diff --git a/net/tools/quic/quic_spdy_client_stream_test.cc b/net/tools/quic/quic_spdy_client_stream_test.cc index f2e6fed..715fda0 100644 --- a/net/tools/quic/quic_spdy_client_stream_test.cc +++ b/net/tools/quic/quic_spdy_client_stream_test.cc
@@ -144,8 +144,6 @@ TEST_F(QuicSpdyClientStreamTest, ReceivingTrailers) { // Test that receiving trailing headers, containing a final offset, results in // the stream being closed at that byte offset. - ValueRestore<bool> old_flag(&FLAGS_quic_supports_trailers, true); - // Send headers as usual. stream_->OnStreamHeaders(headers_string_); stream_->OnStreamHeadersComplete(false, headers_string_.size());
diff --git a/net/tools/quic/quic_time_wait_list_manager.cc b/net/tools/quic/quic_time_wait_list_manager.cc index 3b50f2d..64ff05e 100644 --- a/net/tools/quic/quic_time_wait_list_manager.cc +++ b/net/tools/quic/quic_time_wait_list_manager.cc
@@ -190,6 +190,17 @@ SendPublicReset(server_address, client_address, connection_id, packet_number); } +void QuicTimeWaitListManager::SendVersionNegotiationPacket( + QuicConnectionId connection_id, + const QuicVersionVector& supported_versions, + const IPEndPoint& server_address, + const IPEndPoint& client_address) { + QueuedPacket* packet = new QueuedPacket( + server_address, client_address, QuicFramer::BuildVersionNegotiationPacket( + connection_id, supported_versions)); + SendOrQueuePacket(packet); +} + // Returns true if the number of packets received for this connection_id is a // power of 2 to throttle the number of public reset packets we send to a // client.
diff --git a/net/tools/quic/quic_time_wait_list_manager.h b/net/tools/quic/quic_time_wait_list_manager.h index 51df345d..52e1d62 100644 --- a/net/tools/quic/quic_time_wait_list_manager.h +++ b/net/tools/quic/quic_time_wait_list_manager.h
@@ -98,6 +98,14 @@ // The number of connections on the time-wait list. size_t num_connections() const { return connection_id_map_.size(); } + // Sends a version negotiation packet for |connection_id| announcing support + // for |supported_versions| to |client_address| from |server_address|. + virtual void SendVersionNegotiationPacket( + QuicConnectionId connection_id, + const QuicVersionVector& supported_versions, + const IPEndPoint& server_address, + const IPEndPoint& client_address); + protected: virtual QuicEncryptedPacket* BuildPublicReset( const QuicPublicResetPacket& packet);
diff --git a/net/tools/quic/quic_time_wait_list_manager_test.cc b/net/tools/quic/quic_time_wait_list_manager_test.cc index 9607847..12cb7fb 100644 --- a/net/tools/quic/quic_time_wait_list_manager_test.cc +++ b/net/tools/quic/quic_time_wait_list_manager_test.cc
@@ -218,6 +218,21 @@ EXPECT_TRUE(IsConnectionIdInTimeWait(connection_id_)); } +TEST_F(QuicTimeWaitListManagerTest, SendVersionNegotiationPacket) { + scoped_ptr<QuicEncryptedPacket> packet( + QuicFramer::BuildVersionNegotiationPacket(connection_id_, + QuicSupportedVersions())); + EXPECT_CALL(writer_, + WritePacket(_, packet->length(), server_address_.address(), + client_address_, _)) + .WillOnce(Return(WriteResult(WRITE_STATUS_OK, 1))); + + time_wait_list_manager_.SendVersionNegotiationPacket( + connection_id_, QuicSupportedVersions(), server_address_, + client_address_); + EXPECT_EQ(0u, time_wait_list_manager_.num_connections()); +} + TEST_F(QuicTimeWaitListManagerTest, SendConnectionClose) { const size_t kConnectionCloseLength = 100; EXPECT_CALL(visitor_, OnConnectionAddedToTimeWaitList(connection_id_));
diff --git a/net/tools/quic/spdy_balsa_utils.cc b/net/tools/quic/spdy_balsa_utils.cc index d6132f9..dd24c99 100644 --- a/net/tools/quic/spdy_balsa_utils.cc +++ b/net/tools/quic/spdy_balsa_utils.cc
@@ -227,16 +227,16 @@ if (url.empty() || url[0] == '/') { path = url; } else { - GURL request_uri(url); + std::unique_ptr<GURL> request_uri(new GURL(url)); if (request_headers.request_method() == "CONNECT") { path = url; } else { - path = request_uri.path(); - if (!request_uri.query().empty()) { - path = path + "?" + request_uri.query(); + path = request_uri->path(); + if (!request_uri->query().empty()) { + path = path + "?" + request_uri->query(); } - host_and_port = request_uri.host(); - scheme = request_uri.scheme(); + host_and_port = request_uri->host(); + scheme = request_uri->scheme(); } }
diff --git a/net/tools/quic/test_tools/mock_quic_time_wait_list_manager.h b/net/tools/quic/test_tools/mock_quic_time_wait_list_manager.h index 2cf5f83..5d5542b 100644 --- a/net/tools/quic/test_tools/mock_quic_time_wait_list_manager.h +++ b/net/tools/quic/test_tools/mock_quic_time_wait_list_manager.h
@@ -42,6 +42,12 @@ QuicConnectionId connection_id, QuicPacketNumber packet_number, const QuicEncryptedPacket& packet)); + + MOCK_METHOD4(SendVersionNegotiationPacket, + void(QuicConnectionId connection_id, + const QuicVersionVector& supported_versions, + const IPEndPoint& server_address, + const IPEndPoint& client_address)); }; } // namespace test
diff --git a/net/tools/quic/test_tools/quic_client_peer.cc b/net/tools/quic/test_tools/quic_client_peer.cc index f4a1512..71d3520f 100644 --- a/net/tools/quic/test_tools/quic_client_peer.cc +++ b/net/tools/quic/test_tools/quic_client_peer.cc
@@ -10,8 +10,8 @@ namespace test { // static -bool QuicClientPeer::CreateUDPSocket(QuicClient* client) { - return client->CreateUDPSocket(); +bool QuicClientPeer::CreateUDPSocketAndBind(QuicClient* client) { + return client->CreateUDPSocketAndBind(); } // static
diff --git a/net/tools/quic/test_tools/quic_client_peer.h b/net/tools/quic/test_tools/quic_client_peer.h index eb163dc..4d249a30 100644 --- a/net/tools/quic/test_tools/quic_client_peer.h +++ b/net/tools/quic/test_tools/quic_client_peer.h
@@ -19,7 +19,7 @@ class QuicClientPeer { public: - static bool CreateUDPSocket(QuicClient* client); + static bool CreateUDPSocketAndBind(QuicClient* client); static void CleanUpUDPSocket(QuicClient* client, int fd); static void SetClientPort(QuicClient* client, int port);
diff --git a/net/tools/quic/test_tools/quic_test_client.cc b/net/tools/quic/test_tools/quic_test_client.cc index 7e6d413..cf1abec 100644 --- a/net/tools/quic/test_tools/quic_test_client.cc +++ b/net/tools/quic/test_tools/quic_test_client.cc
@@ -181,7 +181,9 @@ config, supported_versions, &epoll_server_)), - allow_bidirectional_data_(false) { + allow_bidirectional_data_(false), + num_requests_(0), + num_responses_(0) { Initialize(); } @@ -273,6 +275,7 @@ spdy_headers[":authority"] = client_->server_id().host(); } ret = stream->SendRequest(spdy_headers, body, fin); + ++num_requests_; } else { stream->SendBody(body.as_string(), fin, delegate); ret = body.length(); @@ -576,6 +579,7 @@ response_header_size_ = headers_.GetSizeForWriteBuffer(); response_body_size_ = stream_->data().size(); stream_ = nullptr; + ++num_responses_; } bool QuicTestClient::CheckVary(const SpdyHeaderBlock& client_request,
diff --git a/net/tools/quic/test_tools/quic_test_client.h b/net/tools/quic/test_tools/quic_test_client.h index df38ad5..6dc3ea5e 100644 --- a/net/tools/quic/test_tools/quic_test_client.h +++ b/net/tools/quic/test_tools/quic_test_client.h
@@ -199,6 +199,10 @@ bool allow_bidirectional_data() const { return allow_bidirectional_data_; } + size_t num_requests() const { return num_requests_; } + + size_t num_responses() const { return num_responses_; } + protected: QuicTestClient(); @@ -269,6 +273,9 @@ // For async push promise rendezvous, validation may fail in which // case the request should be retried. std::unique_ptr<TestClientDataToResend> push_promise_data_to_resend_; + // Number of requests/responses this client has sent/received. + size_t num_requests_; + size_t num_responses_; DISALLOW_COPY_AND_ASSIGN(QuicTestClient); };
diff --git a/net/tools/quic/test_tools/quic_test_server.cc b/net/tools/quic/test_tools/quic_test_server.cc index b5ea61a..31ddef8b 100644 --- a/net/tools/quic/test_tools/quic_test_server.cc +++ b/net/tools/quic/test_tools/quic_test_server.cc
@@ -44,7 +44,9 @@ return nullptr; } if (stream_factory_) { - return stream_factory_->CreateStream(id, this); + QuicSpdyStream* stream = stream_factory_->CreateStream(id, this); + ActivateStream(stream); + return stream; } return QuicSimpleServerSession::CreateIncomingDynamicStream(id); }
diff --git a/net/tools/quic/test_tools/server_thread.cc b/net/tools/quic/test_tools/server_thread.cc index ee6ceeb3..b51dfb11 100644 --- a/net/tools/quic/test_tools/server_thread.cc +++ b/net/tools/quic/test_tools/server_thread.cc
@@ -36,7 +36,7 @@ return; } - server_->Listen(address_); + server_->CreateUDPSocketAndListen(address_); port_lock_.Acquire(); port_ = server_->port();
diff --git a/ppapi/BUILD.gn b/ppapi/BUILD.gn index a0748e8..964175b 100644 --- a/ppapi/BUILD.gn +++ b/ppapi/BUILD.gn
@@ -137,7 +137,7 @@ deps = [ "//base/test:run_all_unittests", "//base/test:test_support", - "//gpu/ipc", + "//gpu/ipc/common", "//ipc", "//ipc:test_support", "//media:shared_memory_support",
diff --git a/ppapi/native_client/BUILD.gn b/ppapi/native_client/BUILD.gn index 5c49d1e4..96edfb0 100644 --- a/ppapi/native_client/BUILD.gn +++ b/ppapi/native_client/BUILD.gn
@@ -19,7 +19,7 @@ "//gpu/command_buffer/client", "//gpu/command_buffer/client:gles2_implementation", "//gpu/command_buffer/common", - "//gpu/ipc", + "//gpu/ipc/common", "//ipc", "//media:shared_memory_support", "//native_client/src/shared/gio",
diff --git a/ppapi/ppapi_internal.gyp b/ppapi/ppapi_internal.gyp index 042ed44..a6eed4d 100644 --- a/ppapi/ppapi_internal.gyp +++ b/ppapi/ppapi_internal.gyp
@@ -84,7 +84,7 @@ }, 'dependencies': [ '../base/base.gyp:base', - '../gpu/gpu.gyp:gpu_ipc', + '../gpu/gpu.gyp:gpu_ipc_common', '../ipc/ipc.gyp:ipc', '../skia/skia.gyp:skia', 'ppapi.gyp:ppapi_c', @@ -108,7 +108,7 @@ '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../gin/gin.gyp:gin', '../gpu/gpu.gyp:gles2_implementation', - '../gpu/gpu.gyp:gpu_ipc', + '../gpu/gpu.gyp:gpu_ipc_common', '../media/media.gyp:shared_memory_support', '../ipc/ipc.gyp:ipc', '../skia/skia.gyp:skia', @@ -156,7 +156,7 @@ '../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../gin/gin.gyp:gin', '../gpu/gpu.gyp:gles2_implementation', - '../gpu/gpu.gyp:gpu_ipc', + '../gpu/gpu.gyp:gpu_ipc_common', '../media/media.gyp:shared_memory_support', '../ipc/ipc.gyp:ipc', '../skia/skia.gyp:skia', @@ -240,12 +240,12 @@ 'dependencies': [ '../base/base.gyp:base_win64', '../ipc/ipc.gyp:ipc_win64', - '../gpu/gpu.gyp:gpu_ipc_win64', + '../gpu/gpu.gyp:gpu_ipc_common_win64', 'ppapi.gyp:ppapi_c', 'ppapi_shared_win64', ], 'export_dependent_settings': [ - '../gpu/gpu.gyp:gpu_ipc_win64', + '../gpu/gpu.gyp:gpu_ipc_common_win64', ], 'defines': [ '<@(nacl_win64_defines)',
diff --git a/ppapi/ppapi_tests.gypi b/ppapi/ppapi_tests.gypi index f8ab6f6e..a2ee7f0 100644 --- a/ppapi/ppapi_tests.gypi +++ b/ppapi/ppapi_tests.gypi
@@ -200,7 +200,7 @@ 'ppapi_unittest_shared', '../base/base.gyp:run_all_unittests', '../base/base.gyp:test_support_base', - '../gpu/gpu.gyp:gpu_ipc', + '../gpu/gpu.gyp:gpu_ipc_common', '../ipc/ipc.gyp:ipc', '../ipc/ipc.gyp:test_support_ipc', '../media/media.gyp:shared_memory_support',
diff --git a/ppapi/proxy/BUILD.gn b/ppapi/proxy/BUILD.gn index 9167f882..79ab6855 100644 --- a/ppapi/proxy/BUILD.gn +++ b/ppapi/proxy/BUILD.gn
@@ -279,7 +279,7 @@ deps = [ "//base", "//gpu/command_buffer/client:gles2_implementation", - "//gpu/ipc", + "//gpu/ipc/common", "//ipc", "//media:shared_memory_support", "//ppapi/c", @@ -343,7 +343,7 @@ deps = [ "//base", - "//gpu/ipc", + "//gpu/ipc/common", "//ipc", "//ppapi/c", "//ppapi/shared_impl",
diff --git a/ppapi/proxy/ppapi_messages.h b/ppapi/proxy/ppapi_messages.h index ebaeed90..a30c175 100644 --- a/ppapi/proxy/ppapi_messages.h +++ b/ppapi/proxy/ppapi_messages.h
@@ -20,7 +20,7 @@ #include "gpu/command_buffer/common/command_buffer_id.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/common/sync_token.h" -#include "gpu/ipc/gpu_command_buffer_traits.h" +#include "gpu/ipc/common/gpu_command_buffer_traits.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_message_utils.h"
diff --git a/remoting/client/jni/chromoting_jni_instance.cc b/remoting/client/jni/chromoting_jni_instance.cc index 678db65..4902e17 100644 --- a/remoting/client/jni/chromoting_jni_instance.cc +++ b/remoting/client/jni/chromoting_jni_instance.cc
@@ -81,12 +81,12 @@ host_pubkey)); std::vector<protocol::AuthenticationMethod> auth_methods; - auth_methods.push_back(protocol::AuthenticationMethod::Spake2Pair()); - auth_methods.push_back(protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::HMAC_SHA256)); - auth_methods.push_back(protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::NONE)); - auth_methods.push_back(protocol::AuthenticationMethod::ThirdParty()); + auth_methods.push_back(protocol::AuthenticationMethod::THIRD_PARTY); + auth_methods.push_back(protocol::AuthenticationMethod::SPAKE2_PAIR); + auth_methods.push_back( + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); + auth_methods.push_back( + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN); authenticator_.reset(new protocol::NegotiatingClientAuthenticator( pairing_id, pairing_secret, host_id_,
diff --git a/remoting/client/plugin/chromoting_instance.cc b/remoting/client/plugin/chromoting_instance.cc index 23f60af..a90b5071 100644 --- a/remoting/client/plugin/chromoting_instance.cc +++ b/remoting/client/plugin/chromoting_instance.cc
@@ -151,8 +151,7 @@ initialized_(false), plugin_task_runner_(new PepperMainThreadTaskRunner()), context_(plugin_task_runner_.get()), - input_tracker_(&mouse_input_filter_), - touch_input_scaler_(&input_tracker_), + touch_input_scaler_(&mouse_input_filter_), key_mapper_(&touch_input_scaler_), input_handler_(&input_tracker_), cursor_setter_(this), @@ -649,7 +648,7 @@ DCHECK(key_filter.empty()); normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); } - input_handler_.set_input_stub(normalizing_input_filter_.get()); + input_tracker_.set_input_stub(normalizing_input_filter_.get()); // Try initializing 3D video renderer. video_renderer_.reset(new PepperVideoRenderer3D()); @@ -705,12 +704,12 @@ host_public_key)); std::vector<protocol::AuthenticationMethod> auth_methods; - auth_methods.push_back(protocol::AuthenticationMethod::ThirdParty()); - auth_methods.push_back(protocol::AuthenticationMethod::Spake2Pair()); - auth_methods.push_back(protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::HMAC_SHA256)); - auth_methods.push_back(protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::NONE)); + auth_methods.push_back(protocol::AuthenticationMethod::THIRD_PARTY); + auth_methods.push_back(protocol::AuthenticationMethod::SPAKE2_PAIR); + auth_methods.push_back( + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); + auth_methods.push_back( + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN); scoped_ptr<protocol::Authenticator> authenticator( new protocol::NegotiatingClientAuthenticator(
diff --git a/remoting/client/plugin/chromoting_instance.h b/remoting/client/plugin/chromoting_instance.h index 9eba3d1..52b6efd 100644 --- a/remoting/client/plugin/chromoting_instance.h +++ b/remoting/client/plugin/chromoting_instance.h
@@ -263,10 +263,10 @@ // Input pipeline components, in reverse order of distance from input source. protocol::MouseInputFilter mouse_input_filter_; - protocol::InputEventTracker input_tracker_; TouchInputScaler touch_input_scaler_; KeyEventMapper key_mapper_; scoped_ptr<protocol::InputFilter> normalizing_input_filter_; + protocol::InputEventTracker input_tracker_; PepperInputHandler input_handler_; // Cursor shape handling components, in reverse order to that in which they
diff --git a/remoting/client/plugin/pepper_input_handler.cc b/remoting/client/plugin/pepper_input_handler.cc index c25c566..4b652649 100644 --- a/remoting/client/plugin/pepper_input_handler.cc +++ b/remoting/client/plugin/pepper_input_handler.cc
@@ -111,8 +111,7 @@ PepperInputHandler::PepperInputHandler( protocol::InputEventTracker* input_tracker) - : input_stub_(nullptr), - input_tracker_(input_tracker), + : input_tracker_(input_tracker), has_focus_(false), send_mouse_input_when_unfocused_(false), send_mouse_move_deltas_(false), @@ -133,10 +132,8 @@ case PP_INPUTEVENT_TYPE_TOUCHMOVE: case PP_INPUTEVENT_TYPE_TOUCHEND: case PP_INPUTEVENT_TYPE_TOUCHCANCEL: { - if (!input_stub_) - return true; pp::TouchInputEvent pp_touch_event(event); - input_stub_->InjectTouchEvent(MakeTouchEvent(pp_touch_event)); + input_tracker_->InjectTouchEvent(MakeTouchEvent(pp_touch_event)); return true; } @@ -148,10 +145,8 @@ case PP_INPUTEVENT_TYPE_KEYDOWN: case PP_INPUTEVENT_TYPE_KEYUP: { - if (!input_stub_) - return true; pp::KeyboardInputEvent pp_key_event(event); - input_stub_->InjectKeyEvent(MakeKeyEvent(pp_key_event)); + input_tracker_->InjectKeyEvent(MakeKeyEvent(pp_key_event)); return true; } @@ -159,8 +154,6 @@ case PP_INPUTEVENT_TYPE_MOUSEUP: { if (!has_focus_ && !send_mouse_input_when_unfocused_) return false; - if (!input_stub_) - return true; pp::MouseInputEvent pp_mouse_event(event); protocol::MouseEvent mouse_event( @@ -181,7 +174,7 @@ if (mouse_event.has_button()) { bool is_down = (event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN); mouse_event.set_button_down(is_down); - input_stub_->InjectMouseEvent(mouse_event); + input_tracker_->InjectMouseEvent(mouse_event); } return true; @@ -192,11 +185,9 @@ case PP_INPUTEVENT_TYPE_MOUSELEAVE: { if (!has_focus_ && !send_mouse_input_when_unfocused_) return false; - if (!input_stub_) - return true; pp::MouseInputEvent pp_mouse_event(event); - input_stub_->InjectMouseEvent( + input_tracker_->InjectMouseEvent( MakeMouseEvent(pp_mouse_event, send_mouse_move_deltas_)); return true; @@ -205,8 +196,6 @@ case PP_INPUTEVENT_TYPE_WHEEL: { if (!has_focus_ && !send_mouse_input_when_unfocused_) return false; - if (!input_stub_) - return true; pp::WheelInputEvent pp_wheel_event(event); @@ -246,7 +235,7 @@ mouse_event.set_wheel_ticks_x(ticks_x); mouse_event.set_wheel_ticks_y(ticks_y); - input_stub_->InjectMouseEvent(mouse_event); + input_tracker_->InjectMouseEvent(mouse_event); } return true; }
diff --git a/remoting/client/plugin/pepper_input_handler.h b/remoting/client/plugin/pepper_input_handler.h index 3c00221..1d07c9f 100644 --- a/remoting/client/plugin/pepper_input_handler.h +++ b/remoting/client/plugin/pepper_input_handler.h
@@ -26,11 +26,6 @@ // for the lifetime of the PepperInputHandler. explicit PepperInputHandler(protocol::InputEventTracker* input_tracker); - // Sets the input stub to which processed events will be passed. - void set_input_stub(protocol::InputStub* input_stub) { - input_stub_ = input_stub; - } - // Enable or disable sending mouse input when the plugin does not have input // focus. void set_send_mouse_input_when_unfocused(bool send) { @@ -46,7 +41,7 @@ detect_stuck_modifiers_ = detect; } - // Processes PPAPI events and dispatches them to |input_stub_|. + // Processes PPAPI events and dispatches them to |input_tracker_|. bool HandleInputEvent(const pp::InputEvent& event); // Must be called when the plugin receives or loses focus. @@ -59,10 +54,8 @@ // are not indicated as active on |event|, release all keys. void ReleaseAllIfModifiersStuck(const pp::InputEvent& event); - // Receives input events generated from PPAPI input. - protocol::InputStub* input_stub_; - - // Tracks input events to manage auto-release in ReleaseAllIfModifiersStuck. + // Tracks input events to manage auto-release in ReleaseAllIfModifiersStuck + // and receives input events generated from PPAPI input. protocol::InputEventTracker* input_tracker_; // True if the plugin has focus.
diff --git a/remoting/host/pin_hash.cc b/remoting/host/pin_hash.cc index c9b1ca3c..d0ee42d 100644 --- a/remoting/host/pin_hash.cc +++ b/remoting/host/pin_hash.cc
@@ -11,10 +11,33 @@ namespace remoting { +bool ParsePinHashFromConfig(const std::string& value, + const std::string& host_id, + std::string* pin_hash_out) { + size_t separator = value.find(':'); + if (separator == std::string::npos) + return false; + + if (!base::Base64Decode(value.substr(separator + 1), pin_hash_out)) + return false; + + std::string function_name = value.substr(0, separator); + if (function_name == "plain") { + *pin_hash_out = protocol::ApplySharedSecretHashFunction( + protocol::HashFunction::HMAC_SHA256, host_id, *pin_hash_out); + return true; + } else if (function_name == "hmac") { + return true; + } + + pin_hash_out->clear(); + return false; +} + std::string MakeHostPinHash(const std::string& host_id, const std::string& pin) { - std::string hash = protocol::AuthenticationMethod::ApplyHashFunction( - protocol::AuthenticationMethod::HMAC_SHA256, host_id, pin); + std::string hash = protocol::ApplySharedSecretHashFunction( + protocol::HashFunction::HMAC_SHA256, host_id, pin); std::string hash_base64; base::Base64Encode(hash, &hash_base64); return "hmac:" + hash_base64; @@ -23,15 +46,14 @@ bool VerifyHostPinHash(const std::string& hash, const std::string& host_id, const std::string& pin) { - remoting::protocol::SharedSecretHash hash_parsed; - if (!hash_parsed.Parse(hash)) { - LOG(FATAL) << "Invalid hash."; + std::string hash_parsed; + if (!ParsePinHashFromConfig(hash, host_id, &hash_parsed)) { + LOG(FATAL) << "Failed to parse PIN hash."; return false; } - std::string hash_calculated = - remoting::protocol::AuthenticationMethod::ApplyHashFunction( - hash_parsed.hash_function, host_id, pin); - return hash_calculated == hash_parsed.value; + std::string hash_calculated = protocol::ApplySharedSecretHashFunction( + protocol::HashFunction::HMAC_SHA256, host_id, pin); + return hash_calculated == hash_parsed; } } // namespace remoting
diff --git a/remoting/host/pin_hash.h b/remoting/host/pin_hash.h index 033ac4a4..f1e725a 100644 --- a/remoting/host/pin_hash.h +++ b/remoting/host/pin_hash.h
@@ -13,6 +13,14 @@ // hashed host ID and PIN. std::string MakeHostPinHash(const std::string& host_id, const std::string& pin); +// Parse string representation of a shared secret hash. The value can be either +// "plain:<pin_in_base64>" or "hmac:<pin_hmac_in_base64>". In the first case the +// returned value is automatically hashed. False is returned if |value| is in +// invalid format. +bool ParsePinHashFromConfig(const std::string& value, + const std::string& host_id, + std::string* pin_hash_out); + // Extracts the hash function from the given hash, uses it to calculate the // hash of the given host ID and PIN, and compares that hash to the given hash. // Returns true if the calculated and given hashes are equal.
diff --git a/remoting/host/remoting_me2me_host.cc b/remoting/host/remoting_me2me_host.cc index c44740d..11fefc5 100644 --- a/remoting/host/remoting_me2me_host.cc +++ b/remoting/host/remoting_me2me_host.cc
@@ -69,6 +69,7 @@ #include "remoting/host/me2me_desktop_environment.h" #include "remoting/host/oauth_token_getter_impl.h" #include "remoting/host/pairing_registry_delegate.h" +#include "remoting/host/pin_hash.h" #include "remoting/host/policy_watcher.h" #include "remoting/host/security_key/gnubby_auth_handler.h" #include "remoting/host/security_key/gnubby_extension.h" @@ -404,7 +405,7 @@ scoped_ptr<ConfigWatcher> config_watcher_; std::string host_id_; - protocol::SharedSecretHash host_secret_hash_; + std::string pin_hash_; scoped_refptr<RsaKeyPair> key_pair_; std::string oauth_refresh_token_; std::string serialized_config_; @@ -795,9 +796,9 @@ pairing_registry = pairing_registry_; } - factory = protocol::Me2MeHostAuthenticatorFactory::CreateWithSharedSecret( + factory = protocol::Me2MeHostAuthenticatorFactory::CreateWithPin( use_service_account_, host_owner_, local_certificate, key_pair_, - client_domain_, host_secret_hash_, pairing_registry); + client_domain_, pin_hash_, pairing_registry); host_->set_pairing_registry(pairing_registry); } else { @@ -1034,13 +1035,9 @@ } std::string host_secret_hash_string; - if (!config.GetString(kHostSecretHashConfigPath, - &host_secret_hash_string)) { - host_secret_hash_string = "plain:"; - } - - if (!host_secret_hash_.Parse(host_secret_hash_string)) { - LOG(ERROR) << "Invalid host_secret_hash."; + if (!config.GetString(kHostSecretHashConfigPath, &host_secret_hash_string) || + !ParsePinHashFromConfig(host_secret_hash_string, host_id_, &pin_hash_)) { + LOG(ERROR) << "Cannot parse host_secret_hash configuration value."; return false; }
diff --git a/remoting/protocol/authentication_method.cc b/remoting/protocol/authentication_method.cc index d02a19ff..f78b0db 100644 --- a/remoting/protocol/authentication_method.cc +++ b/remoting/protocol/authentication_method.cc
@@ -4,63 +4,60 @@ #include "remoting/protocol/authentication_method.h" -#include <stddef.h> - -#include "base/base64.h" #include "base/logging.h" #include "crypto/hmac.h" #include "remoting/protocol/auth_util.h" +#include "remoting/protocol/name_value_map.h" namespace remoting { namespace protocol { -// static -AuthenticationMethod AuthenticationMethod::Invalid() { - return AuthenticationMethod(); +const NameMapElement<AuthenticationMethod> kAuthenticationMethodStrings[] = { + {AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN, "spake2_plain"}, + {AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC, "spake2_hmac"}, + {AuthenticationMethod::SPAKE2_PAIR, "spake2_pair"}, + {AuthenticationMethod::THIRD_PARTY, "third_party"}}; + +AuthenticationMethod ParseAuthenticationMethodString(const std::string& value) { + AuthenticationMethod result; + if (!NameToValue(kAuthenticationMethodStrings, value, &result)) + return AuthenticationMethod::INVALID; + return result; } -// static -AuthenticationMethod AuthenticationMethod::Spake2(HashFunction hash_function) { - return AuthenticationMethod(SPAKE2, hash_function); +const std::string AuthenticationMethodToString( + AuthenticationMethod method) { + return ValueToName(kAuthenticationMethodStrings, method); } -// static -AuthenticationMethod AuthenticationMethod::Spake2Pair() { - return AuthenticationMethod(SPAKE2_PAIR, HMAC_SHA256); -} +HashFunction GetHashFunctionForAuthenticationMethod( + AuthenticationMethod method) { + switch (method) { + case AuthenticationMethod::INVALID: + NOTREACHED(); + return HashFunction::NONE; -// static -AuthenticationMethod AuthenticationMethod::ThirdParty() { - return AuthenticationMethod(THIRD_PARTY, NONE); -} + case AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN: + case AuthenticationMethod::THIRD_PARTY: + return HashFunction::NONE; -// static -AuthenticationMethod AuthenticationMethod::FromString( - const std::string& value) { - if (value == "spake2_pair") { - return Spake2Pair(); - } else if (value == "spake2_plain") { - return Spake2(NONE); - } else if (value == "spake2_hmac") { - return Spake2(HMAC_SHA256); - } else if (value == "third_party") { - return ThirdParty(); - } else { - return AuthenticationMethod::Invalid(); + case AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC: + case AuthenticationMethod::SPAKE2_PAIR: + return HashFunction::HMAC_SHA256; } + + NOTREACHED(); + return HashFunction::NONE; } -// static -std::string AuthenticationMethod::ApplyHashFunction( - HashFunction hash_function, - const std::string& tag, - const std::string& shared_secret) { +std::string ApplySharedSecretHashFunction(HashFunction hash_function, + const std::string& tag, + const std::string& shared_secret) { switch (hash_function) { - case NONE: + case HashFunction::NONE: return shared_secret; - break; - case HMAC_SHA256: { + case HashFunction::HMAC_SHA256: { crypto::HMAC response(crypto::HMAC::SHA256); if (!response.Init(tag)) { LOG(FATAL) << "HMAC::Init failed"; @@ -79,76 +76,5 @@ return shared_secret; } -AuthenticationMethod::AuthenticationMethod() - : type_(INVALID), - hash_function_(NONE) { -} - -AuthenticationMethod::AuthenticationMethod(MethodType type, - HashFunction hash_function) - : type_(type), - hash_function_(hash_function) { - DCHECK_NE(type_, INVALID); -} - -AuthenticationMethod::HashFunction AuthenticationMethod::hash_function() const { - DCHECK(is_valid()); - return hash_function_; -} - -const std::string AuthenticationMethod::ToString() const { - DCHECK(is_valid()); - - switch (type_) { - case INVALID: - NOTREACHED(); - break; - - case SPAKE2_PAIR: - return "spake2_pair"; - - case SPAKE2: - switch (hash_function_) { - case NONE: - return "spake2_plain"; - case HMAC_SHA256: - return "spake2_hmac"; - } - break; - - case THIRD_PARTY: - return "third_party"; - } - - return "invalid"; -} - -bool AuthenticationMethod::operator ==( - const AuthenticationMethod& other) const { - return type_ == other.type_ && - hash_function_ == other.hash_function_; -} - -bool SharedSecretHash::Parse(const std::string& as_string) { - size_t separator = as_string.find(':'); - if (separator == std::string::npos) - return false; - - std::string function_name = as_string.substr(0, separator); - if (function_name == "plain") { - hash_function = AuthenticationMethod::NONE; - } else if (function_name == "hmac") { - hash_function = AuthenticationMethod::HMAC_SHA256; - } else { - return false; - } - - if (!base::Base64Decode(as_string.substr(separator + 1), &value)) { - return false; - } - - return true; -} - } // namespace protocol } // namespace remoting
diff --git a/remoting/protocol/authentication_method.h b/remoting/protocol/authentication_method.h index c2265d5..1b8dc46 100644 --- a/remoting/protocol/authentication_method.h +++ b/remoting/protocol/authentication_method.h
@@ -1,14 +1,6 @@ // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - -// AuthenticationMethod represents an authentication algorithm and its -// configuration. It knows how to parse and format authentication -// method names. -// Currently the following methods are supported: -// spake2_plain - SPAKE2 without hashing applied to the password. -// spake2_hmac - SPAKE2 with HMAC hashing of the password. - #ifndef REMOTING_PROTOCOL_AUTHENTICATION_METHOD_H_ #define REMOTING_PROTOCOL_AUTHENTICATION_METHOD_H_ @@ -19,74 +11,38 @@ class Authenticator; -class AuthenticationMethod { - public: - enum MethodType { - INVALID, - SPAKE2, - SPAKE2_PAIR, - THIRD_PARTY - }; - - enum HashFunction { - NONE, - HMAC_SHA256, - }; - - // Constructors for various authentication methods. - static AuthenticationMethod Invalid(); - static AuthenticationMethod Spake2(HashFunction hash_function); - static AuthenticationMethod Spake2Pair(); - static AuthenticationMethod ThirdParty(); - - // Parses a string that defines an authentication method. Returns an - // invalid value if the string is invalid. - static AuthenticationMethod FromString(const std::string& value); - - // Applies the specified hash function to |shared_secret| with the - // specified |tag| as a key. - static std::string ApplyHashFunction(HashFunction hash_function, - const std::string& tag, - const std::string& shared_secret); - - bool is_valid() const { return type_ != INVALID; } - - MethodType type() const { return type_; } - - // Following methods are valid only when is_valid() returns true. - - // Hash function applied to the shared secret on both ends. - HashFunction hash_function() const; - - // Returns string representation of the value stored in this object. - const std::string ToString() const; - - // Comparison operators so that std::find() can be used with - // collections of this class. - bool operator ==(const AuthenticationMethod& other) const; - bool operator !=(const AuthenticationMethod& other) const { - return !(*this == other); - } - - protected: - AuthenticationMethod(); - AuthenticationMethod(MethodType type, HashFunction hash_function); - - MethodType type_; - HashFunction hash_function_; +// AuthenticationMethod represents an authentication algorithm. +enum class AuthenticationMethod { + INVALID, + SPAKE2_SHARED_SECRET_PLAIN, + SPAKE2_SHARED_SECRET_HMAC, + SPAKE2_PAIR, + THIRD_PARTY }; -// SharedSecretHash stores hash of a host secret paired with the type -// of the hashing function. -struct SharedSecretHash { - AuthenticationMethod::HashFunction hash_function; - std::string value; - - // Parse string representation of a shared secret hash. The |as_string| - // must be in form "<hash_function>:<hash_value_base64>". - bool Parse(const std::string& as_string); +enum class HashFunction { + NONE, + HMAC_SHA256, }; +// Parses a string that defines an authentication method. Returns +// AuthenticationMethod::INVALID if the string is invalid. +AuthenticationMethod ParseAuthenticationMethodString(const std::string& value); + +// Returns string representation of |method|. +const std::string AuthenticationMethodToString(AuthenticationMethod method); + +// Returns hash function applied to the shared secret on both ends for the +// spefied |method|. +HashFunction GetHashFunctionForAuthenticationMethod( + AuthenticationMethod method); + +// Applies the specified hash function to |shared_secret| with the +// specified |tag| as a key. +std::string ApplySharedSecretHashFunction(HashFunction hash_function, + const std::string& tag, + const std::string& shared_secret); + } // namespace protocol } // namespace remoting
diff --git a/remoting/protocol/input_event_tracker.cc b/remoting/protocol/input_event_tracker.cc index 60c4bfd..c232c013 100644 --- a/remoting/protocol/input_event_tracker.cc +++ b/remoting/protocol/input_event_tracker.cc
@@ -10,9 +10,10 @@ namespace remoting { namespace protocol { +InputEventTracker::InputEventTracker() {} + InputEventTracker::InputEventTracker(InputStub* input_stub) - : input_stub_(input_stub), - mouse_button_state_(0) { + : input_stub_(input_stub) { } InputEventTracker::~InputEventTracker() {} @@ -26,6 +27,8 @@ } void InputEventTracker::ReleaseAll() { + DCHECK(input_stub_); + // Release all pressed keys. for (auto keycode : pressed_keys_) { KeyEvent event; @@ -91,6 +94,8 @@ } void InputEventTracker::InjectKeyEvent(const KeyEvent& event) { + DCHECK(input_stub_); + // We don't need to track the keyboard lock states of key down events. // Pressed keys will be released with |lock_states| set to 0. // The lock states of auto generated key up events don't matter as long as @@ -108,10 +113,13 @@ } void InputEventTracker::InjectTextEvent(const TextEvent& event) { + DCHECK(input_stub_); input_stub_->InjectTextEvent(event); } void InputEventTracker::InjectMouseEvent(const MouseEvent& event) { + DCHECK(input_stub_); + if (event.has_x() && event.has_y()) { mouse_pos_ = webrtc::DesktopVector(event.x(), event.y()); } @@ -130,6 +138,7 @@ } void InputEventTracker::InjectTouchEvent(const TouchEvent& event) { + DCHECK(input_stub_); // We only need the IDs to cancel all touch points in ReleaseAll(). Other // fields do not have to be tracked here as long as the host keeps track of // them.
diff --git a/remoting/protocol/input_event_tracker.h b/remoting/protocol/input_event_tracker.h index ff19b1d..1511fa5 100644 --- a/remoting/protocol/input_event_tracker.h +++ b/remoting/protocol/input_event_tracker.h
@@ -23,9 +23,14 @@ // |input_stub| for all currently-pressed keys and buttons when necessary. class InputEventTracker : public InputStub { public: - explicit InputEventTracker(protocol::InputStub* input_stub); + InputEventTracker(); + explicit InputEventTracker(InputStub* input_stub); ~InputEventTracker() override; + void set_input_stub(InputStub* input_stub) { + input_stub_ = input_stub; + } + // Returns true if the key with the specified USB code is currently pressed. bool IsKeyPressed(ui::DomCode usb_keycode) const; @@ -49,12 +54,12 @@ void InjectTouchEvent(const TouchEvent& event) override; private: - protocol::InputStub* input_stub_; + InputStub* input_stub_ = nullptr; std::set<ui::DomCode> pressed_keys_; webrtc::DesktopVector mouse_pos_; - uint32_t mouse_button_state_; + uint32_t mouse_button_state_ = 0; std::set<uint32_t> touch_point_ids_;
diff --git a/remoting/protocol/it2me_host_authenticator_factory.cc b/remoting/protocol/it2me_host_authenticator_factory.cc index 6bc05fbd..695b1b5 100644 --- a/remoting/protocol/it2me_host_authenticator_factory.cc +++ b/remoting/protocol/it2me_host_authenticator_factory.cc
@@ -16,16 +16,14 @@ It2MeHostAuthenticatorFactory::It2MeHostAuthenticatorFactory( const std::string& local_cert, scoped_refptr<RsaKeyPair> key_pair, - const std::string& shared_secret, + const std::string& access_code, const std::string& required_client_domain) : local_cert_(local_cert), key_pair_(key_pair), - shared_secret_(shared_secret), - required_client_domain_(required_client_domain) { -} + access_code_(access_code), + required_client_domain_(required_client_domain) {} -It2MeHostAuthenticatorFactory::~It2MeHostAuthenticatorFactory() { -} +It2MeHostAuthenticatorFactory::~It2MeHostAuthenticatorFactory() {} scoped_ptr<Authenticator> It2MeHostAuthenticatorFactory::CreateAuthenticator( const std::string& local_jid, @@ -48,9 +46,8 @@ } } - return NegotiatingHostAuthenticator::CreateWithSharedSecret( - local_cert_, key_pair_, shared_secret_, AuthenticationMethod::NONE, - nullptr); + return NegotiatingHostAuthenticator::CreateForIt2Me(local_cert_, key_pair_, + access_code_); } } // namespace protocol
diff --git a/remoting/protocol/it2me_host_authenticator_factory.h b/remoting/protocol/it2me_host_authenticator_factory.h index fddea60..78957d2 100644 --- a/remoting/protocol/it2me_host_authenticator_factory.h +++ b/remoting/protocol/it2me_host_authenticator_factory.h
@@ -23,11 +23,10 @@ // understands both the V2 and legacy V1 authentication mechanisms. class It2MeHostAuthenticatorFactory : public AuthenticatorFactory { public: - It2MeHostAuthenticatorFactory( - const std::string& local_cert, - scoped_refptr<RsaKeyPair> key_pair, - const std::string& shared_secret, - const std::string& required_client_domain); + It2MeHostAuthenticatorFactory(const std::string& local_cert, + scoped_refptr<RsaKeyPair> key_pair, + const std::string& access_code, + const std::string& required_client_domain); ~It2MeHostAuthenticatorFactory() override; // AuthenticatorFactory interface. @@ -39,7 +38,7 @@ private: std::string local_cert_; scoped_refptr<RsaKeyPair> key_pair_; - std::string shared_secret_; + std::string access_code_; std::string required_client_domain_; DISALLOW_COPY_AND_ASSIGN(It2MeHostAuthenticatorFactory);
diff --git a/remoting/protocol/me2me_host_authenticator_factory.cc b/remoting/protocol/me2me_host_authenticator_factory.cc index bd31a0d2..56e9631 100644 --- a/remoting/protocol/me2me_host_authenticator_factory.cc +++ b/remoting/protocol/me2me_host_authenticator_factory.cc
@@ -20,14 +20,13 @@ namespace protocol { // static -scoped_ptr<AuthenticatorFactory> -Me2MeHostAuthenticatorFactory::CreateWithSharedSecret( +scoped_ptr<AuthenticatorFactory> Me2MeHostAuthenticatorFactory::CreateWithPin( bool use_service_account, const std::string& host_owner, const std::string& local_cert, scoped_refptr<RsaKeyPair> key_pair, const std::string& required_client_domain, - const SharedSecretHash& shared_secret_hash, + const std::string& pin_hash, scoped_refptr<PairingRegistry> pairing_registry) { scoped_ptr<Me2MeHostAuthenticatorFactory> result( new Me2MeHostAuthenticatorFactory()); @@ -36,7 +35,7 @@ result->local_cert_ = local_cert; result->key_pair_ = key_pair; result->required_client_domain_ = required_client_domain; - result->shared_secret_hash_ = shared_secret_hash; + result->pin_hash_ = pin_hash; result->pairing_registry_ = pairing_registry; return std::move(result); } @@ -128,9 +127,8 @@ local_jid, remote_jid)); } - return NegotiatingHostAuthenticator::CreateWithSharedSecret( - local_cert_, key_pair_, shared_secret_hash_.value, - shared_secret_hash_.hash_function, pairing_registry_); + return NegotiatingHostAuthenticator::CreateWithPin( + local_cert_, key_pair_, pin_hash_, pairing_registry_); } return make_scoped_ptr(
diff --git a/remoting/protocol/me2me_host_authenticator_factory.h b/remoting/protocol/me2me_host_authenticator_factory.h index 5cc1beed..18ad8d3 100644 --- a/remoting/protocol/me2me_host_authenticator_factory.h +++ b/remoting/protocol/me2me_host_authenticator_factory.h
@@ -27,13 +27,13 @@ class Me2MeHostAuthenticatorFactory : public AuthenticatorFactory { public: // Create a factory that dispenses shared secret authenticators. - static scoped_ptr<AuthenticatorFactory> CreateWithSharedSecret( + static scoped_ptr<AuthenticatorFactory> CreateWithPin( bool use_service_account, const std::string& host_owner, const std::string& local_cert, scoped_refptr<RsaKeyPair> key_pair, const std::string& required_client_domain, - const SharedSecretHash& shared_secret_hash, + const std::string& pin_hash, scoped_refptr<PairingRegistry> pairing_registry); // Create a factory that dispenses third party authenticators. @@ -62,8 +62,8 @@ scoped_refptr<RsaKeyPair> key_pair_; std::string required_client_domain_; - // Used only for shared secret host authenticators. - SharedSecretHash shared_secret_hash_; + // Used only for PIN-based host authenticators. + std::string pin_hash_; // Used only for third party host authenticators. scoped_ptr<TokenValidatorFactory> token_validator_factory_;
diff --git a/remoting/protocol/negotiating_authenticator_base.cc b/remoting/protocol/negotiating_authenticator_base.cc index 12e1d8b..1d25466 100644 --- a/remoting/protocol/negotiating_authenticator_base.cc +++ b/remoting/protocol/negotiating_authenticator_base.cc
@@ -28,13 +28,9 @@ NegotiatingAuthenticatorBase::NegotiatingAuthenticatorBase( Authenticator::State initial_state) - : current_method_(AuthenticationMethod::Invalid()), - state_(initial_state), - rejection_reason_(INVALID_CREDENTIALS) { -} + : state_(initial_state) {} -NegotiatingAuthenticatorBase::~NegotiatingAuthenticatorBase() { -} +NegotiatingAuthenticatorBase::~NegotiatingAuthenticatorBase() {} Authenticator::State NegotiatingAuthenticatorBase::state() const { return state_; @@ -83,7 +79,7 @@ scoped_ptr<buzz::XmlElement> NegotiatingAuthenticatorBase::GetNextMessageInternal() { DCHECK_EQ(state(), MESSAGE_READY); - DCHECK(current_method_.is_valid()); + DCHECK(current_method_ != AuthenticationMethod::INVALID); scoped_ptr<buzz::XmlElement> result; if (current_authenticator_->state() == MESSAGE_READY) { @@ -93,13 +89,13 @@ } state_ = current_authenticator_->state(); DCHECK(state_ == ACCEPTED || state_ == WAITING_MESSAGE); - result->AddAttr(kMethodAttributeQName, current_method_.ToString()); + result->AddAttr(kMethodAttributeQName, + AuthenticationMethodToString(current_method_)); return result; } -void NegotiatingAuthenticatorBase::AddMethod( - const AuthenticationMethod& method) { - DCHECK(method.is_valid()); +void NegotiatingAuthenticatorBase::AddMethod(AuthenticationMethod method) { + DCHECK(method != AuthenticationMethod::INVALID); methods_.push_back(method); }
diff --git a/remoting/protocol/negotiating_authenticator_base.h b/remoting/protocol/negotiating_authenticator_base.h index 72481e3d..4d67a80 100644 --- a/remoting/protocol/negotiating_authenticator_base.h +++ b/remoting/protocol/negotiating_authenticator_base.h
@@ -85,7 +85,7 @@ explicit NegotiatingAuthenticatorBase(Authenticator::State initial_state); - void AddMethod(const AuthenticationMethod& method); + void AddMethod(AuthenticationMethod method); // Updates |state_| to reflect the current underlying authenticator state. // |resume_callback| is called after the state is updated. @@ -96,10 +96,10 @@ virtual scoped_ptr<buzz::XmlElement> GetNextMessageInternal(); std::vector<AuthenticationMethod> methods_; - AuthenticationMethod current_method_; + AuthenticationMethod current_method_ = AuthenticationMethod::INVALID; scoped_ptr<Authenticator> current_authenticator_; State state_; - RejectionReason rejection_reason_; + RejectionReason rejection_reason_ = INVALID_CREDENTIALS; private: DISALLOW_COPY_AND_ASSIGN(NegotiatingAuthenticatorBase);
diff --git a/remoting/protocol/negotiating_authenticator_unittest.cc b/remoting/protocol/negotiating_authenticator_unittest.cc index 8c570ca..4461d1d 100644 --- a/remoting/protocol/negotiating_authenticator_unittest.cc +++ b/remoting/protocol/negotiating_authenticator_unittest.cc
@@ -45,31 +45,31 @@ class NegotiatingAuthenticatorTest : public AuthenticatorTestBase { public: - NegotiatingAuthenticatorTest() { - } + NegotiatingAuthenticatorTest() {} ~NegotiatingAuthenticatorTest() override {} protected: - void InitAuthenticators( - const std::string& client_id, - const std::string& client_paired_secret, - const std::string& client_interactive_pin, - const std::string& host_secret, - AuthenticationMethod::HashFunction hash_function, - bool client_hmac_only) { - std::string host_secret_hash = AuthenticationMethod::ApplyHashFunction( - hash_function, kTestHostId, host_secret); - host_ = NegotiatingHostAuthenticator::CreateWithSharedSecret( - host_cert_, key_pair_, host_secret_hash, hash_function, - pairing_registry_); + void InitAuthenticators(const std::string& client_id, + const std::string& client_paired_secret, + const std::string& client_interactive_pin, + const std::string& host_secret, + bool it2me, + bool client_hmac_only) { + if (it2me) { + host_ = NegotiatingHostAuthenticator::CreateForIt2Me( + host_cert_, key_pair_, host_secret); + } else { + std::string host_secret_hash = ApplySharedSecretHashFunction( + HashFunction::HMAC_SHA256, kTestHostId, host_secret); + host_ = NegotiatingHostAuthenticator::CreateWithPin( + host_cert_, key_pair_, host_secret_hash, pairing_registry_); + } std::vector<AuthenticationMethod> methods; - methods.push_back(AuthenticationMethod::Spake2Pair()); - methods.push_back(AuthenticationMethod::Spake2( - AuthenticationMethod::HMAC_SHA256)); + methods.push_back(AuthenticationMethod::SPAKE2_PAIR); + methods.push_back(AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); if (!client_hmac_only) { - methods.push_back(AuthenticationMethod::Spake2( - AuthenticationMethod::NONE)); + methods.push_back(AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN); } bool pairing_expected = pairing_registry_.get() != nullptr; FetchSecretCallback fetch_secret_callback = @@ -146,34 +146,29 @@ DISALLOW_COPY_AND_ASSIGN(NegotiatingAuthenticatorTest); }; -TEST_F(NegotiatingAuthenticatorTest, SuccessfulAuthHmac) { - ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kNoClientId, kNoPairedSecret, kTestPin, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); - VerifyAccepted( - AuthenticationMethod::Spake2(AuthenticationMethod::HMAC_SHA256)); +TEST_F(NegotiatingAuthenticatorTest, SuccessfulAuthMe2MePin) { + ASSERT_NO_FATAL_FAILURE(InitAuthenticators(kNoClientId, kNoPairedSecret, + kTestPin, kTestPin, false, false)); + VerifyAccepted(AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); } -TEST_F(NegotiatingAuthenticatorTest, SuccessfulAuthPlain) { - ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kNoClientId, kNoPairedSecret, kTestPin, kTestPin, - AuthenticationMethod::NONE, false)); - VerifyAccepted(AuthenticationMethod::Spake2(AuthenticationMethod::NONE)); +TEST_F(NegotiatingAuthenticatorTest, SuccessfulAuthIt2me) { + ASSERT_NO_FATAL_FAILURE(InitAuthenticators(kNoClientId, kNoPairedSecret, + kTestPin, kTestPin, true, false)); + VerifyAccepted(AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN); } -TEST_F(NegotiatingAuthenticatorTest, InvalidSecretHmac) { +TEST_F(NegotiatingAuthenticatorTest, InvalidMe2MePin) { ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kNoClientId, kNoPairedSecret, kTestPinBad, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + kNoClientId, kNoPairedSecret, kTestPinBad, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); VerifyRejected(Authenticator::INVALID_CREDENTIALS); } -TEST_F(NegotiatingAuthenticatorTest, InvalidSecretPlain) { +TEST_F(NegotiatingAuthenticatorTest, InvalidIt2MeAccessCode) { ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kNoClientId, kNoPairedSecret, kTestPin, kTestPinBad, - AuthenticationMethod::NONE, false)); + kNoClientId, kNoPairedSecret, kTestPin, kTestPinBad, true, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); VerifyRejected(Authenticator::INVALID_CREDENTIALS); @@ -181,45 +176,39 @@ TEST_F(NegotiatingAuthenticatorTest, IncompatibleMethods) { ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kNoClientId, kNoPairedSecret, kTestPin, kTestPinBad, - AuthenticationMethod::NONE, true)); + kNoClientId, kNoPairedSecret, kTestPin, kTestPinBad, true, true)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); VerifyRejected(Authenticator::PROTOCOL_ERROR); } TEST_F(NegotiatingAuthenticatorTest, PairingNotSupported) { - ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kTestClientId, kTestPairedSecret, kTestPin, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + ASSERT_NO_FATAL_FAILURE(InitAuthenticators(kTestClientId, kTestPairedSecret, + kTestPin, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); - VerifyAccepted( - AuthenticationMethod::Spake2(AuthenticationMethod::HMAC_SHA256)); + VerifyAccepted(AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); } TEST_F(NegotiatingAuthenticatorTest, PairingSupportedButNotPaired) { CreatePairingRegistry(false); - ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kNoClientId, kNoPairedSecret, kTestPin, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + ASSERT_NO_FATAL_FAILURE(InitAuthenticators(kNoClientId, kNoPairedSecret, + kTestPin, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); - VerifyAccepted(AuthenticationMethod::Spake2Pair()); + VerifyAccepted(AuthenticationMethod::SPAKE2_PAIR); } TEST_F(NegotiatingAuthenticatorTest, PairingRevokedPinOkay) { CreatePairingRegistry(false); - ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kTestClientId, kTestPairedSecret, kTestPin, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + ASSERT_NO_FATAL_FAILURE(InitAuthenticators(kTestClientId, kTestPairedSecret, + kTestPin, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); - VerifyAccepted(AuthenticationMethod::Spake2Pair()); + VerifyAccepted(AuthenticationMethod::SPAKE2_PAIR); } TEST_F(NegotiatingAuthenticatorTest, PairingRevokedPinBad) { CreatePairingRegistry(false); ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kTestClientId, kTestPairedSecret, kTestPinBad, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + kTestClientId, kTestPairedSecret, kTestPinBad, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); VerifyRejected(Authenticator::INVALID_CREDENTIALS); } @@ -227,27 +216,25 @@ TEST_F(NegotiatingAuthenticatorTest, PairingSucceeded) { CreatePairingRegistry(true); ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kTestClientId, kTestPairedSecret, kTestPinBad, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + kTestClientId, kTestPairedSecret, kTestPinBad, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); - VerifyAccepted(AuthenticationMethod::Spake2Pair()); + VerifyAccepted(AuthenticationMethod::SPAKE2_PAIR); } TEST_F(NegotiatingAuthenticatorTest, PairingSucceededInvalidSecretButPinOkay) { CreatePairingRegistry(true); ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kTestClientId, kTestPairedSecretBad, kTestPin, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + kTestClientId, kTestPairedSecretBad, kTestPin, kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); - VerifyAccepted(AuthenticationMethod::Spake2Pair()); + VerifyAccepted(AuthenticationMethod::SPAKE2_PAIR); } TEST_F(NegotiatingAuthenticatorTest, PairingFailedInvalidSecretAndPin) { CreatePairingRegistry(true); - ASSERT_NO_FATAL_FAILURE(InitAuthenticators( - kTestClientId, kTestPairedSecretBad, kTestPinBad, kTestPin, - AuthenticationMethod::HMAC_SHA256, false)); + ASSERT_NO_FATAL_FAILURE(InitAuthenticators(kTestClientId, + kTestPairedSecretBad, kTestPinBad, + kTestPin, false, false)); ASSERT_NO_FATAL_FAILURE(RunAuthExchange()); VerifyRejected(Authenticator::INVALID_CREDENTIALS); }
diff --git a/remoting/protocol/negotiating_client_authenticator.cc b/remoting/protocol/negotiating_client_authenticator.cc index 17b6c77..2a2247ef 100644 --- a/remoting/protocol/negotiating_client_authenticator.cc +++ b/remoting/protocol/negotiating_client_authenticator.cc
@@ -51,13 +51,13 @@ DCHECK_EQ(state(), WAITING_MESSAGE); std::string method_attr = message->Attr(kMethodAttributeQName); - AuthenticationMethod method = AuthenticationMethod::FromString(method_attr); + AuthenticationMethod method = ParseAuthenticationMethodString(method_attr); // The host picked a method different from the one the client had selected. if (method != current_method_) { // The host must pick a method that is valid and supported by the client, // and it must not change methods after it has picked one. - if (method_set_by_host_ || !method.is_valid() || + if (method_set_by_host_ || method == AuthenticationMethod::INVALID || std::find(methods_.begin(), methods_.end(), method) == methods_.end()) { state_ = REJECTED; rejection_reason_ = PROTOCOL_ERROR; @@ -84,7 +84,7 @@ DCHECK_EQ(state(), MESSAGE_READY); // This is the first message to the host, send a list of supported methods. - if (!current_method_.is_valid()) { + if (current_method_ == AuthenticationMethod::INVALID) { // If no authentication method has been chosen, see if we can optimistically // choose one. scoped_ptr<buzz::XmlElement> result; @@ -97,14 +97,13 @@ } // Include a list of supported methods. - std::stringstream supported_methods(std::stringstream::out); - for (std::vector<AuthenticationMethod>::iterator it = methods_.begin(); - it != methods_.end(); ++it) { - if (it != methods_.begin()) - supported_methods << kSupportedMethodsSeparator; - supported_methods << it->ToString(); + std::string supported_methods; + for (AuthenticationMethod method : methods_) { + if (!supported_methods.empty()) + supported_methods += kSupportedMethodsSeparator; + supported_methods += AuthenticationMethodToString(method); } - result->AddAttr(kSupportedMethodsAttributeQName, supported_methods.str()); + result->AddAttr(kSupportedMethodsAttributeQName, supported_methods); state_ = WAITING_MESSAGE; return result; } @@ -114,8 +113,8 @@ void NegotiatingClientAuthenticator::CreateAuthenticatorForCurrentMethod( Authenticator::State preferred_initial_state, const base::Closure& resume_callback) { - DCHECK(current_method_.is_valid()); - if (current_method_.type() == AuthenticationMethod::THIRD_PARTY) { + DCHECK(current_method_ != AuthenticationMethod::INVALID); + if (current_method_ == AuthenticationMethod::THIRD_PARTY) { // |ThirdPartyClientAuthenticator| takes ownership of |token_fetcher_|. // The authentication method negotiation logic should guarantee that only // one |ThirdPartyClientAuthenticator| will need to be created per session. @@ -124,10 +123,12 @@ std::move(token_fetcher_))); resume_callback.Run(); } else { - DCHECK(current_method_.type() == AuthenticationMethod::SPAKE2 || - current_method_.type() == AuthenticationMethod::SPAKE2_PAIR); + DCHECK(current_method_ == + AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN || + current_method_ == AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC || + current_method_ == AuthenticationMethod::SPAKE2_PAIR); bool pairing_supported = - (current_method_.type() == AuthenticationMethod::SPAKE2_PAIR); + (current_method_ == AuthenticationMethod::SPAKE2_PAIR); SecretFetchedCallback callback = base::Bind( &NegotiatingClientAuthenticator::CreateV2AuthenticatorWithSecret, weak_factory_.GetWeakPtr(), preferred_initial_state, resume_callback); @@ -138,13 +139,13 @@ void NegotiatingClientAuthenticator::CreatePreferredAuthenticator() { if (!client_pairing_id_.empty() && !shared_secret_.empty() && std::find(methods_.begin(), methods_.end(), - AuthenticationMethod::Spake2Pair()) != methods_.end()) { + AuthenticationMethod::SPAKE2_PAIR) != methods_.end()) { // If the client specified a pairing id and shared secret, then create a // PairingAuthenticator. current_authenticator_.reset(new PairingClientAuthenticator( client_pairing_id_, shared_secret_, fetch_secret_callback_, authentication_tag_)); - current_method_ = AuthenticationMethod::Spake2Pair(); + current_method_ = AuthenticationMethod::SPAKE2_PAIR; } } @@ -153,8 +154,9 @@ const base::Closure& resume_callback, const std::string& shared_secret) { current_authenticator_ = V2Authenticator::CreateForClient( - AuthenticationMethod::ApplyHashFunction( - current_method_.hash_function(), authentication_tag_, shared_secret), + ApplySharedSecretHashFunction( + GetHashFunctionForAuthenticationMethod(current_method_), + authentication_tag_, shared_secret), initial_state); resume_callback.Run(); }
diff --git a/remoting/protocol/negotiating_host_authenticator.cc b/remoting/protocol/negotiating_host_authenticator.cc index 8bcad2a..57277ef 100644 --- a/remoting/protocol/negotiating_host_authenticator.cc +++ b/remoting/protocol/negotiating_host_authenticator.cc
@@ -28,23 +28,33 @@ scoped_refptr<RsaKeyPair> key_pair) : NegotiatingAuthenticatorBase(WAITING_MESSAGE), local_cert_(local_cert), - local_key_pair_(key_pair) { + local_key_pair_(key_pair) {} + +// static +scoped_ptr<Authenticator> NegotiatingHostAuthenticator::CreateForIt2Me( + const std::string& local_cert, + scoped_refptr<RsaKeyPair> key_pair, + const std::string& access_code) { + scoped_ptr<NegotiatingHostAuthenticator> result( + new NegotiatingHostAuthenticator(local_cert, key_pair)); + result->shared_secret_hash_ = access_code; + result->AddMethod(AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN); + return std::move(result); } // static -scoped_ptr<Authenticator> NegotiatingHostAuthenticator::CreateWithSharedSecret( +scoped_ptr<Authenticator> NegotiatingHostAuthenticator::CreateWithPin( const std::string& local_cert, scoped_refptr<RsaKeyPair> key_pair, - const std::string& shared_secret_hash, - AuthenticationMethod::HashFunction hash_function, + const std::string& pin_hash, scoped_refptr<PairingRegistry> pairing_registry) { scoped_ptr<NegotiatingHostAuthenticator> result( new NegotiatingHostAuthenticator(local_cert, key_pair)); - result->shared_secret_hash_ = shared_secret_hash; + result->shared_secret_hash_ = pin_hash; result->pairing_registry_ = pairing_registry; - result->AddMethod(AuthenticationMethod::Spake2(hash_function)); + result->AddMethod(AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); if (pairing_registry.get()) { - result->AddMethod(AuthenticationMethod::Spake2Pair()); + result->AddMethod(AuthenticationMethod::SPAKE2_PAIR); } return std::move(result); } @@ -58,7 +68,7 @@ scoped_ptr<NegotiatingHostAuthenticator> result( new NegotiatingHostAuthenticator(local_cert, key_pair)); result->token_validator_ = std::move(token_validator); - result->AddMethod(AuthenticationMethod::ThirdParty()); + result->AddMethod(AuthenticationMethod::THIRD_PARTY); return std::move(result); } @@ -71,10 +81,11 @@ DCHECK_EQ(state(), WAITING_MESSAGE); std::string method_attr = message->Attr(kMethodAttributeQName); - AuthenticationMethod method = AuthenticationMethod::FromString(method_attr); + AuthenticationMethod method = ParseAuthenticationMethodString(method_attr); // If the host has already chosen a method, it can't be changed by the client. - if (current_method_.is_valid() && method != current_method_) { + if (current_method_ != AuthenticationMethod::INVALID && + method != current_method_) { state_ = REJECTED; rejection_reason_ = PROTOCOL_ERROR; resume_callback.Run(); @@ -84,9 +95,9 @@ // If the client did not specify a preferred auth method, or specified an // unknown or unsupported method, then select the first known method from // the supported-methods attribute. - if (!method.is_valid() || + if (method == AuthenticationMethod::INVALID || std::find(methods_.begin(), methods_.end(), method) == methods_.end()) { - method = AuthenticationMethod::Invalid(); + method = AuthenticationMethod::INVALID; std::string supported_methods_attr = message->Attr(kSupportedMethodsAttributeQName); @@ -105,17 +116,17 @@ std::string(1, kSupportedMethodsSeparator), base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { AuthenticationMethod list_value = - AuthenticationMethod::FromString(method_str); - if (list_value.is_valid() && - std::find(methods_.begin(), - methods_.end(), list_value) != methods_.end()) { + ParseAuthenticationMethodString(method_str); + if (list_value != AuthenticationMethod::INVALID && + std::find(methods_.begin(), methods_.end(), list_value) != + methods_.end()) { // Found common method. method = list_value; break; } } - if (!method.is_valid()) { + if (method == AuthenticationMethod::INVALID) { // Failed to find a common auth method. state_ = REJECTED; rejection_reason_ = PROTOCOL_ERROR; @@ -134,7 +145,7 @@ // If the client specified a supported method, and the host hasn't chosen a // method yet, use the client's preferred method and process the message. - if (!current_method_.is_valid()) { + if (current_method_ == AuthenticationMethod::INVALID) { current_method_ = method; state_ = PROCESSING_MESSAGE; // Copy the message since the authenticator may process it asynchronously. @@ -156,16 +167,16 @@ void NegotiatingHostAuthenticator::CreateAuthenticator( Authenticator::State preferred_initial_state, const base::Closure& resume_callback) { - DCHECK(current_method_.is_valid()); + DCHECK(current_method_ != AuthenticationMethod::INVALID); - if (current_method_.type() == AuthenticationMethod::THIRD_PARTY) { + if (current_method_ == AuthenticationMethod::THIRD_PARTY) { // |ThirdPartyHostAuthenticator| takes ownership of |token_validator_|. // The authentication method negotiation logic should guarantee that only // one |ThirdPartyHostAuthenticator| will need to be created per session. DCHECK(token_validator_); current_authenticator_.reset(new ThirdPartyHostAuthenticator( local_cert_, local_key_pair_, std::move(token_validator_))); - } else if (current_method_ == AuthenticationMethod::Spake2Pair() && + } else if (current_method_ == AuthenticationMethod::SPAKE2_PAIR && preferred_initial_state == WAITING_MESSAGE) { // If the client requested Spake2Pair and sent an initial message, attempt // the paired connection protocol. @@ -178,8 +189,10 @@ // Spake2Pair so that the client knows that the host supports pairing and // that it can therefore present the option to the user when they enter // the PIN. - DCHECK(current_method_.type() == AuthenticationMethod::SPAKE2 || - current_method_.type() == AuthenticationMethod::SPAKE2_PAIR); + DCHECK(current_method_ == + AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN || + current_method_ == AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC || + current_method_ == AuthenticationMethod::SPAKE2_PAIR); current_authenticator_ = V2Authenticator::CreateForHost( local_cert_, local_key_pair_, shared_secret_hash_, preferred_initial_state);
diff --git a/remoting/protocol/negotiating_host_authenticator.h b/remoting/protocol/negotiating_host_authenticator.h index 569d15a..ed0c8ee6 100644 --- a/remoting/protocol/negotiating_host_authenticator.h +++ b/remoting/protocol/negotiating_host_authenticator.h
@@ -29,14 +29,19 @@ public: ~NegotiatingHostAuthenticator() override; - // Creates a host authenticator, using a fixed shared secret/PIN hash. - // If |pairing_registry| is non-nullptr then the Spake2Pair method will - // be offered, supporting PIN-less authentication. - static scoped_ptr<Authenticator> CreateWithSharedSecret( + // Creates a host authenticator for It2Me host. + static scoped_ptr<Authenticator> CreateForIt2Me( const std::string& local_cert, scoped_refptr<RsaKeyPair> key_pair, - const std::string& shared_secret_hash, - AuthenticationMethod::HashFunction hash_function, + const std::string& access_code); + + // Creates a host authenticator, using a fixed PIN. + // If |pairing_registry| is non-nullptr then the spake2_pair method will + // be offered, supporting PIN-less authentication. + static scoped_ptr<Authenticator> CreateWithPin( + const std::string& local_cert, + scoped_refptr<RsaKeyPair> key_pair, + const std::string& pin_hash, scoped_refptr<PairingRegistry> pairing_registry); // Creates a host authenticator, using third party authentication.
diff --git a/remoting/protocol/pairing_client_authenticator.cc b/remoting/protocol/pairing_client_authenticator.cc index 0d3037aa..5c03ab5 100644 --- a/remoting/protocol/pairing_client_authenticator.cc +++ b/remoting/protocol/pairing_client_authenticator.cc
@@ -62,9 +62,8 @@ const SetAuthenticatorCallback& callback, const std::string& pin) { callback.Run(V2Authenticator::CreateForClient( - AuthenticationMethod::ApplyHashFunction( - AuthenticationMethod::HMAC_SHA256, - authentication_tag_, pin), + ApplySharedSecretHashFunction(HashFunction::HMAC_SHA256, + authentication_tag_, pin), initial_state)); }
diff --git a/remoting/test/host_info.cc b/remoting/test/host_info.cc index 4be97e1..acb1c51 100644 --- a/remoting/test/host_info.cc +++ b/remoting/test/host_info.cc
@@ -91,15 +91,13 @@ connection_setup_info.user_name = user_name; connection_setup_info.auth_methods.push_back( - protocol::AuthenticationMethod::Spake2Pair()); + protocol::AuthenticationMethod::SPAKE2_PAIR); connection_setup_info.auth_methods.push_back( - protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::HashFunction::NONE)); + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_PLAIN); connection_setup_info.auth_methods.push_back( - protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::HashFunction::HMAC_SHA256)); + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); connection_setup_info.auth_methods.push_back( - protocol::AuthenticationMethod::ThirdParty()); + protocol::AuthenticationMethod::THIRD_PARTY); return connection_setup_info; }
diff --git a/remoting/test/protocol_perftest.cc b/remoting/test/protocol_perftest.cc index fa1a325..7debeb4 100644 --- a/remoting/test/protocol_perftest.cc +++ b/remoting/test/protocol_perftest.cc
@@ -52,6 +52,8 @@ const char kHostJid[] = "host_jid@example.com/host"; const char kHostOwner[] = "jane.doe@example.com"; const char kClientJid[] = "jane.doe@example.com/client"; +const char kHostId[] = "ABC123"; +const char kHostPin[] = "123456"; struct NetworkPerformanceParams { NetworkPerformanceParams(int bandwidth, @@ -347,12 +349,11 @@ scoped_refptr<RsaKeyPair> key_pair = RsaKeyPair::FromString(key_base64); ASSERT_TRUE(key_pair.get()); - protocol::SharedSecretHash host_secret; - host_secret.hash_function = protocol::AuthenticationMethod::NONE; - host_secret.value = "123456"; + std::string host_pin_hash = protocol::ApplySharedSecretHashFunction( + protocol::HashFunction::HMAC_SHA256, kHostId, kHostPin); scoped_ptr<protocol::AuthenticatorFactory> auth_factory = - protocol::Me2MeHostAuthenticatorFactory::CreateWithSharedSecret( - true, kHostOwner, host_cert, key_pair, "", host_secret, nullptr); + protocol::Me2MeHostAuthenticatorFactory::CreateWithPin( + true, kHostOwner, host_cert, key_pair, "", host_pin_hash, nullptr); host_->SetAuthenticatorFactory(std::move(auth_factory)); host_->AddStatusObserver(this); @@ -387,13 +388,13 @@ network_settings, protocol::TransportRole::CLIENT)); std::vector<protocol::AuthenticationMethod> auth_methods; - auth_methods.push_back(protocol::AuthenticationMethod::Spake2( - protocol::AuthenticationMethod::NONE)); + auth_methods.push_back( + protocol::AuthenticationMethod::SPAKE2_SHARED_SECRET_HMAC); scoped_ptr<protocol::Authenticator> client_authenticator( new protocol::NegotiatingClientAuthenticator( std::string(), // client_pairing_id std::string(), // client_pairing_secret - std::string(), // authentication_tag + kHostId, base::Bind(&ProtocolPerfTest::FetchPin, base::Unretained(this)), nullptr, auth_methods)); client_.reset( @@ -406,7 +407,7 @@ void FetchPin( bool pairing_supported, const protocol::SecretFetchedCallback& secret_fetched_callback) { - secret_fetched_callback.Run("123456"); + secret_fetched_callback.Run(kHostPin); } void MeasureTotalLatency(bool webrtc) {
diff --git a/remoting/test/remote_host_info.cc b/remoting/test/remote_host_info.cc index 3e79492..c4f97cd 100644 --- a/remoting/test/remote_host_info.cc +++ b/remoting/test/remote_host_info.cc
@@ -53,7 +53,7 @@ connection_setup_info.user_name = user_name; connection_setup_info.auth_methods.push_back( - protocol::AuthenticationMethod::ThirdParty()); + protocol::AuthenticationMethod::THIRD_PARTY); return connection_setup_info; }
diff --git a/remoting/test/test_chromoting_client_unittest.cc b/remoting/test/test_chromoting_client_unittest.cc index 6a4d2cb..d4fd7e59 100644 --- a/remoting/test/test_chromoting_client_unittest.cc +++ b/remoting/test/test_chromoting_client_unittest.cc
@@ -73,7 +73,7 @@ connection_setup_info_.host_jid = "test_host@faux_address.com/321"; connection_setup_info_.auth_methods.push_back( - protocol::AuthenticationMethod::ThirdParty()); + protocol::AuthenticationMethod::THIRD_PARTY); } void TestChromotingClientTest::TearDown() {
diff --git a/remoting/webapp/crd/js/me2me_activity.js b/remoting/webapp/crd/js/me2me_activity.js index 66530a0..8635565 100644 --- a/remoting/webapp/crd/js/me2me_activity.js +++ b/remoting/webapp/crd/js/me2me_activity.js
@@ -74,11 +74,10 @@ } } - this.hostUpdateDialog_.showIfNecessary(webappVersion).then(function() { - return that.host_.options.load(); - }).catch(remoting.Error.handler(function(/** remoting.Error */ error) { - // User cancels out of the Host upgrade dialog. Report it as bad version. - throw new remoting.Error(remoting.Error.Tag.BAD_VERSION); + this.hostUpdateDialog_.showIfNecessary(webappVersion).catch( + remoting.Error.handler(function(/** remoting.Error */ error) { + // User cancels the Host upgrade dialog. Report it as bad version. + throw new remoting.Error(remoting.Error.Tag.BAD_VERSION); })).then( this.gnubbyAuthHandler_.isGnubbyExtensionInstalled.bind( this.gnubbyAuthHandler_) @@ -144,7 +143,11 @@ this.desktopActivity_ = new remoting.DesktopRemotingActivity( this, this.logger_, this.additionalCapabilities_); this.desktopActivity_.getConnectingDialog().show(); - this.desktopActivity_.start(this.host_, this.createCredentialsProvider_()); + this.host_.options.load().then( + function() { + this.desktopActivity_.start(this.host_, + this.createCredentialsProvider_()); + }.bind(this)); }; /**
diff --git a/sync/engine/syncer.cc b/sync/engine/syncer.cc index 5eccd80..27bc1ba3 100644 --- a/sync/engine/syncer.cc +++ b/sync/engine/syncer.cc
@@ -214,7 +214,7 @@ session->SendSyncCycleEndEventNotification(source); bool success = !sessions::HasSyncerError( - session->status_controller().model_neutral_state()); + session->status_controller().model_neutral_state()); if (success && source == sync_pb::GetUpdatesCallerInfo::PERIODIC) session->mutable_status_controller()->UpdatePollTime(); return success;
diff --git a/sync/protocol/device_info_specifics.proto b/sync/protocol/device_info_specifics.proto index 0103aa6..c4e2e48 100644 --- a/sync/protocol/device_info_specifics.proto +++ b/sync/protocol/device_info_specifics.proto
@@ -43,4 +43,10 @@ // Device_id that is stable until user signs out. This device_id is used for // annotating login scoped refresh token. optional string signin_scoped_device_id = 7; + + // This field is updated to be the current time periodically, and is also set + // to the current time whenever another field changes. By examining the + // difference between this field and the current time, it should be possible + // to reason about the inactivity of any device that was syncing at one time. + optional int64 last_updated_timestamp = 8; }
diff --git a/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter b/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter index 6857e84..905b3b8 100644 --- a/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter +++ b/testing/buildbot/filters/browser-side-navigation.linux.browser_tests.filter
@@ -2,6 +2,15 @@ -AllUrlsApiTest.WhitelistedExtension -AppApiTest.ReloadIntoAppProcessWithJavaScript -AppWindowAPITest.TestCreate +-AutofillTest.AggregatesMinValidProfile +-AutofillTest.AggregatesMinValidProfileDifferentJS +-AutofillTest.AppendCountryCodeForAggregatedPhones +-AutofillTest.ProfileSavedWithValidCountryPhone +-AutofillTest.ProfilesNotAggregatedWithInvalidEmail +-AutofillTest.ProfilesNotAggregatedWithNoAddress +-AutofillTest.ProfilesNotAggregatedWithSubmitHandler +-AutofillTest.ProfileWithEmailInOtherFieldNotSaved +-AutofillTest.UsePlusSignForInternationalNumber -BrowserActionApiTest.BrowserActionPopupWithIframe -BrowserNavigatorTest.NavigateFromNTPToOptionsInSameTab -BrowserTest.CancelBeforeUnloadResetsURL
diff --git a/testing/libfuzzer/fuzzers/BUILD.gn b/testing/libfuzzer/fuzzers/BUILD.gn index e924b417..984338aa 100644 --- a/testing/libfuzzer/fuzzers/BUILD.gn +++ b/testing/libfuzzer/fuzzers/BUILD.gn
@@ -301,3 +301,13 @@ "//v8:wasm_asmjs_fuzzer", ] } + +fuzzer_test("third_party_re2_fuzzer") { + sources = [ + "re2_fuzzer.cc", + ] + deps = [ + "//third_party/re2:re2", + ] + libfuzzer_options = "re2_fuzzer.options" +}
diff --git a/testing/libfuzzer/fuzzers/re2_fuzzer.cc b/testing/libfuzzer/fuzzers/re2_fuzzer.cc new file mode 100644 index 0000000..4ac6c92 --- /dev/null +++ b/testing/libfuzzer/fuzzers/re2_fuzzer.cc
@@ -0,0 +1,88 @@ +// Copyright (c) 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 <stddef.h> +#include <stdint.h> + +#include <string> + +#include "re2/re2.h" +#include "util/logging.h" + +using std::string; + +void Test(const string &buffer, const string &pattern, + const RE2::Options &options) { + RE2 re(pattern, options); + if (!re.ok()) + return; + + string m1, m2; + int i1, i2; + double d1; + + if (re.NumberOfCapturingGroups() == 0) { + RE2::FullMatch(buffer, re); + RE2::PartialMatch(buffer, re); + } else if (re.NumberOfCapturingGroups() == 1) { + RE2::FullMatch(buffer, re, &m1); + RE2::PartialMatch(buffer, re, &i1); + } else if (re.NumberOfCapturingGroups() == 2) { + RE2::FullMatch(buffer, re, &i1, &i2); + RE2::PartialMatch(buffer, re, &m1, &m2); + } + + re2::StringPiece input(buffer); + RE2::Consume(&input, re, &m1); + RE2::FindAndConsume(&input, re, &d1); + string tmp1(buffer); + RE2::Replace(&tmp1, re, "zz"); + string tmp2(buffer); + RE2::GlobalReplace(&tmp2, re, "xx"); + RE2::QuoteMeta(re2::StringPiece(pattern)); +} + +// Entry point for LibFuzzer. +extern "C" int LLVMFuzzerTestOneInput(const unsigned char *data, size_t size) { + if (size < 1) + return 0; + + re2::FLAGS_minloglevel = 3; + RE2::Options options; + + size_t options_randomizer = 0; + for (size_t i = 0; i < size; i++) + options_randomizer += data[i]; + + if (options_randomizer & 1) + options.set_encoding(RE2::Options::EncodingLatin1); + + options.set_posix_syntax(options_randomizer & 2); + options.set_longest_match(options_randomizer & 4); + options.set_literal(options_randomizer & 8); + options.set_never_nl(options_randomizer & 16); + options.set_dot_nl(options_randomizer & 32); + options.set_never_capture(options_randomizer & 64); + options.set_case_sensitive(options_randomizer & 128); + options.set_perl_classes(options_randomizer & 256); + options.set_word_boundary(options_randomizer & 512); + options.set_one_line(options_randomizer & 1024); + + options.set_log_errors(false); + + const char* data_input = reinterpret_cast<const char*>(data); + { + string pattern(data_input, size); + string buffer(data_input, size); + Test(buffer, pattern, options); + } + + if (size >= 3) { + string pattern(data_input, size / 3); + string buffer(data_input + size / 3, size - size / 3); + Test(buffer, pattern, options); + } + + return 0; +}
diff --git a/testing/libfuzzer/fuzzers/re2_fuzzer.options b/testing/libfuzzer/fuzzers/re2_fuzzer.options new file mode 100644 index 0000000..dbe9bb4 --- /dev/null +++ b/testing/libfuzzer/fuzzers/re2_fuzzer.options
@@ -0,0 +1,3 @@ +[libfuzzer] +# re2_fuzzer is very slow and almost useless for long inputs. +max_len = random(4, 32)
diff --git a/testing/scripts/mojo_apptests.py b/testing/scripts/mojo_apptests.py index 56e54e23..8718ddd6 100755 --- a/testing/scripts/mojo_apptests.py +++ b/testing/scripts/mojo_apptests.py
@@ -16,7 +16,7 @@ build_dir = os.path.join(common.SRC_DIR, 'out', args.build_config_fs) with common.temporary_file() as tempfile_path: - rc = common.run_command([runner, build_dir, '--verbose', + rc = common.run_command([sys.executable, runner, build_dir, '--verbose', '--write-full-results-to', tempfile_path]) with open(tempfile_path) as f: results = json.load(f)
diff --git a/third_party/WebKit/LayoutTests/SlowTests b/third_party/WebKit/LayoutTests/SlowTests index 79b7bf0..4fb51b0 100644 --- a/third_party/WebKit/LayoutTests/SlowTests +++ b/third_party/WebKit/LayoutTests/SlowTests
@@ -148,6 +148,7 @@ crbug.com/311482 virtual/threaded/animations/interpolation/filter-interpolation.html [ Slow ] crbug.com/311482 virtual/threaded/animations/keyframes-unprefixed-03.html [ Slow ] crbug.com/243871 virtual/threaded/fast/scroll-behavior/ [ Slow ] +crbug.com/243871 virtual/threaded/fast/idle-callback/idle_periods.html [ Slow ] crbug.com/258896 animations/animation-direction-reverse-fill-mode.html [ Slow ] @@ -280,5 +281,5 @@ crbug.com/570656 [ Mac ] fast/writing-mode/Kusa-Makura-background-canvas.html [ Slow ] crbug.com/570656 [ Mac ] fast/text/unicode-fallback-font.html [ Slow ] -# This is really only slow under MSAN, but it's forbidden to add this expectation to MSANExpectations. -crbug.com/584807 [ Linux ] printing/webgl-oversized-printing.html [ Slow ] +crbug.com/584807 printing/webgl-oversized-printing.html [ Slow ] +crbug.com/584807 virtual/threaded/printing/webgl-oversized-printing.html [ Slow ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 9973a6d..e367f966 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -22,7 +22,7 @@ crbug.com/377567 [ Debug ] editing/selection/programmatic-selection-on-mac-is-directionless.html [ Timeout Pass ] crbug.com/377567 [ Debug ] fast/css/large-list-of-rules-crash.html [ Timeout Pass ] -crbug.com/501229 fast/forms/associatedFormControls-leak-nodes.html [ Failure ] +crbug.com/501229 fast/forms/associatedFormControls-leak-nodes.html [ Failure Pass ] crbug.com/417181 http/tests/xmlhttprequest/abort-on-changestate-headers-received.html [ Failure Pass ] @@ -112,14 +112,12 @@ crbug.com/538697 [ Win7 Debug ] virtual/threaded/printing/webgl-oversized-printing.html [ Crash ] crbug.com/538697 [ Win7 Debug ] printing/webgl-oversized-printing.html [ Crash ] -# Ref-tests that fail due to character based shaping/fallback. -crbug.com/404597 fast/text/international/inline-plaintext-is-isolated.html [ Failure ] -crbug.com/404597 fast/text/international/bdi-dir-default-to-auto.html [ Failure ] - crbug.com/539226 http/tests/xmlhttprequest/open-in-body-onload-sync-to-invalid-cross-origin-response-handling.html [ Timeout Pass ] crbug.com/539226 [ Win ] http/tests/xmlhttprequest/open-in-body-onload-sync-to-invalid-redirect-response-handling.html [ Timeout Pass ] crbug.com/539226 [ Win ] http/tests/xmlhttprequest/open-in-body-onload-sync-to-invalid-preflight-handling.html [ Timeout Pass ] +crbug.com/592063 svg/custom/relative-sized-shadow-tree-content-with-symbol.xhtml [ NeedsRebaseline ] + crbug.com/417782 [ Linux Win ] virtual/rootlayerscrolls/fast/scrolling/fractional-scroll-offset-fixed-position-non-composited.html [ Failure ] crbug.com/492664 [ Linux ] imported/csswg-test/css-writing-modes-3/box-offsets-rel-pos-vlr-005.xht [ Failure ] crbug.com/492664 [ Linux ] imported/csswg-test/css-writing-modes-3/box-offsets-rel-pos-vrl-004.xht [ Failure ] @@ -137,7 +135,6 @@ crbug.com/267206 [ Mac ] virtual/rootlayerscrolls/fast/scrolling/scrollbar-tickmarks-hittest.html [ Timeout ] -crbug.com/582836 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/variables/variable-external-font-face-01.html [ Failure ] crbug.com/582836 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/variables/variable-font-face-01.html [ Failure ] crbug.com/582836 imported/csswg-test/vendor-imports/mozilla/mozilla-central-reftests/variables/variable-font-face-02.html [ Failure ] @@ -170,7 +167,6 @@ crbug.com/520166 compositing/overflow/do-not-repaint-if-scrolling-composited-layers.html [ Failure Pass ] crbug.com/520169 [ Win ] fast/dom/Geolocation/timestamp.html [ Failure Pass ] crbug.com/520170 [ Win ] fast/dom/timer-throttling-hidden-page.html [ Failure Pass ] -crbug.com/520172 [ Win ] fast/dom/webtiming.html [ Failure Pass ] crbug.com/520174 fast/events/message-port-start-and-close-different-microtask.html [ Failure Pass ] crbug.com/520177 [ Android ] fast/images/style-access-during-imageChanged-crash.html [ Crash Pass ] crbug.com/520179 fast/preloader/document-write-noscript.html [ Failure Pass ] @@ -193,6 +189,11 @@ crbug.com/339597 http/tests/navigation/back-to-redirect-with-frame.php [ Pass Timeout ] crbug.com/473718 http/tests/navigation/beacon-cross-origin-redirect.html [ Failure Pass ] +# Skia roll +crbug.com/586181 svg/batik/paints/patternRegions-positioned-objects.svg [ NeedsRebaseline ] +crbug.com/586181 svg/batik/paints/patternRegions.svg [ NeedsRebaseline ] +crbug.com/586181 svg/custom/stroked-pattern.svg [ NeedsRebaseline ] + crbug.com/410974 fast/scroll-behavior/scroll-customization/scrollstate-basic.html [ Pass Failure ] crbug.com/410974 fast/scroll-behavior/scroll-customization/scrollstate-consume-deltas.html [ Pass Failure ] crbug.com/410974 fast/scroll-behavior/scroll-customization/scrollstate-consume-deltas-throw.html [ Pass Failure ] @@ -387,10 +388,6 @@ crbug.com/411164 [ Win ] http/tests/security/powerfulFeatureRestrictions/serviceworker-on-insecure-origin.html [ Pass ] -# This batch is flaky: -crbug.com/310679 [ Mac ] virtual/pointerevent/fast/events/scale-and-scroll-iframe-body.html [ Failure ] -crbug.com/310679 [ Mac ] virtual/pointerevent/fast/events/scale-and-scroll-iframe-window.html [ Failure ] - crbug.com/475984 [ Mac Debug ] css2.1/t100801-c544-valgn-03-d-agi.html [ Failure ] # Rebaseline didn't fix this. It's flaking between two different failures due to rounding error. @@ -398,8 +395,6 @@ # But consistently passes on release builds. crbug.com/518005 crbug.com/463358 [ Mac ] svg/W3C-SVG-1.1/struct-frag-02-t.svg [ Pass Failure ] -crbug.com/510337 inspector/elements/edit/edit-dom-actions.html [ Timeout ] - # SPv2 paint properties are still being implemented. # # These tests should not be rebaselined automatically, as our goal is to exactly match @@ -457,8 +452,7 @@ # expectation files. The following tests with [ Failure ] don't have failure # expectation files because they contain local path names. # Use crbug.com/490511 for untriaged failures. -crbug.com/490511 imported/web-platform-tests/html/browsers/history/the-location-interface/location_assign.html [ Timeout ] -crbug.com/490511 imported/web-platform-tests/html/rendering/bindings/the-input-element-as-a-text-entry-widget/unrecognized-type-should-fallback-as-text-type.html [ Failure ] +crbug.com/490511 [ Linux Win ] imported/web-platform-tests/html/rendering/bindings/the-input-element-as-a-text-entry-widget/unrecognized-type-should-fallback-as-text-type.html [ Failure ] crbug.com/526898 imported/web-platform-tests/html/rendering/non-replaced-elements/phrasing-content-0/font-element-text-decoration-color/001-x.xhtml [ Failure ] crbug.com/108417 imported/web-platform-tests/html/rendering/non-replaced-elements/tables/table-border-1.html [ Failure ] crbug.com/490511 imported/web-platform-tests/html/rendering/non-replaced-elements/the-hr-element-0/color.html [ Failure Pass ] @@ -466,7 +460,6 @@ crbug.com/490511 imported/web-platform-tests/html/semantics/document-metadata/styling/LinkStyle.html [ Failure Pass ] crbug.com/525896 imported/web-platform-tests/html/semantics/embedded-content/the-embed-element/embed-represent-nothing-01.html [ Failure ] crbug.com/490511 imported/web-platform-tests/html/semantics/embedded-content/media-elements/interfaces/HTMLElement/HTMLTrackElement/src.html [ Failure ] -crbug.com/526920 imported/web-platform-tests/html/semantics/embedded-content/media-elements/location-of-the-media-resource/currentSrc.html [ Failure ] crbug.com/525889 imported/web-platform-tests/html/webappapis/scripting/processing-model-2/compile-error-in-setInterval.html [ Failure ] crbug.com/525889 imported/web-platform-tests/html/webappapis/scripting/processing-model-2/compile-error-in-setTimeout.html [ Failure ] crbug.com/525889 imported/web-platform-tests/html/webappapis/scripting/processing-model-2/runtime-error-in-setInterval.html [ Failure ] @@ -510,7 +503,6 @@ crbug.com/387740 imported/web-platform-tests/mediacapture-streams/stream-api/mediastream/mediastream-removetrack.html [ Skip ] crbug.com/412381 imported/web-platform-tests/mediacapture-streams/obtaining-local-multimedia-content/navigatorusermedia/empty-option-param.html [ Failure ] -crbug.com/412381 imported/web-platform-tests/mediacapture-streams/obtaining-local-multimedia-content/navigatorusermedia/getusermedia-optional-constraint.html [ Failure ] crbug.com/412381 imported/web-platform-tests/mediacapture-streams/obtaining-local-multimedia-content/navigatorusermedia/getusermedia-trivial-constraint.html [ Failure ] crbug.com/412381 imported/web-platform-tests/mediacapture-streams/obtaining-local-multimedia-content/navigatorusermedia/unknownkey-option-param.html [ Failure ] @@ -519,8 +511,6 @@ crbug.com/325673 imported/web-platform-tests/custom-elements/concepts/custom-elements-type-naming.html [ Failure ] crbug.com/542660 fast/css/absolute-inline-alignment-2.html [ Failure ] -crbug.com/542660 fast/css/absolute-inline-alignment.html [ Failure ] -crbug.com/542660 fast/inline/nested-text-descendants.html [ Failure ] # Ref tests that needs investigation. crbug.com/404597 [ Mac ] fast/css3-text/css3-text-justify/text-justify-crash.html [ Failure ] @@ -562,8 +552,6 @@ crbug.com/552494 virtual/prefer_compositing_to_lcd_text/scrollbars/overflow-scrollbar-combinations.html [ Pass Failure ] crbug.com/552494 virtual/rootlayerscrolls/scrollbars/overflow-scrollbar-combinations.html [ Pass Failure ] -crbug.com/570702 virtual/rootlayerscrolls/scrollbars/custom-scrollbar-changing-style.html [ Failure ] - crbug.com/380217 [ Linux Win ] fast/shapes/shape-outside-floats/shape-outside-floats-inset-rounded-large-radius.html [ Skip ] crbug.com/380217 [ Win ] fast/shapes/shape-outside-floats/shape-outside-floats-inset-rounded-bottom-left.html [ Skip ] @@ -575,14 +563,14 @@ crbug.com/405389 imported/csswg-test/css-shapes-1/shape-outside/supported-shapes/polygon/shape-outside-polygon-017.html [ Failure ] crbug.com/424365 imported/csswg-test/css-shapes-1/shape-outside/shape-image/shape-image-010.html [ Failure ] crbug.com/424365 imported/csswg-test/css-shapes-1/shape-outside/shape-image/shape-image-024.html [ Failure ] -crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-margin-001.html [ Failure ] +crbug.com/441840 [ Linux Win ] imported/csswg-test/css-shapes-1/shape-outside/values/shape-margin-001.html [ Failure ] crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-circle-004.html [ Failure ] crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-circle-005.html [ Failure ] crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-ellipse-004.html [ Failure ] crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-ellipse-005.html [ Failure ] crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-inset-003.html [ Failure ] crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-polygon-004.html [ Failure ] -crbug.com/441840 imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-shape-arguments-000.html [ Failure ] +crbug.com/441840 [ Linux Win ] imported/csswg-test/css-shapes-1/shape-outside/values/shape-outside-shape-arguments-000.html [ Failure ] crbug.com/586413 imported/csswg-test/css-snap-size-1/snap-width-block-in-available-001.html [ Failure ] crbug.com/586413 imported/csswg-test/css-snap-size-1/snap-width-block-in-fixed-001.html [ Failure ] @@ -705,11 +693,6 @@ crbug.com/492664 imported/csswg-test/css-writing-modes-3/clip-rect-vrl-008.xht [ Failure ] crbug.com/492664 imported/csswg-test/css-writing-modes-3/line-box-direction-vrl-009.xht [ Failure ] -crbug.com/549571 [ Mac Win ] fast/text/unicode-fallback-font.html [ NeedsRebaseline ] -crbug.com/549571 [ Win ] css2.1/t1202-counter-04-b.html [ NeedsRebaseline ] -crbug.com/549571 [ Win ] css2.1/t1202-counters-04-b.html [ NeedsRebaseline ] -crbug.com/549571 [ Win ] inspector-protocol/layout-fonts/languages-emoji-rare-glyphs.html [ NeedsRebaseline ] - # These tests pass but images do not match because tests are stricter than the spec. crbug.com/492664 imported/csswg-test/css-writing-modes-3/text-combine-upright-value-all-001.html [ Failure ] crbug.com/492664 imported/csswg-test/css-writing-modes-3/text-combine-upright-value-all-002.html [ Failure ] @@ -961,8 +944,6 @@ # Significant Slimming Paint failure. crbug.com/459305 [ Mac ] svg/custom/foreign-object-skew.svg [ Failure ] -crbug.com/463798 [ Mac ] svg/as-image/svg-invalid-image-1.html [ Failure ] - crbug.com/463358 [ Mac Linux Debug ] css3/masking/clip-path-polygon-evenodd.html [ Failure ] crbug.com/482229 compositing/layer-creation/fixed-position-under-transform.html [ Failure ] @@ -1045,7 +1026,7 @@ crbug.com/479533 accessibility/show-context-menu-shadowdom.html [ Skip ] crbug.com/483653 accessibility/scroll-containers.html [ Skip ] -crbug.com/491764 http/tests/inspector/service-workers/user-agent-override.html [ Timeout ] +crbug.com/491764 http/tests/inspector/service-workers/user-agent-override.html [ Pass Timeout ] crbug.com/474798 fast/repaint/align-self-change-keeping-geometry-grid.html [ Failure ] crbug.com/474798 fast/repaint/justify-self-change-keeping-geometry.html [ Failure ] crbug.com/474798 virtual/spv2/paint/invalidation/spv2/align-self-change-keeping-geometry-grid-as-text.html [ Skip ] @@ -1070,12 +1051,7 @@ crbug.com/321237 [ Win ] fast/multicol/span/pseudo-before-after-in-content.html [ Failure ] crbug.com/321237 [ Win ] fast/selectors/004.html [ Failure ] -# Rebaselines that got missed in the first pass -crbug.com/321237 [ Mac ] fast/text/international/complex-text-leading-space-wrapping.html [ Failure ] -crbug.com/321237 [ Win ] fast/text/international/complex-text-leading-space-wrapping.html [ Failure ] - crbug.com/501659 fast/xsl/xslt-missing-namespace-in-xslt.xml [ Failure ] -crbug.com/501659 http/tests/xmlviewer/dumpAsText/svg.xml [ Failure ] crbug.com/501659 http/tests/security/xss-DENIED-xml-external-entity.xhtml [ Failure ] crbug.com/501659 fast/css/stylesheet-candidate-nodes-crash.xhtml [ Failure ] @@ -1112,6 +1088,9 @@ crbug.com/464736 http/tests/xmlhttprequest/ontimeout-event-override-after-failure.html [ Pass Failure ] +crbug.com/591901 fast/images/color-profile-background-clip-text.html [ NeedsRebaseline ] +crbug.com/591901 fast/images/color-profile-svg-fill-text.html [ NeedsRebaseline ] + crbug.com/521730 [ Win10 ] fast/forms/month-multiple-fields/month-multiple-fields-preserve-value-after-history-back.html [ Failure ] crbug.com/521730 [ Win10 ] fast/forms/month-multiple-fields/month-multiple-fields-value-set-empty.html [ Failure ] crbug.com/521730 [ Win10 ] fast/forms/suggested-value.html [ Failure ] @@ -1224,7 +1203,7 @@ crbug.com/571233 compositing/background-color/background-color-outside-document.html [ Skip ] -crbug.com/331582 fast/inline/justify-emphasis-inline-box.html [ Failure ] +crbug.com/331582 [ Win ] fast/inline/justify-emphasis-inline-box.html [ Failure ] crbug.com/474759 fast/writing-mode/vertical-rl-replaced-selection.html [ Failure ] crbug.com/353746 virtual/android/fullscreen/video-specified-size.html [ Failure Pass ] @@ -1339,17 +1318,12 @@ crbug.com/581038 fast/text/first-letter-bad-line-boxes-crash.html [ Crash Pass ] -# No baselines, but this js test is also showing FAIL -crbug.com/583675 fast/dom/shadow/scoped-events-by-ua-stopped.html [ Failure ] - crbug.com/585724 fast/js/JSON-parse.html [ NeedsManualRebaseline ] crbug.com/587136 [ Linux Debug ] http/tests/security/xss-DENIED-cross-origin-stack-overflow.html [ Timeout Pass ] crbug.com/587593 [ Android ] fast/js/pic/cached-single-entry-transition.html [ Pass Failure ] -crbug.com/587950 [ Mac Win ] virtual/threaded/animations/background-shorthand-crash.html [ Failure Crash ] - crbug.com/588061 [ Debug ] inspector/sources/debugger-breakpoints/debugger-reload-breakpoints-with-source-maps.html [ Pass Failure ] crbug.com/248063 [ Win ] plugins/plugin-clip-subframe.html [ Pass Failure ] @@ -1369,6 +1343,8 @@ crbug.com/257405 http/tests/websocket/bad-sub-protocol-control-chars.html [ NeedsManualRebaseline ] crbug.com/257405 inspector/console/console-control-characters.html [ NeedsManualRebaseline ] +crbug.com/591821 fast/events/iframe-object-onload.html [ Failure Pass ] +crbug.com/591821 [ Linux Win ] fast/events/menu-key-context-menu-document.html [ Failure Pass ] crbug.com/591821 fast/events/keyboard-scroll-by-page.html [ Failure Pass ] crbug.com/591821 fast/events/mouse-cursor-no-mousemove.html [ Failure Pass ] crbug.com/591821 fast/events/mouse-cursor-style-change-iframe.html [ Failure Pass ] @@ -1379,7 +1355,11 @@ crbug.com/591821 fast/events/mouse-event-buttons-attribute.html [ Failure Pass ] crbug.com/591821 fast/events/mouse-relative-position.html [ Failure Pass ] crbug.com/591821 fast/events/mouse-wheel-main-frame-scroll.html [ Pass Timeout ] +crbug.com/591821 fast/events/scale-and-scroll-iframe-body.html [ Pass Timeout ] +crbug.com/591821 fast/events/updateLayoutForHitTest.html [ Pass Timeout ] +crbug.com/591821 virtual/pointerevent/fast/events/iframe-object-onload.html [ Failure Pass ] crbug.com/591821 virtual/pointerevent/fast/events/keyboard-scroll-by-page.html [ Failure Pass ] +crbug.com/591821 [ Linux Win ] virtual/pointerevent/fast/events/menu-key-context-menu-document.html [ Failure Pass ] crbug.com/591821 virtual/pointerevent/fast/events/mouse-cursor-no-mousemove.html [ Failure Pass ] crbug.com/591821 virtual/pointerevent/fast/events/mouse-cursor-style-change-iframe.html [ Failure Pass ] crbug.com/591821 virtual/pointerevent/fast/events/mouse-double-triple-click-should-not-select-next-node-for-user-select-none.html [ Failure Pass ] @@ -1389,7 +1369,12 @@ crbug.com/591821 virtual/pointerevent/fast/events/mouse-event-buttons-attribute.html [ Failure Pass ] crbug.com/591821 virtual/pointerevent/fast/events/mouse-relative-position.html [ Failure Pass ] crbug.com/591821 virtual/pointerevent/fast/events/mouse-wheel-main-frame-scroll.html [ Pass Timeout ] +crbug.com/591821 virtual/pointerevent/fast/events/scale-and-scroll-iframe-body.html [ Failure Pass ] +crbug.com/591821 virtual/pointerevent/fast/events/scale-and-scroll-iframe-window.html [ Failure Pass ] +crbug.com/591821 virtual/pointerevent/fast/events/updateLayoutForHitTest.html [ Failure Pass ] +crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/iframe-object-onload.html [ Failure Pass ] crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/keyboard-scroll-by-page.html [ Failure Pass ] +crbug.com/591821 [ Linux Win ] virtual/trustedeventsdefaultaction/fast/events/menu-key-context-menu-document.html [ Failure Pass ] crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/mouse-cursor-no-mousemove.html [ Failure Pass ] crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/mouse-cursor-style-change-iframe.html [ Failure Pass ] crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/mouse-double-triple-click-should-not-select-next-node-for-user-select-none.html [ Failure Pass ] @@ -1399,6 +1384,8 @@ crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/mouse-event-buttons-attribute.html [ Failure Pass ] crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/mouse-relative-position.html [ Failure Pass ] crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/mouse-wheel-main-frame-scroll.html [ Pass Timeout ] +crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/scale-and-scroll-iframe-body.html [ Failure Pass ] +crbug.com/591821 virtual/trustedeventsdefaultaction/fast/events/updateLayoutForHitTest.html [ Failure Pass ] crbug.com/591825 [ Mac10.11 Debug ] fast/text/selection-multiple-runs.html [ Failure ] @@ -1420,7 +1407,9 @@ crbug.com/591832 [ Mac10.10 Mac10.11 Retina ] compositing/squashing/squash-partial-repaint-inside-squashed-layer.html [ Failure ] crbug.com/591832 [ Mac10.10 Mac10.11 Retina ] compositing/squashing/squashing-inside-preserve-3d-element.html [ Failure ] -crbug.com/591901 [ Mac10.11 Retina ] fast/images/color-profile-background-clip-text.html [ Failure ] -crbug.com/591901 [ Mac10.11 Retina ] fast/images/color-profile-svg-fill-text.html [ Failure ] - crbug.com/591902 [ Linux Mac10.10 Mac10.11 Retina ] http/tests/security/contentTypeOptions/nosniff-script-without-content-type-blocked.html [ Failure ] + +crbug.com/592183 usb/usbDevice.html [ Timeout Pass ] + +crbug.com/592185 fast/repaint/fixed-right-in-page-scale.html [ Failure Pass ] +
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options-expected.txt b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options-expected.txt index 5faf527..32a5aeb 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options-expected.txt
@@ -115,6 +115,62 @@ PASS This pixel is transparent black PASS This pixel is transparent black PASS This pixel is transparent black +Checking HTMLVideoElement with imageOrientation: none with premultiplyAlphaOption: premultiply. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black Checking HTMLVideoElement with imageOrientation: none with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLVideoElement with imageOrientation: flipY with premultiplyAlphaOption: default. @@ -229,12 +285,70 @@ PASS This pixel is transparent black PASS This pixel is transparent black PASS This pixel is transparent black +Checking HTMLVideoElement with imageOrientation: flipY with premultiplyAlphaOption: premultiply. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is opaque +PASS This pixel is opaque +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black +PASS This pixel is transparent black Checking HTMLVideoElement with imageOrientation: flipY with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLVideoElement with imageOrientation: invalid with premultiplyAlphaOption: default. PASS createImageBitmap with invalid options are rejected Checking HTMLVideoElement with imageOrientation: invalid with premultiplyAlphaOption: none. PASS createImageBitmap with invalid options are rejected +Checking HTMLVideoElement with imageOrientation: invalid with premultiplyAlphaOption: premultiply. +PASS createImageBitmap with invalid options are rejected Checking HTMLVideoElement with imageOrientation: invalid with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options.html index 753ef90..a08367b4 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-video-with-options.html
@@ -51,10 +51,10 @@ var bitmap; var video; var imageOrientationOptions = ["none", "flipY", "invalid"]; -var premultiplyAlphaOptions = ["default", "none", "invalid"]; -var optionIndexArray = [[0, 0], [0, 1], [0, 2], - [1, 0], [1, 1], [1, 2], - [2, 0], [2, 1], [2, 2]]; +var premultiplyAlphaOptions = ["default", "none", "premultiply", "invalid"]; +var optionIndexArray = [[0, 0], [0, 1], [0, 2], [0, 3], + [1, 0], [1, 1], [1, 2], [1, 3], + [2, 0], [2, 1], [2, 2], [2, 3]]; var optionIndex = 0; var canvas = document.createElement("canvas"); @@ -98,8 +98,7 @@ videoLoaded(); }, function(ex) { // when the options are invalid, we expect the promise to be rejected. - if ((imageOrientationOptions[optionIndex1] != "none" && imageOrientationOptions[optionIndex1] != "flipY") || - (premultiplyAlphaOptions[optionIndex2] != "default" && premultiplyAlphaOptions[optionIndex2] != "none")) { + if (imageOrientationOptions[optionIndex1] == "invalid" || premultiplyAlphaOptions[optionIndex2] == "invalid") { testPassed("createImageBitmap with invalid options are rejected"); optionIndex++; videoLoaded();
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options-expected.txt b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options-expected.txt index fcadb19..2ebb350d 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options-expected.txt
@@ -189,6 +189,97 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking HTMLImageElement with imageOrientation: none with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking HTMLImageElement with imageOrientation: none with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLImageElement with imageOrientation: flipY with premultiplyAlphaOption: default. @@ -377,12 +468,107 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking HTMLImageElement with imageOrientation: flipY with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is blue. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking HTMLImageElement with imageOrientation: flipY with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLImageElement with imageOrientation: invalid with premultiplyAlphaOption: default. PASS createImageBitmap with invalid options are rejected Checking HTMLImageElement with imageOrientation: invalid with premultiplyAlphaOption: none. PASS createImageBitmap with invalid options are rejected +Checking HTMLImageElement with imageOrientation: invalid with premultiplyAlphaOption: premultiply. +PASS createImageBitmap with invalid options are rejected Checking HTMLImageElement with imageOrientation: invalid with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLCanvasElement with imageOrientation: none with premultiplyAlphaOption: default. @@ -567,6 +753,97 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking HTMLCanvasElement with imageOrientation: none with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking HTMLCanvasElement with imageOrientation: none with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLCanvasElement with imageOrientation: flipY with premultiplyAlphaOption: default. @@ -755,12 +1032,107 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking HTMLCanvasElement with imageOrientation: flipY with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is blue. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking HTMLCanvasElement with imageOrientation: flipY with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking HTMLCanvasElement with imageOrientation: invalid with premultiplyAlphaOption: default. PASS createImageBitmap with invalid options are rejected Checking HTMLCanvasElement with imageOrientation: invalid with premultiplyAlphaOption: none. PASS createImageBitmap with invalid options are rejected +Checking HTMLCanvasElement with imageOrientation: invalid with premultiplyAlphaOption: premultiply. +PASS createImageBitmap with invalid options are rejected Checking HTMLCanvasElement with imageOrientation: invalid with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking ImageData with imageOrientation: none with premultiplyAlphaOption: default. @@ -945,6 +1317,97 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking ImageData with imageOrientation: none with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking ImageData with imageOrientation: none with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking ImageData with imageOrientation: flipY with premultiplyAlphaOption: default. @@ -1133,12 +1596,107 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking ImageData with imageOrientation: flipY with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is blue. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking ImageData with imageOrientation: flipY with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking ImageData with imageOrientation: invalid with premultiplyAlphaOption: default. PASS createImageBitmap with invalid options are rejected Checking ImageData with imageOrientation: invalid with premultiplyAlphaOption: none. PASS createImageBitmap with invalid options are rejected +Checking ImageData with imageOrientation: invalid with premultiplyAlphaOption: premultiply. +PASS createImageBitmap with invalid options are rejected Checking ImageData with imageOrientation: invalid with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking ImageBitmap with imageOrientation: none with premultiplyAlphaOption: default. @@ -1323,6 +1881,97 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking ImageBitmap with imageOrientation: none with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking ImageBitmap with imageOrientation: none with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking ImageBitmap with imageOrientation: flipY with premultiplyAlphaOption: default. @@ -1511,12 +2160,107 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking ImageBitmap with imageOrientation: flipY with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is blue. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking ImageBitmap with imageOrientation: flipY with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking ImageBitmap with imageOrientation: invalid with premultiplyAlphaOption: default. PASS createImageBitmap with invalid options are rejected Checking ImageBitmap with imageOrientation: invalid with premultiplyAlphaOption: none. PASS createImageBitmap with invalid options are rejected +Checking ImageBitmap with imageOrientation: invalid with premultiplyAlphaOption: premultiply. +PASS createImageBitmap with invalid options are rejected Checking ImageBitmap with imageOrientation: invalid with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking Blob with imageOrientation: none with premultiplyAlphaOption: default. @@ -1701,6 +2445,97 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking Blob with imageOrientation: none with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking Blob with imageOrientation: none with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking Blob with imageOrientation: flipY with premultiplyAlphaOption: default. @@ -1889,12 +2724,107 @@ PASS This pixel is transparent black. PASS This pixel is transparent black. PASS This pixel is transparent black. +Checking Blob with imageOrientation: flipY with premultiplyAlphaOption: premultiply. +Check no crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is imageWidth +PASS bitmap.height is imageHeight +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop center. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop right. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 60 +PASS bitmap.height is 60 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is blue. +PASS This pixel is blue. +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is green. +PASS This pixel is green. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check over crop right. +PASS bitmap.width is 50 +PASS bitmap.height is 50 +PASS This pixel is black. +PASS This pixel is black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check crop. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 10 +PASS bitmap.height is 10 +PASS This pixel is red. +PASS This pixel is red. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +Check empty. +PASS jsWrapperClass(bitmap) is 'ImageBitmap' +PASS bitmap.width is 30 +PASS bitmap.height is 30 +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. +PASS This pixel is transparent black. Checking Blob with imageOrientation: flipY with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected Checking Blob with imageOrientation: invalid with premultiplyAlphaOption: default. PASS createImageBitmap with invalid options are rejected Checking Blob with imageOrientation: invalid with premultiplyAlphaOption: none. PASS createImageBitmap with invalid options are rejected +Checking Blob with imageOrientation: invalid with premultiplyAlphaOption: premultiply. +PASS createImageBitmap with invalid options are rejected Checking Blob with imageOrientation: invalid with premultiplyAlphaOption: invalid. PASS createImageBitmap with invalid options are rejected PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options.html index dd8d311..d7a5bdc 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-createImageBitmap-drawImage-with-options.html
@@ -163,10 +163,10 @@ // check all elements elements = [image, aCanvas, d, testBitmap, blob]; imageOrientationOptions = ["none", "flipY", "invalid"]; - premultiplyAlphaOptions = ["default", "none", "invalid"]; - optionIndexArray = [[0, 0], [0, 1], [0, 2], - [1, 0], [1, 1], [1, 2], - [2, 0], [2, 1], [2, 2]]; + premultiplyAlphaOptions = ["default", "none", "premultiply", "invalid"]; + optionIndexArray = [[0, 0], [0, 1], [0, 2], [0, 3], + [1, 0], [1, 1], [1, 2], [1, 3], + [2, 0], [2, 1], [2, 2], [2, 3]]; // wait for callback to finish before each check to ensure synchronous behavior nextCheck(0, 0); } @@ -207,8 +207,7 @@ nextCheck(elementIndex, optionIndex + 1); }, function() { // when the options are invalid, we expect the promise to be rejected. - if ((imageOrientationOptions[optionIndex1] != "none" && imageOrientationOptions[optionIndex1] != "flipY") || - (premultiplyAlphaOptions[optionIndex2] != "default" && premultiplyAlphaOptions[optionIndex2] != "none")) { + if (imageOrientationOptions[optionIndex1] == "invalid" || premultiplyAlphaOptions[optionIndex2] == "invalid") { testPassed("createImageBitmap with invalid options are rejected"); if (optionIndex == optionIndexArray.length - 1) nextCheck(elementIndex + 1, 0);
diff --git a/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-cascade-trick-2-expected.txt b/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-cascade-trick-2-expected.txt deleted file mode 100644 index 8ac6345e..0000000 --- a/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-cascade-trick-2-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Custom property sets can be extended with the (self-referential) cascade trick assert_equals: expected "rgb(0, 128, 0)" but got "rgb(255, 0, 0)" -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-override-custom-property-expected.txt b/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-override-custom-property-expected.txt deleted file mode 100644 index 58fff47..0000000 --- a/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-override-custom-property-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL @apply can override custom properties assert_equals: expected "rgb(0, 128, 0)" but got "rgb(255, 0, 0)" -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-override-self-expected.txt b/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-override-self-expected.txt deleted file mode 100644 index 319717c23..0000000 --- a/third_party/WebKit/LayoutTests/fast/css/atapply/at-apply-override-self-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL @apply can override the custom property it applies assert_equals: expected "rgb(0, 128, 0)" but got "rgba(0, 0, 0, 0)" -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/fast/css/pseudo-default-checkbox-radio.html b/third_party/WebKit/LayoutTests/fast/css/pseudo-default-checkbox-radio.html new file mode 100644 index 0000000..6ded0ff --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/css/pseudo-default-checkbox-radio.html
@@ -0,0 +1,51 @@ +<!DOCTYPE html> +<html> +<head> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +</head> +<body> +<form method="get"> +<input name="y" type="checkbox" checked /> +<input name="y" type ="radio" checked /> +<input id="c1" name="y" type="checkbox" /> +<input id="r1" name="y" type="radio" /> +<input id="c2" name="n" type="checkbox" /> +<input id="r2" name="n" type="radio" /> +<input name="n" type="checkbox" /> +<input name="n" type="radio" /> +<input name="n" type="text" checked /> +<input name="n" type="password" checked /> +<input name="n" type="button" checked /> +<input name="n" type="file" checked /> +<input name="n" type="reset" checked /> +<input name="n" type="search" checked /> +<input name="n" type="email" checked /> +<input name="n" type="url" checked /> +<input name="n" type="tel" checked /> +<input name="n" type="number" checked /> +<input name="n" type="range" checked /> +<input name="n" type="date" checked /> +<input name="n" type="month" checked /> +<input name="n" type="week" checked /> +<input name="n" type="time" checked /> +<input name="n" type="date-time" checked /> +<input name="n" type="datetime-local" checked /> +<input name="n" type="color" checked /> +</form> +<script> +test(function() { + document.getElementById("c1").defaultChecked = true; + document.getElementById("r1").defaultChecked = true; + document.getElementById("c2").checked = true; + document.getElementById("r2").checked = true; + u = document.getElementsByName("n"); + for (i = 0; i < u.length; i++) + assert_false(u[i].matches(":default")); + v = document.getElementsByName("y"); + for (i = 0; i < v.length; i++) + assert_true(v[i].matches(":default")); +}, "This test performs a check for the input types which are checkable having checked attribute to be considered for :default CSS selector."); +</script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/fast/css/pseudo-default-option.html b/third_party/WebKit/LayoutTests/fast/css/pseudo-default-option.html new file mode 100644 index 0000000..d762b89 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/css/pseudo-default-option.html
@@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html> +<head> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +</head> +<body> +<form method="get"> +<select> +<option name="n">1</option> +<option name="y" selected>2</option> +<option id="o1" name="y">3</option> +<option id="o2" name="n">4</option> +</select> +</form> +<script> +test(function() { + document.getElementById("o1").defaultSelected = true; + document.getElementById("o2").selected = true; + u = document.getElementsByName("n"); + for (i = 0; i < u.length; i++) + assert_false(u[i].matches(":default")); + v = document.getElementsByName("y"); + for (i = 0; i < v.length; i++) + assert_true(v[i].matches(":default")); +}, "This test performs a check for option elements having selected attribute to be considered for :default CSS selector."); +</script> +</body> +</html> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Attr/dir-empty-attribute-value-expected.html b/third_party/WebKit/LayoutTests/fast/dom/dir-empty-attribute-value-expected.html similarity index 100% rename from third_party/WebKit/LayoutTests/fast/dom/Attr/dir-empty-attribute-value-expected.html rename to third_party/WebKit/LayoutTests/fast/dom/dir-empty-attribute-value-expected.html
diff --git a/third_party/WebKit/LayoutTests/fast/dom/Attr/dir-empty-attribute-value.html b/third_party/WebKit/LayoutTests/fast/dom/dir-empty-attribute-value.html similarity index 100% rename from third_party/WebKit/LayoutTests/fast/dom/Attr/dir-empty-attribute-value.html rename to third_party/WebKit/LayoutTests/fast/dom/dir-empty-attribute-value.html
diff --git a/third_party/WebKit/LayoutTests/fast/dom/document-all-use-counters.html b/third_party/WebKit/LayoutTests/fast/dom/document-all-use-counters.html new file mode 100644 index 0000000..5ed692e --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/dom/document-all-use-counters.html
@@ -0,0 +1,87 @@ +<!DOCTYPE html> +<title>document.all UseCounters</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +test(function() { + const DocumentAllItemNoArguments = 1252; // From UseCounter.h + assert_false(internals.isUseCounted(document, DocumentAllItemNoArguments)); + document.all.item(); + assert_true(internals.isUseCounted(document, DocumentAllItemNoArguments)); +}, 'document.all.item with no arguments'); + +test(function() { + const DocumentAllItemNamed = 1253; // From UseCounter.h + assert_false(internals.isUseCounted(document, DocumentAllItemNamed)); + document.all.item('x'); + assert_true(internals.isUseCounted(document, DocumentAllItemNamed)); +}, 'document.all.item with name'); + +test(function() { + const DocumentAllItemIndexed = 1254; // From UseCounter.h + document.all.item(-1); + document.all.item(4294967295); + assert_false(internals.isUseCounted(document, DocumentAllItemIndexed)); + document.all.item(4294967294); + assert_true(internals.isUseCounted(document, DocumentAllItemIndexed)); +}, 'document.all.item with index'); + +test(function() { + const DocumentAllItemIndexedWithNonNumber = 1255; // From UseCounter.h + document.all.item(0); + document.all.item(0.5); + document.all.item(NaN); + document.all.item(Infinity); + document.all.item('-1'); + document.all.item('00'); + document.all.item('4294967295'); + assert_false(internals.isUseCounted(document, DocumentAllItemIndexedWithNonNumber)); + document.all.item('4294967294'); + assert_true(internals.isUseCounted(document, DocumentAllItemIndexedWithNonNumber)); +}, 'document.all.item with index as string'); + +test(function() { + const DocumentAllLegacyCallNoArguments = 1256; // From UseCounter.h + assert_false(internals.isUseCounted(document, DocumentAllLegacyCallNoArguments)); + document.all(); + assert_true(internals.isUseCounted(document, DocumentAllLegacyCallNoArguments)); +}, 'document.all legacy call with no arguments'); + +test(function() { + const DocumentAllLegacyCallNamed = 1257; // From UseCounter.h + assert_false(internals.isUseCounted(document, DocumentAllLegacyCallNamed)); + document.all('x'); + assert_true(internals.isUseCounted(document, DocumentAllLegacyCallNamed)); +}, 'document.all legacy call with name'); + +test(function() { + const DocumentAllLegacyCallIndexed = 1258; // From UseCounter.h + document.all(-1); + document.all(4294967295); + assert_false(internals.isUseCounted(document, DocumentAllLegacyCallIndexed)); + document.all(4294967294); + assert_true(internals.isUseCounted(document, DocumentAllLegacyCallIndexed)); +}, 'document.all legacy call with index'); + +test(function() { + const DocumentAllLegacyCallIndexedWithNonNumber = 1259; // From UseCounter.h + document.all(0); + document.all(0.5); + document.all(NaN); + document.all(Infinity); + document.all('-1'); + document.all('00'); + document.all('4294967295'); + assert_false(internals.isUseCounted(document, DocumentAllLegacyCallIndexedWithNonNumber)); + document.all('4294967294'); + assert_true(internals.isUseCounted(document, DocumentAllLegacyCallIndexedWithNonNumber)); +}, 'document.all legacy call with index as a non-number (string)'); + +test(function() { + const DocumentAllLegacyCallTwoArguments = 1260; // From UseCounter.h + document.all('x'); + assert_false(internals.isUseCounted(document, DocumentAllLegacyCallTwoArguments)); + document.all('x', 0); + assert_true(internals.isUseCounted(document, DocumentAllLegacyCallTwoArguments)); +}, 'document.all legacy call with two arguments'); +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots-expected.txt b/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots-expected.txt index 05e0460..b40f654 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots-expected.txt +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots-expected.txt
@@ -11,12 +11,14 @@ PASS Should move from host//older-B to host///younger-B in forward PASS -Should move from host///younger-B to B in forward -Expected innermost activeElement is B, but actual innermost activeElement is #light-child-B -FAIL -Should move from B to host///younger-B in backward -Expected innermost activeElement is host///younger-B, but actual innermost activeElement is #light-child-B -FAIL +Should move from host///younger-B to light-child-B in forward +PASS +Should move from light-child-B to B in forward +PASS +Should move from B to light-child-B in backward +PASS +Should move from light-child-B to host///younger-B in backward +PASS Should move from host///younger-B to host//older-B in backward PASS Should move from host//older-B to host//older-A in backward
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots.html b/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots.html index 04513ed..c1cfa99 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots.html +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/focus-navigation-with-multiple-shadow-roots.html
@@ -48,6 +48,7 @@ 'host//older-A', 'host//older-B', 'host///younger-B', + 'light-child-B', 'B', ];
diff --git a/third_party/WebKit/LayoutTests/fast/dom/shadow/tabindex-slot.html b/third_party/WebKit/LayoutTests/fast/dom/shadow/tabindex-slot.html new file mode 100644 index 0000000..d5f73ce --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/dom/shadow/tabindex-slot.html
@@ -0,0 +1,89 @@ +<!DOCTYPE html> +<script src='../../../resources/testharness.js'></script> +<script src='../../../resources/testharnessreport.js'></script> +<script src='resources/shadow-dom.js'></script> +<div id="log"></div> +<p> + document tree: [i0 -> [x-foo]]<br> + x-foo's shadow tree: [j5 -> [x-bar] -> j6]<br> + x-bar's shadow tree: [k1 -> k0 -> [s2]]<br> + slot #s2: [j1 -> j2 -> j3 -> j4 -> [s1] -> j0]<br><br> + slot #s1: [i1 -> i2]<br> + <b>v1 ideal nav forward: [i0 -> j5 -> xbar -> k1 -> k0 -> j1 -> j2 -> j3 -> j4 -> i1 -> i2 -> j0 -> j6]</b><br> +</p> + + <input id="i0" tabindex=0 value="i0"> + <div id="x-foo"> + <input id="i2" slot="s1" tabindex=2 value="i2"> + <input id="i1" slot="s1" tabindex=1 value="i1"> + <template data-mode="open"> + <div id="x-bar" tabindex=4> + <input id="j1" slot="s2" tabindex=1 value="j1"> + <slot id="s1" name="s1" slot="s2"></slot> + <input id="j0" slot="s2" tabindex=0 value="j0"> + <input id="j3" slot="s2" tabindex=2 value="j3"> + <div id="j4" slot="s2" tabindex=3> + <input id="j2" tabindex=1 value="j2"> + </div> + <template data-mode="open"> + <input id="k0" tabindex=0 value="k0"> + <slot id="s2" name="s2"></slot> + <input id="k1" tabindex=1 value="k1"> + </template> + </div> + <input id="j6" tabindex=4 value="j6"> + <input id="j5" tabindex=3 value="j5"> + </template> + </div> +</div> + +<script> + +function shouldCustomNavigateFocus(from, to, direction) +{ + var fromElement = getNodeInComposedTree(from); + if (!fromElement) { + return; + } + fromElement.focus(); + if (!isInnermostActiveElement(from)) { + return; + } + if (direction == 'forward') + navigateFocusForward(); + else + navigateFocusBackward(); + return isInnermostActiveElement(to); +} + +test(function() { + var xfoo = document.getElementById('x-foo'); + convertTemplatesToShadowRootsWithin(xfoo); + var sr = xfoo.shadowRoot; + var xbar = sr.querySelector('div'); + convertTemplatesToShadowRootsWithin(xbar); + + var elements = [ + 'i0', + 'x-foo/j5', + 'x-foo/x-bar', + 'x-foo/x-bar/k1', + 'x-foo/x-bar/k0', + 'x-foo/j1', + 'x-foo/j2', + 'x-foo/j3', + 'x-foo/j4', + 'i1', + 'i2', + 'x-foo/j0', + 'x-foo/j6' + ]; + + for (var i = 0; i + 1 < elements.length; ++i) + assert_true(shouldCustomNavigateFocus(elements[i], elements[i + 1], 'forward'), elements[i]+" to "+ elements[i+1]); + elements.reverse(); + for (var i = 0; i + 1 < elements.length; ++i) + assert_true(shouldCustomNavigateFocus(elements[i], elements[i + 1], 'backward'), elements[i]+" to "+ elements[i+1]); +}, 'Focus controller should treat slots as a focus scope.'); + +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/images/color-profile-background-clip-text.html b/third_party/WebKit/LayoutTests/fast/images/color-profile-background-clip-text.html index e5e0ae8..ff543322 100644 --- a/third_party/WebKit/LayoutTests/fast/images/color-profile-background-clip-text.html +++ b/third_party/WebKit/LayoutTests/fast/images/color-profile-background-clip-text.html
@@ -5,16 +5,16 @@ <style> p { -webkit-text-fill-color: transparent; - background: url("resources/red-at-12-oclock-with-color-profile.jpg") -10px 100px; + background: url("resources/red-at-12-oclock-with-color-profile.jpg") -20px 100px; -webkit-background-clip: text; - font: 147pt Ahem, sans-serif; + font: 190px Ahem, sans-serif; position: relative; - top: -220pt; + top: -300px; } p + p { - top: -480pt; + top: -650px; } </style>
diff --git a/third_party/WebKit/LayoutTests/fast/images/color-profile-svg-fill-text.html b/third_party/WebKit/LayoutTests/fast/images/color-profile-svg-fill-text.html index bf62265..4f809a9 100644 --- a/third_party/WebKit/LayoutTests/fast/images/color-profile-svg-fill-text.html +++ b/third_party/WebKit/LayoutTests/fast/images/color-profile-svg-fill-text.html
@@ -8,7 +8,7 @@ <pattern id="pattern" patternUnits="userSpaceOnUse" y="20" width="400" height="120" patternTransform="scale(0.4)"> <image onload="top.load()" xlink:href="resources/red-at-12-oclock-with-color-profile.jpg" width="400" height="400"/> </pattern> - <text x="10" y="0.5em" style="fill: url(#pattern); font: 108pt Ahem, sans-serif; -webkit-font-smoothing: none;"> + <text x="10" y="70" style="fill: url(#pattern); font: 140px Ahem, sans-serif; -webkit-font-smoothing: none;"> ▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅ </text> </svg>
diff --git a/third_party/WebKit/LayoutTests/fast/speech/scripted/speechrecognition-restart-onend-expected.txt b/third_party/WebKit/LayoutTests/fast/speech/scripted/speechrecognition-restart-onend-expected.txt new file mode 100644 index 0000000..d6e7ce07 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/speech/scripted/speechrecognition-restart-onend-expected.txt
@@ -0,0 +1,9 @@ +Verify that calling start() during onend does not crash. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/fast/speech/scripted/speechrecognition-restart-onend.html b/third_party/WebKit/LayoutTests/fast/speech/scripted/speechrecognition-restart-onend.html new file mode 100644 index 0000000..cae9057 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/speech/scripted/speechrecognition-restart-onend.html
@@ -0,0 +1,22 @@ +<!DOCTYPE HTML> +<html> +<head> +<script src="../../../resources/js-test.js"></script> +</head> +<body> +<script> +description("Verify that calling start() during onend does not crash."); + +self.jsTestIsAsync = true; + +if (window.testRunner) { + testRunner.dumpAsText(); + testRunner.waitUntilDone(); +} + +var recog = new webkitSpeechRecognition(); +recog.onend = function () { recog.start(); setTimeout(finishJSTest); }; +recog.start(); +</script> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-expected.html b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-expected.html new file mode 100644 index 0000000..ee8db18 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-expected.html
@@ -0,0 +1,17 @@ +<svg style="display: block; width: 0; height: 0"> + <defs> + <filter id="blur"> + <feGaussianBlur stdDeviation="3 3"/> + </filter> + </defs> +</svg> +<canvas id="canvas" width="100" height="100"></canvas> +<script> +var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); +ctx.fillStyle = '#0f0'; +ctx.fillRect(0, 0, 90, 90); +ctx.filter = 'url(#blur)'; +ctx.fillStyle = '#f00'; +ctx.fillRect(20, 20, 30, 30); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-multiple-expected.html b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-multiple-expected.html new file mode 100644 index 0000000..c563a859 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-multiple-expected.html
@@ -0,0 +1,24 @@ +<svg style="display: block; width: 0; height: 0"> + <defs> + <filter id="blur"> + <feGaussianBlur stdDeviation="3 3"/> + </filter> + <filter id="hue-rotate" color-interpolation-filters="sRGB"> + <feColorMatrix type="hueRotate" values="90"/> + </filter> + </defs> +</svg> +<canvas id="canvas" width="100" height="100"></canvas> +<script> +var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); +ctx.fillStyle = '#0f0'; +ctx.fillRect(0, 0, 100, 100); +ctx.fillStyle = '#f00'; +ctx.filter = 'url(#blur)'; +ctx.fillRect(10, 10, 20, 20); +ctx.filter = 'url(#hue-rotate)'; +ctx.fillRect(40, 40, 20, 20); +ctx.filter = 'url(#blur)'; +ctx.fillRect(70, 70, 20, 20); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-multiple.html b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-multiple.html new file mode 100644 index 0000000..ee7bdf6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external-multiple.html
@@ -0,0 +1,46 @@ +<canvas id="canvas" width="100" height="100"></canvas> +<script> +function draw() { + var canvas = document.getElementById('canvas'); + var ctx = canvas.getContext('2d'); + ctx.fillStyle = '#0f0'; + ctx.fillRect(0, 0, 100, 100); + ctx.fillStyle = '#f00'; + ctx.filter = 'url(resources/blur.svg#blur)'; + ctx.fillRect(10, 10, 20, 20); + ctx.filter = 'url(resources/hue-rotate.svg#hue-rotate)'; + ctx.fillRect(40, 40, 20, 20); + ctx.filter = 'url(resources/blur.svg#blur)'; + ctx.fillRect(70, 70, 20, 20); + + if (window.testRunner) + testRunner.notifyDone(); +} + +function filterLoaded() { + loadedFilterCount++; + if (loadedFilterCount == 2) + draw(); +} + +if (window.testRunner) + testRunner.waitUntilDone(); + +var loadedFilterCount = 0; + +var svgElement = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); +svgElement.setAttribute('width', '0'); +svgElement.setAttribute('height', '0'); + +var useElement = document.createElementNS("http://www.w3.org/2000/svg", 'use'); +useElement.addEventListener("load", filterLoaded); +useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', "resources/blur.svg#blur"); +svgElement.appendChild(useElement); + +useElement = document.createElementNS("http://www.w3.org/2000/svg", 'use'); +useElement.addEventListener("load", filterLoaded); +useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', "resources/hue-rotate.svg#hue-rotate"); +svgElement.appendChild(useElement); + +document.body.appendChild(svgElement); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external.html b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external.html new file mode 100644 index 0000000..4402f5a --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/canvas/canvas-filter-svg-external.html
@@ -0,0 +1,27 @@ +<canvas id="canvas" width="100" height="100"></canvas> +<script> +function draw() { + var canvas = document.getElementById('canvas'); + var ctx = canvas.getContext('2d'); + ctx.fillStyle = '#0f0'; + ctx.fillRect(0, 0, 90, 90); + ctx.filter = 'url(resources/blur.svg#blur)'; + ctx.fillStyle = '#f00'; + ctx.fillRect(20, 20, 30, 30); + + if (window.testRunner) + testRunner.notifyDone(); +} + +if (window.testRunner) + testRunner.waitUntilDone(); + +var svgElement = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); +svgElement.setAttribute('width', '0'); +svgElement.setAttribute('height', '0'); +var useElement = document.createElementNS("http://www.w3.org/2000/svg", 'use'); +useElement.addEventListener("load", draw); +useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', "resources/blur.svg#blur"); +svgElement.appendChild(useElement); +document.body.appendChild(svgElement); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/canvas/resources/blur.svg b/third_party/WebKit/LayoutTests/http/tests/canvas/resources/blur.svg new file mode 100644 index 0000000..21331ac --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/canvas/resources/blur.svg
@@ -0,0 +1,7 @@ +<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg" version="1.1"> + <defs> + <filter id="blur"> + <feGaussianBlur stdDeviation="3 3"/> + </filter> + </defs> +</svg>
diff --git a/third_party/WebKit/LayoutTests/http/tests/canvas/resources/hue-rotate.svg b/third_party/WebKit/LayoutTests/http/tests/canvas/resources/hue-rotate.svg new file mode 100644 index 0000000..5a447522 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/canvas/resources/hue-rotate.svg
@@ -0,0 +1,7 @@ +<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg" version="1.1"> + <defs> + <filter id="hue-rotate" color-interpolation-filters="sRGB"> + <feColorMatrix type="hueRotate" values="90"/> + </filter> + </defs> +</svg>
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector-enabled/dedicated-workers-list.html b/third_party/WebKit/LayoutTests/http/tests/inspector-enabled/dedicated-workers-list.html index 1ef555ab..d94a79fbe 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector-enabled/dedicated-workers-list.html +++ b/third_party/WebKit/LayoutTests/http/tests/inspector-enabled/dedicated-workers-list.html
@@ -31,7 +31,7 @@ { InspectorTest.WorkerAgent.disable(); // Debugger should not crash when autoconnecting is immediately followed by termination. - InspectorTest.WorkerAgent.setAutoconnectToWorkers(true, didDisableWorkerInspection); + InspectorTest.WorkerAgent.setWaitForDebuggerOnStart(true, didDisableWorkerInspection); function didDisableWorkerInspection() {
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/timeline-test.js b/third_party/WebKit/LayoutTests/http/tests/inspector/timeline-test.js index e5e8d95..6b13a87 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/timeline-test.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/timeline-test.js
@@ -61,6 +61,38 @@ return "{reason: " + cause.reason + ", stackTrace: " + stackTrace + "}"; } +InspectorTest.preloadPanel("timeline"); +WebInspector.TempFile = InspectorTest.TempFileMock; + +InspectorTest.createTracingModel = function() +{ + return new WebInspector.TracingModel(new WebInspector.TempFileBackingStorage("tracing")); +} + +InspectorTest.tracingModel = function() +{ + return WebInspector.panels.timeline._tracingModel; +} + +InspectorTest.invokeWithTracing = function(functionName, callback, additionalCategories, enableJSSampling) +{ + var categories = "-*,disabled-by-default-devtools.timeline*,devtools.timeline," + WebInspector.TracingModel.TopLevelEventCategory; + if (additionalCategories) + categories += "," + additionalCategories; + InspectorTest.timelineController()._startRecordingWithCategories(categories, enableJSSampling, tracingStarted); + + function tracingStarted() + { + InspectorTest.invokePageFunctionAsync(functionName, onPageActionsDone); + } + + function onPageActionsDone() + { + InspectorTest.addSniffer(WebInspector.panels.timeline, "loadingComplete", callback) + InspectorTest.timelineController().stopRecording(); + } +} + InspectorTest.timelineModel = function() { return WebInspector.panels.timeline._model; @@ -71,15 +103,31 @@ return WebInspector.panels.timeline._frameModel; } +InspectorTest.setTraceEvents = function(timelineModel, tracingModel, events) +{ + tracingModel.reset(); + tracingModel.addEvents(events); + tracingModel.tracingComplete(); + timelineModel.setEvents(tracingModel); +} + +InspectorTest.createTimelineModelWithEvents = function(events) +{ + var tracingModel = new WebInspector.TracingModel(new WebInspector.TempFileBackingStorage("tracing")); + var timelineModel = new WebInspector.TimelineModel(WebInspector.TimelineUIUtils.visibleEventsFilter()); + InspectorTest.setTraceEvents(timelineModel, tracingModel, events); + return timelineModel; +} + +InspectorTest.timelineController = function() +{ + return WebInspector.panels.timeline._controller; +} + InspectorTest.startTimeline = function(callback) { var panel = WebInspector.panels.timeline; - function onRecordingStarted() - { - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, onRecordingStarted, this); - callback(); - } - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, onRecordingStarted, this); + InspectorTest.addSniffer(panel, "recordingStarted", callback); panel._toggleRecording(); }; @@ -88,10 +136,9 @@ var panel = WebInspector.panels.timeline; function didStop() { - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, didStop, this) InspectorTest.runAfterPendingDispatches(callback); } - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, didStop, this) + InspectorTest.addSniffer(panel, "loadingComplete", didStop); panel._toggleRecording(); };
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-broken.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-broken.html index 205e608..e9da562 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-broken.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-broken.html
@@ -1,6 +1,6 @@ <!DOCTYPE html> <meta charset="utf-8"> -<meta name="origin-trials" content="I am a website so Frobulate is yes" /> +<meta http-equiv="origin-trial" content="I am a website so Frobulate is yes" /> <title>Test Sample API when trial is disabled (invalid token)</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html index 378bb864..bcad26b 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-enabled.html
@@ -3,7 +3,7 @@ <!-- TODO(iclelland): Generate this sample token during the build. The token below will expire in 2033, but it would be better to always have a token which is guaranteed to be valid when the tests are run. --> -<meta name="origin-trials" content="1|tZPW/JJ2Sxm4z7k/Eb1/upMsppozWpTwEuGwhgQko0zWS6ebvjQ+EXPP/ftoMX8/PCoDgOS3xlrXElMgDDvbCg==|http://127.0.0.1:8000|Frobulate|2000000000"> +<meta http-equiv="origin-trial" content="1|tZPW/JJ2Sxm4z7k/Eb1/upMsppozWpTwEuGwhgQko0zWS6ebvjQ+EXPP/ftoMX8/PCoDgOS3xlrXElMgDDvbCg==|http://127.0.0.1:8000|Frobulate|2000000000"> <title>Test Sample API when trial is enabled</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html index 973cef51..53641c5 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-expired.html
@@ -4,7 +4,7 @@ below has a valid signature for the current signing key, but it would be better to always have a token which is guaranteed to be valid when the tests are run. --> -<meta name="origin-trials" content="1|W5OpLTgzFacJn++BqWVqbeyfxdbimq4hqMg65lHYlmod6ZB2Jl5pfNWlHtRJBOl88/paQB5wqWq5e3z870tfCw==|http://127.0.0.1:8000|Frobulate|1000000000" /> +<meta http-equiv="origin-trial" content="1|W5OpLTgzFacJn++BqWVqbeyfxdbimq4hqMg65lHYlmod6ZB2Jl5pfNWlHtRJBOl88/paQB5wqWq5e3z870tfCw==|http://127.0.0.1:8000|Frobulate|1000000000" /> <title>Test Sample API when trial has expired</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html index fbf9d24..40ad0f1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-multiple-tokens.html
@@ -3,9 +3,9 @@ <!-- TODO(iclelland): Generate these sample tokens during the build. The tokens below will expire in 2033, but it would be better to always have tokens which are guaranteed to be valid when the tests are run. --> -<meta name="origin-trials" content="1|umr41cAPVTw49gYvZb5zQc+lIy6ixCQkC/QyuDBkDNnAbZQjXe7YM/Pb8d0nHCY7xhRq37ZGP7DhLSCp0aOeDA==|http://127.0.0.1:8000|Grokalyze|2000000000" /> -<meta name="origin-trials" content="1|tZPW/JJ2Sxm4z7k/Eb1/upMsppozWpTwEuGwhgQko0zWS6ebvjQ+EXPP/ftoMX8/PCoDgOS3xlrXElMgDDvbCg==|http://127.0.0.1:8000|Frobulate|2000000000" /> -<meta name="origin-trials" content="1|Z+D6g2JZrstb1O6ztVoTi6bWXYGFCdd9v2lu23Doj2RP+q9gHZqhs7RUp1vfUQ0IVt0p5jzVX/OOrwenvktyBA==|http://127.0.0.1:8000|EnableMarqueeTag|2000000000" /> +<meta http-equiv="origin-trial" content="1|umr41cAPVTw49gYvZb5zQc+lIy6ixCQkC/QyuDBkDNnAbZQjXe7YM/Pb8d0nHCY7xhRq37ZGP7DhLSCp0aOeDA==|http://127.0.0.1:8000|Grokalyze|2000000000" /> +<meta http-equiv="origin-trial" content="1|tZPW/JJ2Sxm4z7k/Eb1/upMsppozWpTwEuGwhgQko0zWS6ebvjQ+EXPP/ftoMX8/PCoDgOS3xlrXElMgDDvbCg==|http://127.0.0.1:8000|Frobulate|2000000000" /> +<meta http-equiv="origin-trial" content="1|Z+D6g2JZrstb1O6ztVoTi6bWXYGFCdd9v2lu23Doj2RP+q9gHZqhs7RUp1vfUQ0IVt0p5jzVX/OOrwenvktyBA==|http://127.0.0.1:8000|EnableMarqueeTag|2000000000" /> <title>Test Sample API when trial is enabled and multiple tokens are present</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html index 4a30de8..50e60a3 100644 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html +++ b/third_party/WebKit/LayoutTests/http/tests/origin_trials/sample-api-stolen.html
@@ -3,7 +3,7 @@ <!-- TODO(iclelland): Generate this sample token during the build. The token below will expire in 2033, but it would be better to always have a token which is guaranteed to be valid when the tests are run. --> -<meta name="origin-trials" content="1|ak4CUgJ69tforMyzN7lgxhWaaIny/lGqtLjIqJjMXBA2b8lqul1KhyyLmKZ38+tJnZDLXZmQUn5ZjMFE/SmNDw==|https://invalid.example.com|Frobulate|2000000000" /> +<meta http-equiv="origin-trial" content="1|ak4CUgJ69tforMyzN7lgxhWaaIny/lGqtLjIqJjMXBA2b8lqul1KhyyLmKZ38+tJnZDLXZmQUn5ZjMFE/SmNDw==|https://invalid.example.com|Frobulate|2000000000" /> <title>Test Sample API when token is present for a different origin</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharness-helpers.js"></script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-document-basic.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-document-basic.html new file mode 100644 index 0000000..f207464 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-document-basic.html
@@ -0,0 +1,11 @@ +<!doctype html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="./resources/addressspace-test.js"></script> +<script> + window.onload = function () { + addressSpaceTest("http://localhost:8000", "document", "local"); + addressSpaceTest("http://127.0.0.1:8000", "document", "local"); + addressSpaceTest("http://example.test:8000", "document", "private"); + }; +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-document-csp.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-document-csp.html new file mode 100644 index 0000000..e3bf605 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-document-csp.html
@@ -0,0 +1,12 @@ +<!doctype html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="./resources/addressspace-test.js"></script> +<script> + window.onload = function () { + addressSpaceTest("http://localhost:8000", "document+csp", "public"); + addressSpaceTest("http://127.0.0.1:8000", "document+csp", "public"); + addressSpaceTest("http://example.test:8000", "document+csp", "public"); + }; +</script> +
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-sharedworker-basic.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-sharedworker-basic.html new file mode 100644 index 0000000..8e95287 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-sharedworker-basic.html
@@ -0,0 +1,11 @@ +<!doctype html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="./resources/addressspace-test.js"></script> +<script> + window.onload = function () { + addressSpaceTest("http://localhost:8000", "sharedworker", "local"); + addressSpaceTest("http://127.0.0.1:8000", "sharedworker", "local"); + addressSpaceTest("http://example.test:8000", "sharedworker", "private"); + }; +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-worker-basic.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-worker-basic.html new file mode 100644 index 0000000..9ac145a --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/addressspace-worker-basic.html
@@ -0,0 +1,12 @@ +<!doctype html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="./resources/addressspace-test.js"></script> +<script> + window.onload = function () { + addressSpaceTest("http://localhost:8000", "worker", "local"); + addressSpaceTest("http://127.0.0.1:8000", "worker", "local"); + addressSpaceTest("http://example.test:8000", "worker", "private"); + }; +</script> +
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/addressspace-test.js b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/addressspace-test.js new file mode 100644 index 0000000..8e019a5 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/addressspace-test.js
@@ -0,0 +1,31 @@ +function createIFrame(origin, type) { + var file; + if (type == "document") { + file = "post-addressspace-to-parent.html"; + } else if (type == "document+csp") { + file = "post-addressspace-to-parent.html?csp"; + } else if (type == "worker") { + file = "post-addressspace-from-worker.html"; + } else if (type == "sharedworker") { + file = "post-addressspace-from-sharedworker.html"; + } + + var i = document.createElement('iframe'); + i.src = origin + "/security/cors-rfc1918/resources/" + file; + return i; +} + +function addressSpaceTest(origin, type, expected) { + async_test(function (t) { + var i = createIFrame(origin, type); + window.addEventListener("message", t.step_func(function (e) { + if (e.source == i.contentWindow) { + assert_equals(e.data.origin, origin); + assert_equals(e.data.addressSpace, expected); + t.done(); + } + })); + + document.body.appendChild(i); + }, origin + " = '" + expected + "'"); +}
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-from-sharedworker.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-from-sharedworker.html new file mode 100644 index 0000000..79fa7169 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-from-sharedworker.html
@@ -0,0 +1,8 @@ +<script> + var w = new SharedWorker("/security/cors-rfc1918/resources/post-addressspace-to-owner.js"); + w.port.onmessage = function (e) { + window.parent.postMessage(e.data, "*"); + } + w.port.start(); + w.port.postMessage("go"); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-from-worker.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-from-worker.html new file mode 100644 index 0000000..43681d2 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-from-worker.html
@@ -0,0 +1,7 @@ +<script> + var w = new Worker("/security/cors-rfc1918/resources/post-addressspace-to-owner.js"); + w.onmessage = function (e) { + window.parent.postMessage(e.data, "*"); + } + w.postMessage("go"); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-to-owner.js b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-to-owner.js new file mode 100644 index 0000000..9522e0e --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-to-owner.js
@@ -0,0 +1,18 @@ +// Dedicated workers. +onmessage = function () { + postMessage({ + "origin": self.location.origin, + "addressSpace": self.addressSpace + }); +} + +// Shared workers. +onconnect = function (e) { + var port = e.ports[0]; + port.onmessage = function () { + port.postMessage({ + "origin": self.location.origin, + "addressSpace": self.addressSpace + }); + } +}
diff --git a/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-to-parent.html b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-to-parent.html new file mode 100644 index 0000000..e7758a5 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/security/cors-rfc1918/resources/post-addressspace-to-parent.html
@@ -0,0 +1,13 @@ +<script> + if (window.location.search == "?csp") { + var m = document.createElement("meta"); + m.setAttribute("http-equiv", "Content-Security-Policy"); + m.setAttribute("content", "treat-as-public-address"); + document.head.appendChild(m); + } + + window.parent.postMessage({ + "origin": window.location.origin, + "addressSpace": document.addressSpace + }, "*"); +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt index 05b3dc427..ddf65c1 100644 --- a/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/serviceworker/webexposed/global-interface-listing-service-worker-expected.txt
@@ -702,6 +702,7 @@ method focus method navigate interface WorkerGlobalScope : EventTarget + getter addressSpace getter console getter crypto getter indexedDB
diff --git a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/browsers/history/the-location-interface/location_assign-expected.txt b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/browsers/history/the-location-interface/location_assign-expected.txt new file mode 100644 index 0000000..5b4dd57 --- /dev/null +++ b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/browsers/history/the-location-interface/location_assign-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +PASS location assign +FAIL URL that fails to parse Failed to execute 'assign' on 'Location': 'http://:' is not a valid URL. +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/dom/documents/dom-tree-accessors/document.title-09-expected.txt b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/dom/documents/dom-tree-accessors/document.title-09-expected.txt deleted file mode 100644 index 1bd121d..0000000 --- a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/dom/documents/dom-tree-accessors/document.title-09-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -FAIL No title element in SVG document assert_equals: expected "title" but got "x-child" -FAIL Title element in SVG document assert_equals: expected "foobar" but got "foo" -FAIL Title element not child of SVG root assert_equals: expected "" but got "foo" -FAIL Title element not in SVG namespace assert_equals: expected "" but got "foo" -FAIL Root element not named "svg" assert_equals: expected "" but got "foo" -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/embedded-content/media-elements/location-of-the-media-resource/currentSrc-expected.txt b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/embedded-content/media-elements/location-of-the-media-resource/currentSrc-expected.txt new file mode 100644 index 0000000..590bdb7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/embedded-content/media-elements/location-of-the-media-resource/currentSrc-expected.txt
@@ -0,0 +1,21 @@ +This is a testharness.js-based test. +PASS audio.currentSrc initial value +PASS audio.currentSrc after setting src attribute "" +PASS audio.currentSrc after adding source element with src attribute "" +PASS audio.currentSrc after setting src attribute "." +PASS audio.currentSrc after adding source element with src attribute "." +PASS audio.currentSrc after setting src attribute " " +PASS audio.currentSrc after adding source element with src attribute " " +PASS audio.currentSrc after setting src attribute "data:," +FAIL audio.currentSrc after adding source element with src attribute "data:," assert_equals: expected "data:," but got "" +PASS video.currentSrc initial value +PASS video.currentSrc after setting src attribute "" +PASS video.currentSrc after adding source element with src attribute "" +PASS video.currentSrc after setting src attribute "." +PASS video.currentSrc after adding source element with src attribute "." +PASS video.currentSrc after setting src attribute " " +PASS video.currentSrc after adding source element with src attribute " " +PASS video.currentSrc after setting src attribute "data:," +FAIL video.currentSrc after adding source element with src attribute "data:," assert_equals: expected "data:," but got "" +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_allow_script-expected.txt b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_allow_script-expected.txt deleted file mode 100644 index cdc69fbd..0000000 --- a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/embedded-content/the-iframe-element/iframe_sandbox_allow_script-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -CONSOLE ERROR: Blocked script execution in 'sandbox_allow_script.html' because the document's frame is sandboxed and the 'allow-scripts' permission is not set. -This is a testharness.js-based test. -PASS iframe_sandbox_allow_scripts -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/selectors/pseudo-classes/default-expected.txt b/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/selectors/pseudo-classes/default-expected.txt deleted file mode 100644 index 1bf9949..0000000 --- a/third_party/WebKit/LayoutTests/imported/web-platform-tests/html/semantics/selectors/pseudo-classes/default-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL ':default' matches <button>s that are their form's default button, <input>s of type submit/image that are their form's default button, checked <input>s and selected <option>s assert_array_equals: lengths differ, expected 9 got 7 -FAIL ':default' matches dynamically changed form's default buttons assert_array_equals: lengths differ, expected 9 got 7 -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html index 45a0bfa..ba29715 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/debugger-step-into-dedicated-worker.html
@@ -37,7 +37,7 @@ } } InspectorTest.sendCommand("Worker.enable", {}, didEnableWorkerDebugging); - InspectorTest.sendCommand("Worker.setAutoconnectToWorkers", { "value": true }); + InspectorTest.sendCommand("Worker.setWaitForDebuggerOnStart", { "value": true }); InspectorTest.sendCommand("Runtime.evaluate", { "expression": "startWorker()" }); InspectorTest.eventHandler["Worker.workerCreated"] = function(messageObject)
diff --git a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html index c2929a3..933404f 100644 --- a/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html +++ b/third_party/WebKit/LayoutTests/inspector-protocol/debugger/suspend-setTimeout-on-pause-in-dedicated-worker.html
@@ -39,7 +39,7 @@ } } InspectorTest.sendCommand("Worker.enable", {}, didEnableWorkerDebugging); - InspectorTest.sendCommand("Worker.setAutoconnectToWorkers", { "value": true }); + InspectorTest.sendCommand("Worker.setWaitForDebuggerOnStart", { "value": true }); InspectorTest.sendCommand("Runtime.evaluate", { "expression": "startWorker()" }); InspectorTest.eventHandler["Worker.workerCreated"] = function(messageObject)
diff --git a/third_party/WebKit/LayoutTests/inspector/profiler/agents-disabled-check-expected.txt b/third_party/WebKit/LayoutTests/inspector/profiler/agents-disabled-check-expected.txt index f6a72e0a..708c25e4 100644 --- a/third_party/WebKit/LayoutTests/inspector/profiler/agents-disabled-check-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/profiler/agents-disabled-check-expected.txt
@@ -1,7 +1,7 @@ Test that if a profiler is working all the agents are disabled. --> WebInspector.targetManager.suspendAllTargets(); -frontend: {"id":<number>,"method":"Worker.setAutoconnectToWorkers","params":{"value":false}} +frontend: {"id":<number>,"method":"Worker.setWaitForDebuggerOnStart","params":{"value":false}} frontend: {"id":<number>,"method":"Debugger.disable"} frontend: {"id":<number>,"method":"Debugger.setAsyncCallStackDepth","params":{"maxDepth":0}} frontend: {"id":<number>,"method":"Page.setOverlayMessage"} @@ -9,7 +9,7 @@ frontend: {"id":<number>,"method":"CSS.disable"} --> WebInspector.targetManager.resumeAllTargets(); -frontend: {"id":<number>,"method":"Worker.setAutoconnectToWorkers","params":{"value":true}} +frontend: {"id":<number>,"method":"Worker.setWaitForDebuggerOnStart","params":{"value":true}} frontend: {"id":<number>,"method":"Debugger.enable"} frontend: {"id":<number>,"method":"Debugger.setPauseOnExceptions","params":{"state":"none"}} frontend: {"id":<number>,"method":"Debugger.setAsyncCallStackDepth","params":{"maxDepth":4}}
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing-model-async.html b/third_party/WebKit/LayoutTests/inspector/tracing-model-async.html index 35a0ff2..436cbe57 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing-model-async.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing-model-async.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../http/tests/inspector/inspector-test.js"></script> -<script src="tracing-test.js"></script> +<script src="../http/tests/inspector/timeline-test.js"></script> <script> function test() {
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing-model-storage.html b/third_party/WebKit/LayoutTests/inspector/tracing-model-storage.html index 93b11b5..295cc672 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing-model-storage.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing-model-storage.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../http/tests/inspector/inspector-test.js"></script> -<script src="tracing-test.js"></script> +<script src="../http/tests/inspector/timeline-test.js"></script> <script> function test() { @@ -21,7 +21,8 @@ } var model = InspectorTest.createTracingModel(); - model.setEventsForTest(testData); + model.addEvents(testData); + model.tracingComplete(); var process = model.sortedProcesses()[0]; var thread = process.sortedThreads()[0]; InspectorTest.assertEquals("лет ми спик фром май харт", getEventByName("NonAscii").args["nonascii"]);
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing-model.html b/third_party/WebKit/LayoutTests/inspector/tracing-model.html index 60c46ad4..50fa4cd 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing-model.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing-model.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../http/tests/inspector/inspector-test.js"></script> -<script src="tracing-test.js"></script> +<script src="../http/tests/inspector/timeline-test.js"></script> <script> function test() { @@ -55,7 +55,8 @@ ]; var model = InspectorTest.createTracingModel(); - model.setEventsForTest(testData); + model.addEvents(testData); + model.tracingComplete(); var events = model.sortedProcesses()[0].threadById(mainThread).events(); for (var i = 0; i < events.length; ++i) { var event = events[i];
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing-session-id.html b/third_party/WebKit/LayoutTests/inspector/tracing-session-id.html index 01c12f66..d90cea8c 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing-session-id.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing-session-id.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../http/tests/inspector/inspector-test.js"></script> -<script src="tracing-test.js"></script> +<script src="../http/tests/inspector/timeline-test.js"></script> <script> function test() @@ -28,7 +28,7 @@ if (!event.hasCategory(WebInspector.TracingModel.DevToolsMetadataEventCategory) || metadataEvents.indexOf(event.name) < 0) return; - InspectorTest.assertEquals(InspectorTest.tracingTimelineModel().sessionId(), event.args["data"]["sessionId"]); + InspectorTest.assertEquals(InspectorTest.timelineModel().sessionId(), event.args["data"]["sessionId"]); InspectorTest.addResult("Got DevTools metadata event: " + event.name); } }
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing-test.js b/third_party/WebKit/LayoutTests/inspector/tracing-test.js deleted file mode 100644 index c304115..0000000 --- a/third_party/WebKit/LayoutTests/inspector/tracing-test.js +++ /dev/null
@@ -1,47 +0,0 @@ -function initialize_TracingTest() -{ - -InspectorTest.preloadPanel("timeline"); -WebInspector.TempFile = InspectorTest.TempFileMock; - -InspectorTest.createTracingModel = function() -{ - return new WebInspector.TracingModel(new WebInspector.TempFileBackingStorage("tracing")); -} - -InspectorTest.tracingModel = function() -{ - return WebInspector.panels.timeline._tracingModel; -} - -InspectorTest.tracingTimelineModel = function() -{ - return WebInspector.panels.timeline._model; -} - -InspectorTest.invokeWithTracing = function(functionName, callback, additionalCategories, enableJSSampling) -{ - var categories = "-*,disabled-by-default-devtools.timeline*,devtools.timeline," + WebInspector.TracingModel.TopLevelEventCategory; - if (additionalCategories) - categories += "," + additionalCategories; - InspectorTest.tracingTimelineModel()._startRecordingWithCategories(categories, enableJSSampling, tracingStarted); - - function tracingStarted() - { - InspectorTest.invokePageFunctionAsync(functionName, onPageActionsDone); - } - - function onPageActionsDone() - { - InspectorTest.tracingTimelineModel().addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, onTracingComplete, this); - InspectorTest.tracingTimelineModel().stopRecording(); - } - - function onTracingComplete(event) - { - InspectorTest.tracingTimelineModel().removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, onTracingComplete, this); - callback(); - } -} - -}
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage-expected.txt b/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage-expected.txt index df64fe2..4f903256 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage-expected.txt
@@ -1,4 +1,8 @@ -Tests that buffer usage update are sent when recording trace events. +Tests that buffer usage update are sent when recording trace events and TimelineLifecycleDelegate methods are properly invoked in the expected order. -SUCCESS: Received buffer usage update. +TimelineLifecycleDelegate.recordingStarted +TimelineLifecycleDelegate.recordingProgress +TimelineLifecycleDelegate.loadingStarted +TimelineLifecycleDelegate.loadingProgress +TimelineLifecycleDelegate.loadingComplete
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage.html b/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage.html index 0e2360a6..212d930 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/buffer-usage.html
@@ -2,20 +2,54 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> function test() { - InspectorTest.tracingTimelineModel().addEventListener(WebInspector.TimelineModel.Events.BufferUsage, onBufferUsage, this); - InspectorTest.tracingTimelineModel().startRecording(); - function onBufferUsage(event) + WebInspector.TestTimelineLifecycleDelegate = function() { - InspectorTest.tracingTimelineModel().removeEventListener(WebInspector.TimelineModel.Events.BufferUsage, onBufferUsage, this); - InspectorTest.tracingTimelineModel().stopRecording(); - InspectorTest.addResult("SUCCESS: Received buffer usage update."); - InspectorTest.completeTest(); + this._hadLoadingProgress = false; } + + WebInspector.TestTimelineLifecycleDelegate.prototype = { + recordingStarted: function() + { + InspectorTest.addResult("TimelineLifecycleDelegate.recordingStarted"); + }, + + recordingProgress: function() + { + if (!controller) + return; + InspectorTest.addResult("TimelineLifecycleDelegate.recordingProgress"); + controller.stopRecording(); + controller = null; + }, + + loadingStarted: function() + { + InspectorTest.addResult("TimelineLifecycleDelegate.loadingStarted"); + }, + + loadingProgress: function() + { + if (this._hadLoadingProgress) + return; + this._hadLoadingProgress = true; + InspectorTest.addResult("TimelineLifecycleDelegate.loadingProgress"); + }, + + loadingComplete: function() + { + InspectorTest.addResult("TimelineLifecycleDelegate.loadingComplete"); + InspectorTest.completeTest(); + }, + + __proto__: WebInspector.TimelineLifecycleDelegate + }; + + var controller = new WebInspector.TimelineController(new WebInspector.TestTimelineLifecycleDelegate(), InspectorTest.createTracingModel()); + controller.startRecording(); } </script> @@ -23,7 +57,8 @@ <body onload="runTest()"> <p> -Tests that buffer usage update are sent when recording trace events. +Tests that buffer usage update are sent when recording trace events and +TimelineLifecycleDelegate methods are properly invoked in the expected order. </p> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/category-filter.html b/third_party/WebKit/LayoutTests/inspector/tracing/category-filter.html index 29003270..ba7528864 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/category-filter.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/category-filter.html
@@ -35,9 +35,7 @@ {"name": "foooooo", "ts": 1099999, "ph": "E", "tid": mainThread, "pid": pid, "cat":"toplevel", "args": {}} ]; - var panel = WebInspector.panels.timeline; - var model = InspectorTest.timelineModel(); - model.setEventsForTest(testData); + var model = InspectorTest.createTimelineModelWithEvents(testData); var view = new WebInspector.EventsTimelineTreeView(model, null); view.updateContents(WebInspector.TimelineSelection.fromRange(model.minimumRecordTime(), model.maximumRecordTime())); var filtersControl = view._filtersControl;
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline-expected.txt b/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline-expected.txt index 9ea88823..d7865e0 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline-expected.txt
@@ -64,17 +64,3 @@ Timeline 'two' timestamp 2 -Running: testRacyStart -timestamp 0 -Timeline 'one' -timestamp 1 -Timeline 'two' -timestamp 2 - -Running: testRacyStart2 -timestamp 0 -Timeline 'one' -timestamp 1 -Timeline 'two' -timestamp 2 -
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline.html b/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline.html index 6648e31..d4fb6b6b 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/console-timeline.html
@@ -147,104 +147,25 @@ function testStartFromPanel(next) { - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); - panel._toggleRecording(); - - function recordingStarted() - { - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - InspectorTest.evaluateInPage("startStopTimeline()", step2); - } - - function step2() - { - panel._toggleRecording(); - } + InspectorTest.evaluateWithTimeline("startStopTimeline()", finish) function finish() { printTimelineAndTimestampEvents(); - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); next(); } }, function testStopFromPanel(next) { - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); - - InspectorTest.startTimeline(step1); - - function step1() - { - InspectorTest.evaluateInPage("startTimeline()", step2); - } - - function step2() - { - panel._toggleRecording(); - } + InspectorTest.evaluateWithTimeline("startTimeline()", finish) function finish() { printTimelineAndTimestampEvents(); - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); next(); } - }, - - function testRacyStart(next) - { - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); - panel._toggleRecording(); - - function recordingStarted() - { - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - InspectorTest.evaluateInPage("startTimeline()", didEvaluate); - } - - function didEvaluate() - { - panel._toggleRecording(); - } - - function finish() - { - printTimelineAndTimestampEvents(); - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); - next(); - } - }, - - function testRacyStart2(next) - { - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - panel._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); - - panel._toggleRecording(); - - function recordingStarted() - { - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - InspectorTest.evaluateInPage("startTimeline()", didEvaluate); - } - - function didEvaluate() - { - // Fool listener order execution. - setTimeout(panel._toggleRecording.bind(panel)); - } - - function finish() - { - panel._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, finish); - printTimelineAndTimestampEvents(); - next(); - } - } + } ]); function printTimelineAndTimestampEvents() {
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/decode-resize.html b/third_party/WebKit/LayoutTests/inspector/tracing/decode-resize.html index 8a50d3b..2a0d305 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/decode-resize.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/decode-resize.html
@@ -25,7 +25,6 @@ </style> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> var images = [ @@ -93,7 +92,7 @@ var urlB = InspectorTest.formatters.formatAsURL(b.url || "<missing>"); return urlA.localeCompare(urlB); } - var events = InspectorTest.tracingTimelineModel().inspectedTargetEvents(); + var events = InspectorTest.timelineModel().inspectedTargetEvents(); var sortedDecodeEvents = events.filter(isDecodeImageEvent).sort(compareImageURLs); for (var i = 0; i < sortedDecodeEvents.length; ++i) { var event = sortedDecodeEvents[i];
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/frame-model.html b/third_party/WebKit/LayoutTests/inspector/tracing/frame-model.html index 2b0fb7c2..19bd3fe 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/frame-model.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/frame-model.html
@@ -280,8 +280,7 @@ function loadEvents(events) { - var tracingTimelineModel = InspectorTest.tracingTimelineModel(); - tracingTimelineModel.setEventsForTest(events); + var tracingTimelineModel = InspectorTest.createTimelineModelWithEvents(events); frameModel.reset(); frameModel.addTraceEvents(WebInspector.targetManager.mainTarget(), tracingTimelineModel.inspectedTargetEvents(), sessionId); }
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/paint-profiler-update.html b/third_party/WebKit/LayoutTests/inspector/tracing/paint-profiler-update.html index 3209ac2..7a320e9 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/paint-profiler-update.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/paint-profiler-update.html
@@ -2,7 +2,6 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> function performActions(callback) { @@ -33,7 +32,7 @@ var paintEvents = []; function onRecordingDone() { - var events = InspectorTest.tracingTimelineModel()._mainThreadEvents; + var events = InspectorTest.timelineModel()._mainThreadEvents; for (var event of events) { if (event.name === WebInspector.TimelineModel.RecordType.Paint) { paintEvents.push(event);
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-aggregated-details.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-aggregated-details.html index ac0f091d..99cbeb1 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-aggregated-details.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-aggregated-details.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> -<script src="../tracing-test.js"></script> +<script src="../../http/tests/inspector/timeline-test.js"></script> <script> function initialize_EventsView() { @@ -573,22 +573,18 @@ ]; var timeline = WebInspector.panels.timeline; - timeline._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, InspectorTest.safeWrap(timelineRecorded), this); - timeline._model.setEventsForTest(rawTraceEvents); + InspectorTest.setTraceEvents(InspectorTest.timelineModel(), InspectorTest.tracingModel(), rawTraceEvents); - function timelineRecorded() - { - timeline.requestWindowTimes(0, Infinity); - for (var grouping in WebInspector.AggregatedTimelineTreeView.GroupBy) { - var groupingValue = WebInspector.AggregatedTimelineTreeView.GroupBy[grouping]; - testEventTree(WebInspector.TimelinePanel.DetailsTab.CallTree, groupingValue); - testEventTree(WebInspector.TimelinePanel.DetailsTab.BottomUp, groupingValue); - } - - testEventTree(WebInspector.TimelinePanel.DetailsTab.Events); - InspectorTest.completeTest(); + timeline.requestWindowTimes(0, Infinity); + for (var grouping in WebInspector.AggregatedTimelineTreeView.GroupBy) { + var groupingValue = WebInspector.AggregatedTimelineTreeView.GroupBy[grouping]; + testEventTree(WebInspector.TimelinePanel.DetailsTab.CallTree, groupingValue); + testEventTree(WebInspector.TimelinePanel.DetailsTab.BottomUp, groupingValue); } + testEventTree(WebInspector.TimelinePanel.DetailsTab.Events); + InspectorTest.completeTest(); + function testEventTree(type, grouping) { InspectorTest.addResult("");
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-record.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-record.html index c407b90d..7f965e1 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-record.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-record.html
@@ -8,11 +8,10 @@ function test() { var panel = WebInspector.panels.timeline; - var model = panel._model; var callbackBarrier = new CallbackBarrier(); - model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, recordingStarted); - model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, callbackBarrier.createCallback()); + InspectorTest.addSniffer(panel, "recordingStarted", recordingStarted); + InspectorTest.addSniffer(panel, "loadingComplete", callbackBarrier.createCallback()); WebInspector.ConsolePanel.show(); InspectorTest.runWhenPageLoads(step1);
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-zoom.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-zoom.html index 2b57020..e4609a7 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-zoom.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-auto-zoom.html
@@ -2,7 +2,6 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> function test() { @@ -34,7 +33,7 @@ {"name": "FunctionCall", "ts": 6000000, "dur": 1000, "ph": "X", args: {}, "tid": mainThread, "pid": 100, "cat":"disabled-by-default-devtools.timeline", "args":{"data":{}}} ]; - WebInspector.panels.timeline._model.setEventsForTest(traceEvents); + InspectorTest.setTraceEvents(InspectorTest.timelineModel(), InspectorTest.tracingModel(), traceEvents); var overview = WebInspector.panels.timeline._overviewPane; var startTime = overview._windowStartTime; var endTime = overview._windowEndTime;
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-dfs.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-dfs.html index e876dbf..979c1fe 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-dfs.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-dfs.html
@@ -48,16 +48,15 @@ {"name": "b", "ts": 4000000, "ph": "E", "tid": mainThread, "pid": pid, "cat":"disabled-by-default.devtools.timeline", "args": {}} ]; - // Reset filter to accept all records. - InspectorTest.timelineModel()._eventFilter = new WebInspector.TimelineModel.Filter(); - InspectorTest.timelineModel().setEventsForTest(testData); + var model = new WebInspector.TimelineModel(new WebInspector.TimelineModel.Filter()); + InspectorTest.setTraceEvents(model, InspectorTest.createTracingModel(), testData); InspectorTest.addResult("DFS preorder:"); - InspectorTest.timelineModel().forAllRecords(dumper); + model.forAllRecords(dumper); InspectorTest.addResult(""); InspectorTest.addResult("DFS postorder:"); - InspectorTest.timelineModel().forAllRecords(null, dumper); + model.forAllRecords(null, dumper); InspectorTest.completeTest(); }
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-filtering.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-filtering.html index f6affed..20b781b 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-filtering.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-filtering.html
@@ -51,9 +51,7 @@ ]; - var panel = WebInspector.panels.timeline; - var model = InspectorTest.timelineModel(); - model.setEventsForTest(testData); + var model = InspectorTest.createTimelineModelWithEvents(testData); var view = new WebInspector.EventsTimelineTreeView(model, null); view.updateContents(WebInspector.TimelineSelection.fromRange(model.minimumRecordTime(), model.maximumRecordTime())); var filtersControl = view._filtersControl;
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-blackboxing.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-blackboxing.html index 1d48fb9c..cd62986 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-blackboxing.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-blackboxing.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> -<script src="../tracing-test.js"></script> +<script src="../../http/tests/inspector/timeline-test.js"></script> <script> function test() { @@ -283,9 +283,8 @@ } Runtime.experiments.enableForTest("blackboxJSFramesOnTimeline"); - var tracingTimelineModel = InspectorTest.tracingTimelineModel(); - tracingTimelineModel.setEventsForTest(rawTraceEvents); - var dataProvider = new WebInspector.TimelineFlameChartDataProvider(tracingTimelineModel, new WebInspector.TracingTimelineFrameModel()); + var timelineModel = InspectorTest.createTimelineModelWithEvents(rawTraceEvents); + var dataProvider = new WebInspector.TimelineFlameChartDataProvider(timelineModel, new WebInspector.TracingTimelineFrameModel()); InspectorTest.addResult("\nBlackboxed url: lib_script.js"); WebInspector.blackboxManager._blackboxURL("lib_script.js");
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-callstacks.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-callstacks.html index 864e914..8f9c2eab 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-callstacks.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-callstacks.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> -<script src="../tracing-test.js"></script> +<script src="../../http/tests/inspector/timeline-test.js"></script> <script> function test() { @@ -550,8 +550,7 @@ } ]; - var tracingTimelineModel = InspectorTest.tracingTimelineModel(); - tracingTimelineModel.setEventsForTest(rawTraceEvents); + var tracingTimelineModel = InspectorTest.createTimelineModelWithEvents(rawTraceEvents); var events = WebInspector.TimelineJSProfileProcessor.generateJSFrameEvents(tracingTimelineModel.mainThreadEvents()); events = events.mergeOrdered(tracingTimelineModel.mainThreadEvents(), WebInspector.TracingModel.Event.orderedCompareStartTime); events.filter(function(e) { return e.duration; }).forEach(function(e) {
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-samping-tracing.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-samping-tracing.html index ce7f551..68c403c 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-samping-tracing.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-js-samping-tracing.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> -<script src="../tracing-test.js"></script> +<script src="../../http/tests/inspector/timeline-test.js"></script> <script> function test() { @@ -463,8 +463,7 @@ ]; Runtime.experiments.enableForTest("timelineTracingJSProfile"); - var tracingTimelineModel = InspectorTest.tracingTimelineModel(); - tracingTimelineModel.setEventsForTest(rawTraceEvents); + var tracingTimelineModel = InspectorTest.createTimelineModelWithEvents(rawTraceEvents); var events = tracingTimelineModel.mainThreadEvents(); events.filter(function(e) { return e.name === "JSFrame"; }).forEach(function(e) { InspectorTest.addResult(e.name + ": " + e.startTime.toFixed(3) + " / " + (e.duration.toFixed(3) || 0) + " " + e.args.data.functionName);
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-model.html b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-model.html index fe99a39e..1824a5f 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/timeline-model.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/timeline-model.html
@@ -2,7 +2,6 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> function test() { @@ -52,8 +51,7 @@ {"name": "Program", "ts": 2009999, "ph": "E", args: {}, "tid": mainThread, "pid": 100, "cat":"disabled-by-default.devtools.timeline"} ]; - var tracingTimelineModel = InspectorTest.tracingTimelineModel(); - tracingTimelineModel.setEventsForTest(commonMetadata.concat(traceEvents)); + var tracingTimelineModel = InspectorTest.createTimelineModelWithEvents(commonMetadata.concat(traceEvents)); var records = tracingTimelineModel.records(); var topLevelRecordsCount = 2; InspectorTest.assertEquals(topLevelRecordsCount, records.length);
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/trace-event-self-time.html b/third_party/WebKit/LayoutTests/inspector/tracing/trace-event-self-time.html index ecd7187..ceade03 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/trace-event-self-time.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/trace-event-self-time.html
@@ -1,7 +1,7 @@ <html> <head> <script src="../../http/tests/inspector/inspector-test.js"></script> -<script src="../tracing-test.js"></script> +<script src="../../http/tests/inspector/timeline-test.js"></script> <script> function test() { @@ -284,13 +284,12 @@ samples: [2, 2, 3, 3, 3, 4, 4, 2, 2 ] }; - var tracingTimelineModel = InspectorTest.tracingTimelineModel(); - tracingTimelineModel._addCpuProfile(WebInspector.targetManager.mainTarget().id(), cpuProfile); - tracingTimelineModel.setEventsForTest(rawTraceEvents); - var events = tracingTimelineModel.inspectedTargetEvents(); - events.forEach(function(e) { - InspectorTest.addResult(e.name + ": " + e.startTime + " " + (e.selfTime || 0).toFixed(2) + "/" + (e.duration || 0).toFixed(2)); - }); + var timelineController = InspectorTest.timelineController(); + timelineController._addCpuProfile(WebInspector.targetManager.mainTarget().id(), cpuProfile); + timelineController.traceEventsCollected(rawTraceEvents); + timelineController.tracingComplete(); + var events = InspectorTest.timelineModel().inspectedTargetEvents(); + events.forEach(e => InspectorTest.addResult(e.name + ": " + e.startTime + " " + (e.selfTime || 0).toFixed(2) + "/" + (e.duration || 0).toFixed(2))); InspectorTest.completeTest(); }
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/tracing-timeline-load.html b/third_party/WebKit/LayoutTests/inspector/tracing/tracing-timeline-load.html index 559c36e..458022a 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/tracing-timeline-load.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/tracing-timeline-load.html
@@ -2,7 +2,6 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> function test() @@ -46,7 +45,6 @@ InspectorTest.override(WebInspector.TimelineLoader, "_createFileReader", createFileReader); WebInspector.TimelineLoader.loadFromFile(model, {}, new InspectorTest.TestTimelineLifecycleDelegate()); - model.tracingComplete(); var saver = new WebInspector.TracingTimelineSaver(); var stream = new InspectorTest.StringOutputStream(InspectorTest.safeWrap(checkSaveData));
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/update-layer-tree.html b/third_party/WebKit/LayoutTests/inspector/tracing/update-layer-tree.html index 139ce6b2..30e0d0399 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/update-layer-tree.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/update-layer-tree.html
@@ -10,7 +10,6 @@ </style> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> function doActions(callback) @@ -28,7 +27,7 @@ InspectorTest.invokeWithTracing("doActions", onTracingComplete); function onTracingComplete() { - var events = InspectorTest.tracingTimelineModel().inspectedTargetEvents(); + var events = InspectorTest.timelineModel().inspectedTargetEvents(); for (var i = 0; i < events.length; ++i) { var event = events[i]; if (events[i].name === WebInspector.TimelineModel.RecordType.UpdateLayerTree) {
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/worker-events.html b/third_party/WebKit/LayoutTests/inspector/tracing/worker-events.html index 688aac5..54a66c6 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/worker-events.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/worker-events.html
@@ -2,7 +2,6 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> // Save references to the worker objects to make sure they are not GC'ed. @@ -59,7 +58,7 @@ return; ++workerMetadataEventCount; - InspectorTest.assertEquals(InspectorTest.tracingTimelineModel().sessionId(), event.args["data"]["sessionId"]); + InspectorTest.assertEquals(InspectorTest.timelineModel().sessionId(), event.args["data"]["sessionId"]); InspectorTest.addResult("Got DevTools worker metadata event(" + workerMetadataEventCount + "): " + event.name); }
diff --git a/third_party/WebKit/LayoutTests/inspector/tracing/worker-js-frames.html b/third_party/WebKit/LayoutTests/inspector/tracing/worker-js-frames.html index 7faa1b9..8be42e0 100644 --- a/third_party/WebKit/LayoutTests/inspector/tracing/worker-js-frames.html +++ b/third_party/WebKit/LayoutTests/inspector/tracing/worker-js-frames.html
@@ -2,7 +2,6 @@ <head> <script src="../../http/tests/inspector/inspector-test.js"></script> <script src="../../http/tests/inspector/timeline-test.js"></script> -<script src="../tracing-test.js"></script> <script> // Save references to the worker objects to make sure they are not GC'ed. @@ -63,9 +62,9 @@ function processTracingEvents() { - var mainThread = { name: "Main Thread", events: InspectorTest.tracingTimelineModel()._mainThreadEvents }; + var mainThread = { name: "Main Thread", events: InspectorTest.timelineModel()._mainThreadEvents }; processThread(new Set(["startSecondWorker", "worker2.onmessage"]), mainThread); - InspectorTest.tracingTimelineModel()._virtualThreads.forEach(function(thread) + InspectorTest.timelineModel()._virtualThreads.forEach(function(thread) { if (!thread.isWorker()) return;
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/use-on-g-containing-symbol-expected.png b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/use-on-g-containing-symbol-expected.png deleted file mode 100644 index ee7e02de..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/use-on-g-containing-symbol-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/use-on-g-containing-symbol-expected.txt b/third_party/WebKit/LayoutTests/platform/linux/svg/custom/use-on-g-containing-symbol-expected.txt deleted file mode 100644 index 9022c94..0000000 --- a/third_party/WebKit/LayoutTests/platform/linux/svg/custom/use-on-g-containing-symbol-expected.txt +++ /dev/null
@@ -1,17 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,45) size 481x83 - LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (0,0) size 0x0 - LayoutSVGHiddenContainer {symbol} at (0,0) size 0x0 - LayoutSVGRect {rect} at (0,0) size 125x25 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00] - LayoutSVGContainer {g} at (245,45) size 130x30 [transform={m=((1.00,0.00)(0.00,1.00)) t=(125.00,25.00)}] - LayoutSVGRect {rect} at (245,45) size 130x30 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00] - LayoutSVGText {text} at (10,46) size 241x18 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 241x18 - chunk 1 text run 1 at (10.00,60.00) startOffset 0 endOffset 38 width 240.50: "The two objects should look identical." - LayoutSVGContainer {use} at (45,45) size 130x30 [transform={m=((1.00,0.00)(0.00,1.00)) t=(25.00,25.00)}] - LayoutSVGContainer {g} at (45,45) size 130x30 - LayoutSVGViewportContainer {svg} at (45,45) size 130x30 - LayoutSVGRect {rect} at (45,45) size 130x30 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00]
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.png index fbfac4d4..945f873 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.txt b/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.txt index a14c9f8..ca9d403 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.10/fast/text/unicode-fallback-font-expected.txt
@@ -77,10 +77,10 @@ text run at (325,542) width 1: " " text run at (0,564) width 340: "U+26Fx \x{26F0} \x{26F1} \x{26F2} \x{26F3} \x{26F4} \x{26F5} \x{26F6} \x{26F7} \x{26F8} \x{26F9} \x{26FA} \x{26FB} \x{26FC} \x{26FD} \x{26FE} \x{26FF}" text run at (339,564) width 1: " " - LayoutText {#text} at (0,581) size 357x229 + LayoutText {#text} at (0,581) size 359x229 text run at (0,581) width 0: " " - text run at (0,600) width 353: "U+270x \x{2700} \x{2701} \x{2702} \x{2703} \x{2704} \x{2705} \x{2706} \x{2707} \x{2708} \x{2709} \x{270A} \x{270B} \x{270C} \x{270D} \x{270E} \x{270F}" - text run at (352,600) width 1: " " + text run at (0,600) width 359: "U+270x \x{2700} \x{2701} \x{2702} \x{2703} \x{2704} \x{2705} \x{2706} \x{2707} \x{2708} \x{2709} \x{270A} \x{270B} \x{270C} \x{270D} \x{270E} \x{270F}" + text run at (358,600) width 1: " " text run at (0,617) width 326: "U+271x \x{2710} \x{2711} \x{2712} \x{2713} \x{2714} \x{2715} \x{2716} \x{2717} \x{2718} \x{2719} \x{271A} \x{271B} \x{271C} \x{271D} \x{271E} \x{271F}" text run at (325,617) width 1: " " text run at (0,636) width 338: "U+272x \x{2720} \x{2721} \x{2722} \x{2723} \x{2724} \x{2725} \x{2726} \x{2727} \x{2728} \x{2729} \x{272A} \x{272B} \x{272C} \x{272D} \x{272E} \x{272F}"
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.png b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.png index 88a0a3f..a438dd3 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.txt b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.txt index 937548f..dfeac51 100644 --- a/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac-mac10.9/fast/text/unicode-fallback-font-expected.txt
@@ -77,10 +77,10 @@ text run at (325,532) width 1: " " text run at (0,554) width 340: "U+26Fx \x{26F0} \x{26F1} \x{26F2} \x{26F3} \x{26F4} \x{26F5} \x{26F6} \x{26F7} \x{26F8} \x{26F9} \x{26FA} \x{26FB} \x{26FC} \x{26FD} \x{26FE} \x{26FF}" text run at (339,554) width 1: " " - LayoutText {#text} at (0,571) size 357x229 + LayoutText {#text} at (0,571) size 359x229 text run at (0,571) width 0: " " - text run at (0,590) width 353: "U+270x \x{2700} \x{2701} \x{2702} \x{2703} \x{2704} \x{2705} \x{2706} \x{2707} \x{2708} \x{2709} \x{270A} \x{270B} \x{270C} \x{270D} \x{270E} \x{270F}" - text run at (352,590) width 1: " " + text run at (0,590) width 359: "U+270x \x{2700} \x{2701} \x{2702} \x{2703} \x{2704} \x{2705} \x{2706} \x{2707} \x{2708} \x{2709} \x{270A} \x{270B} \x{270C} \x{270D} \x{270E} \x{270F}" + text run at (358,590) width 1: " " text run at (0,607) width 326: "U+271x \x{2710} \x{2711} \x{2712} \x{2713} \x{2714} \x{2715} \x{2716} \x{2717} \x{2718} \x{2719} \x{271A} \x{271B} \x{271C} \x{271D} \x{271E} \x{271F}" text run at (325,607) width 1: " " text run at (0,626) width 338: "U+272x \x{2720} \x{2721} \x{2722} \x{2723} \x{2724} \x{2725} \x{2726} \x{2727} \x{2728} \x{2729} \x{272A} \x{272B} \x{272C} \x{272D} \x{272E} \x{272F}"
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.png b/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.png index e5df294..19cdb95 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.txt index 824c3ee5..05489ab 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/fast/text/unicode-fallback-font-expected.txt
@@ -77,10 +77,10 @@ text run at (328,538) width 1: " " text run at (0,560) width 362: "U+26Fx \x{26F0} \x{26F1} \x{26F2} \x{26F3} \x{26F4} \x{26F5} \x{26F6} \x{26F7} \x{26F8} \x{26F9} \x{26FA} \x{26FB} \x{26FC} \x{26FD} \x{26FE} \x{26FF}" text run at (361,560) width 1: " " - LayoutText {#text} at (0,577) size 357x229 + LayoutText {#text} at (0,577) size 361x229 text run at (0,577) width 0: " " - text run at (0,596) width 353: "U+270x \x{2700} \x{2701} \x{2702} \x{2703} \x{2704} \x{2705} \x{2706} \x{2707} \x{2708} \x{2709} \x{270A} \x{270B} \x{270C} \x{270D} \x{270E} \x{270F}" - text run at (352,596) width 1: " " + text run at (0,596) width 361: "U+270x \x{2700} \x{2701} \x{2702} \x{2703} \x{2704} \x{2705} \x{2706} \x{2707} \x{2708} \x{2709} \x{270A} \x{270B} \x{270C} \x{270D} \x{270E} \x{270F}" + text run at (360,596) width 1: " " text run at (0,613) width 326: "U+271x \x{2710} \x{2711} \x{2712} \x{2713} \x{2714} \x{2715} \x{2716} \x{2717} \x{2718} \x{2719} \x{271A} \x{271B} \x{271C} \x{271D} \x{271E} \x{271F}" text run at (325,613) width 1: " " text run at (0,632) width 338: "U+272x \x{2720} \x{2721} \x{2722} \x{2723} \x{2724} \x{2725} \x{2726} \x{2727} \x{2728} \x{2729} \x{272A} \x{272B} \x{272C} \x{272D} \x{272E} \x{272F}"
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/use-on-g-containing-symbol-expected.png b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/use-on-g-containing-symbol-expected.png deleted file mode 100644 index e44856f..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/use-on-g-containing-symbol-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/use-on-g-containing-symbol-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/svg/custom/use-on-g-containing-symbol-expected.txt deleted file mode 100644 index 34dc7d52..0000000 --- a/third_party/WebKit/LayoutTests/platform/mac/svg/custom/use-on-g-containing-symbol-expected.txt +++ /dev/null
@@ -1,17 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,45) size 489x83 - LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (0,0) size 0x0 - LayoutSVGHiddenContainer {symbol} at (0,0) size 0x0 - LayoutSVGRect {rect} at (0,0) size 125x25 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00] - LayoutSVGContainer {g} at (245,45) size 130x30 [transform={m=((1.00,0.00)(0.00,1.00)) t=(125.00,25.00)}] - LayoutSVGRect {rect} at (245,45) size 130x30 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00] - LayoutSVGText {text} at (10,45) size 245x19 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 245x19 - chunk 1 text run 1 at (10.00,60.00) startOffset 0 endOffset 38 width 244.40: "The two objects should look identical." - LayoutSVGContainer {use} at (45,45) size 130x30 [transform={m=((1.00,0.00)(0.00,1.00)) t=(25.00,25.00)}] - LayoutSVGContainer {g} at (45,45) size 130x30 - LayoutSVGViewportContainer {svg} at (45,45) size 130x30 - LayoutSVGRect {rect} at (45,45) size 130x30 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00]
diff --git a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.png b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.png index 3440bcb..f3c82f4 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.txt b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.txt index 7d4021c..4fac6225 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counter-04-b-expected.txt
@@ -1,8 +1,8 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x94 - LayoutBlockFlow {HTML} at (0,0) size 800x94 - LayoutBlockFlow {BODY} at (8,16) size 784x70 +layer at (0,0) size 800x97 + LayoutBlockFlow {HTML} at (0,0) size 800x97 + LayoutBlockFlow {BODY} at (8,16) size 784x73 LayoutBlockFlow {P} at (0,0) size 784x18 LayoutText {#text} at (0,0) size 237x17 text run at (0,0) width 237: "The following two lines should look " @@ -83,17 +83,17 @@ LayoutCounter (anonymous) at (150,0) size 10x17 text run at (150,0) width 10: "\x{25A0}" LayoutText {#text} at (0,0) size 0x0 - LayoutBlockFlow {DIV} at (0,52) size 784x18 - LayoutText {#text} at (0,0) size 188x17 - text run at (0,0) width 16: "\x{25FE} " - text run at (16,0) width 16: "\x{25FE} " - text run at (32,0) width 16: "\x{25FE} " - text run at (48,0) width 16: "\x{25FE} " - text run at (64,0) width 16: "\x{25FE} " - text run at (80,0) width 16: "\x{25FE} " - text run at (96,0) width 16: "\x{25FE} " - text run at (112,0) width 16: "\x{25FE} " - text run at (128,0) width 16: "\x{25FE} " - text run at (144,0) width 16: "\x{25FE} " - text run at (160,0) width 16: "\x{25FE} " - text run at (176,0) width 12: "\x{25FE}" + LayoutBlockFlow {DIV} at (0,52) size 784x21 + LayoutText {#text} at (0,3) size 210x17 + text run at (0,3) width 18: "\x{25FE} " + text run at (17,3) width 19: "\x{25FE} " + text run at (35,3) width 19: "\x{25FE} " + text run at (53,3) width 19: "\x{25FE} " + text run at (71,3) width 18: "\x{25FE} " + text run at (88,3) width 19: "\x{25FE} " + text run at (106,3) width 19: "\x{25FE} " + text run at (124,3) width 19: "\x{25FE} " + text run at (142,3) width 19: "\x{25FE} " + text run at (160,3) width 18: "\x{25FE} " + text run at (177,3) width 19: "\x{25FE} " + text run at (195,3) width 15: "\x{25FE}"
diff --git a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.png b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.png index ce1b5155..c275ae3 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.txt b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.txt index df6e9980..f6aa557 100644 --- a/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/css2.1/t1202-counters-04-b-expected.txt
@@ -1,8 +1,8 @@ layer at (0,0) size 800x600 LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x94 - LayoutBlockFlow {HTML} at (0,0) size 800x94 - LayoutBlockFlow {BODY} at (8,16) size 784x70 +layer at (0,0) size 800x97 + LayoutBlockFlow {HTML} at (0,0) size 800x97 + LayoutBlockFlow {BODY} at (8,16) size 784x73 LayoutBlockFlow {P} at (0,0) size 784x18 LayoutText {#text} at (0,0) size 237x17 text run at (0,0) width 237: "The following two lines should look " @@ -83,17 +83,17 @@ LayoutCounter (anonymous) at (300,0) size 24x17 text run at (300,0) width 24: "\x{25A0}.\x{25A0}" LayoutText {#text} at (0,0) size 0x0 - LayoutBlockFlow {DIV} at (0,52) size 784x18 - LayoutText {#text} at (0,0) size 380x17 - text run at (0,0) width 32: "\x{25FE}.\x{25FE} " - text run at (32,0) width 32: "\x{25FE}.\x{25FE} " - text run at (64,0) width 32: "\x{25FE}.\x{25FE} " - text run at (96,0) width 32: "\x{25FE}.\x{25FE} " - text run at (128,0) width 32: "\x{25FE}.\x{25FE} " - text run at (160,0) width 32: "\x{25FE}.\x{25FE} " - text run at (192,0) width 32: "\x{25FE}.\x{25FE} " - text run at (224,0) width 32: "\x{25FE}.\x{25FE} " - text run at (256,0) width 32: "\x{25FE}.\x{25FE} " - text run at (288,0) width 32: "\x{25FE}.\x{25FE} " - text run at (320,0) width 32: "\x{25FE}.\x{25FE} " - text run at (352,0) width 28: "\x{25FE}.\x{25FE}" + LayoutBlockFlow {DIV} at (0,52) size 784x21 + LayoutText {#text} at (0,3) size 423x17 + text run at (0,3) width 36: "\x{25FE}.\x{25FE} " + text run at (35,3) width 37: "\x{25FE}.\x{25FE} " + text run at (71,3) width 36: "\x{25FE}.\x{25FE} " + text run at (106,3) width 37: "\x{25FE}.\x{25FE} " + text run at (142,3) width 36: "\x{25FE}.\x{25FE} " + text run at (177,3) width 37: "\x{25FE}.\x{25FE} " + text run at (213,3) width 36: "\x{25FE}.\x{25FE} " + text run at (248,3) width 37: "\x{25FE}.\x{25FE} " + text run at (284,3) width 37: "\x{25FE}.\x{25FE} " + text run at (320,3) width 36: "\x{25FE}.\x{25FE} " + text run at (355,3) width 37: "\x{25FE}.\x{25FE} " + text run at (391,3) width 32: "\x{25FE}.\x{25FE}"
diff --git a/third_party/WebKit/LayoutTests/platform/win/fast/text/unicode-fallback-font-expected.png b/third_party/WebKit/LayoutTests/platform/win/fast/text/unicode-fallback-font-expected.png index bfbb24eb..8e67c7c 100644 --- a/third_party/WebKit/LayoutTests/platform/win/fast/text/unicode-fallback-font-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/fast/text/unicode-fallback-font-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/inspector-protocol/layout-fonts/languages-emoji-rare-glyphs-expected.txt b/third_party/WebKit/LayoutTests/platform/win/inspector-protocol/layout-fonts/languages-emoji-rare-glyphs-expected.txt index e4d76f0b..29a5d4ed 100644 --- a/third_party/WebKit/LayoutTests/platform/win/inspector-protocol/layout-fonts/languages-emoji-rare-glyphs-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/inspector-protocol/layout-fonts/languages-emoji-rare-glyphs-expected.txt
@@ -24,7 +24,7 @@ 🌱🌲🌳🌴🌵🌷🌸🌹🌺🌻🌼💐🌾🌿🍀🍁🍂🍃🍄🌰 #emoji: -"Segoe UI Symbol" : 20 +"Segoe UI Emoji" : 20 𓀀𓀁𓀂𓀃𓀄𓀅𓀆𓀇𓀈𓀉𓀊𓀋𓀌𓀍𓀎𓀏 #egyptian_hieroglyphs:
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/use-on-g-containing-symbol-expected.png b/third_party/WebKit/LayoutTests/platform/win/svg/custom/use-on-g-containing-symbol-expected.png deleted file mode 100644 index 1f3dc47..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/use-on-g-containing-symbol-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/svg/custom/use-on-g-containing-symbol-expected.txt b/third_party/WebKit/LayoutTests/platform/win/svg/custom/use-on-g-containing-symbol-expected.txt deleted file mode 100644 index 5ab380f..0000000 --- a/third_party/WebKit/LayoutTests/platform/win/svg/custom/use-on-g-containing-symbol-expected.txt +++ /dev/null
@@ -1,17 +0,0 @@ -layer at (0,0) size 800x600 - LayoutView at (0,0) size 800x600 -layer at (0,0) size 800x600 - LayoutSVGRoot {svg} at (20,45) size 489x82 - LayoutSVGHiddenContainer {defs} at (0,0) size 0x0 - LayoutSVGContainer {g} at (0,0) size 0x0 - LayoutSVGHiddenContainer {symbol} at (0,0) size 0x0 - LayoutSVGRect {rect} at (0,0) size 125x25 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00] - LayoutSVGContainer {g} at (245,45) size 130x30 [transform={m=((1.00,0.00)(0.00,1.00)) t=(125.00,25.00)}] - LayoutSVGRect {rect} at (245,45) size 130x30 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00] - LayoutSVGText {text} at (10,45) size 245x19 contains 1 chunk(s) - LayoutSVGInlineText {#text} at (0,0) size 245x18 - chunk 1 text run 1 at (10.00,60.00) startOffset 0 endOffset 38 width 244.40: "The two objects should look identical." - LayoutSVGContainer {use} at (45,45) size 130x30 [transform={m=((1.00,0.00)(0.00,1.00)) t=(25.00,25.00)}] - LayoutSVGContainer {g} at (45,45) size 130x30 - LayoutSVGViewportContainer {svg} at (45,45) size 130x30 - LayoutSVGRect {rect} at (45,45) size 130x30 [stroke={[type=SOLID] [color=#000080] [stroke width=5.00]}] [fill={[type=SOLID] [color=#FF0000]}] [x=0.00] [y=0.00] [width=60.00] [height=10.00]
diff --git a/third_party/WebKit/LayoutTests/platform/win7/css2.1/t1202-counter-04-b-expected.png b/third_party/WebKit/LayoutTests/platform/win7/css2.1/t1202-counter-04-b-expected.png deleted file mode 100644 index 7f4aed45..0000000 --- a/third_party/WebKit/LayoutTests/platform/win7/css2.1/t1202-counter-04-b-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win7/css2.1/t1202-counters-04-b-expected.png b/third_party/WebKit/LayoutTests/platform/win7/css2.1/t1202-counters-04-b-expected.png deleted file mode 100644 index e66dae0..0000000 --- a/third_party/WebKit/LayoutTests/platform/win7/css2.1/t1202-counters-04-b-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/WebKit/LayoutTests/svg/custom/use-attribute-invalidations.html b/third_party/WebKit/LayoutTests/svg/custom/use-attribute-invalidations.html index 7817ca48..8d4470b 100644 --- a/third_party/WebKit/LayoutTests/svg/custom/use-attribute-invalidations.html +++ b/third_party/WebKit/LayoutTests/svg/custom/use-attribute-invalidations.html
@@ -18,8 +18,8 @@ onload = function() { // Wait until first layout is finished. window.requestAnimationFrame(function() { - document.getElementById('use2').removeAttribute('width'); - document.getElementById('use3').setAttribute('height', '100'); + document.getElementById('use2').setAttribute('width', '100'); + document.getElementById('use3').removeAttribute('height'); }); } </script>
diff --git a/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol-expected.html b/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol-expected.html new file mode 100644 index 0000000..f718ea6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol-expected.html
@@ -0,0 +1,2 @@ +<!DOCTYPE html> +<div style="width: 100px; height: 100px; background-color: green"></div>
diff --git a/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol.html b/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol.html new file mode 100644 index 0000000..9f1fbb4 --- /dev/null +++ b/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<svg> + <g id="rectgroup"> + <symbol id="rect"> + <rect width="50" height="100"/> + </symbol> + <use xlink:href="#rect" fill="green"/> + </g> + <use xlink:href="#rectgroup" x="50"/> +</svg>
diff --git a/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol.svg b/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol.svg deleted file mode 100644 index ef7addcb..0000000 --- a/third_party/WebKit/LayoutTests/svg/custom/use-on-g-containing-symbol.svg +++ /dev/null
@@ -1,19 +0,0 @@ -<?xml version="1.0" standalone="no"?> -<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> -<svg width="800" height="600" viewBox="0 0 400 300" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> -<defs> - <g id="symbol"> - <symbol overflow="visible"> - <rect stroke-width="5px" fill="red" stroke="navy" width="60" height="10"/> - </symbol> - </g> -</defs> - -<g transform="translate(125 25)"> - <rect stroke-width="5px" fill="red" stroke="navy" width="60" height="10"/> -</g> - -<text x="10" y="60">The two objects should look identical.</text> -<use x="25" y="25" xlink:href="#symbol"/> -</svg> -
diff --git a/third_party/WebKit/LayoutTests/svg/custom/use-symbol-initial-width-height-expected.html b/third_party/WebKit/LayoutTests/svg/custom/use-symbol-initial-width-height-expected.html new file mode 100644 index 0000000..f718ea6 --- /dev/null +++ b/third_party/WebKit/LayoutTests/svg/custom/use-symbol-initial-width-height-expected.html
@@ -0,0 +1,2 @@ +<!DOCTYPE html> +<div style="width: 100px; height: 100px; background-color: green"></div>
diff --git a/third_party/WebKit/LayoutTests/svg/custom/use-symbol-initial-width-height.html b/third_party/WebKit/LayoutTests/svg/custom/use-symbol-initial-width-height.html new file mode 100644 index 0000000..7b4267d --- /dev/null +++ b/third_party/WebKit/LayoutTests/svg/custom/use-symbol-initial-width-height.html
@@ -0,0 +1,8 @@ +<!DOCTYPE html> +<svg width="100" height="100"> + <symbol id="s" width="0"> + <rect width="100%" height="100%" fill="green"/> + </symbol> + <rect width="100%" height="100%" fill="red"/> + <use xlink:href="#s"/> +</svg>
diff --git a/third_party/WebKit/LayoutTests/svg/dom/svg-document-set-title-mutations.html b/third_party/WebKit/LayoutTests/svg/dom/svg-document-set-title-mutations.html new file mode 100644 index 0000000..6323c96e --- /dev/null +++ b/third_party/WebKit/LayoutTests/svg/dom/svg-document-set-title-mutations.html
@@ -0,0 +1,21 @@ +<!DOCTYPE html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +test(function() { + var doc = document.implementation.createDocument("http://www.w3.org/2000/svg", "svg", null); + doc.title = 'old'; + var titleElement = doc.querySelector('title'); + var observer = new MutationObserver(function(mutations) { + assert_equals(mutations.length, 1); + assert_equals(mutations[0].type, 'childList'); + assert_equals(mutations[0].addedNodes[0].data, 'new'); + assert_equals(mutations[0].addedNodes.length, 1); + assert_equals(mutations[0].removedNodes[0].data, 'old'); + assert_equals(mutations[0].removedNodes.length, 1); + }); + + observer.observe(titleElement, { childList: true }); + doc.title = 'new'; +}, "Test for mutations to childList when setting title of svg document."); +</script>
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt index 976fd19..ff3cd52d 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-dedicated-worker-expected.txt
@@ -639,6 +639,7 @@ [Worker] setter onmessage [Worker] setter onopen [Worker] interface WorkerGlobalScope : EventTarget +[Worker] getter addressSpace [Worker] getter console [Worker] getter crypto [Worker] getter indexedDB
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index 511afc8f..db02c2af 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -956,6 +956,7 @@ interface Document : Node getter URL getter activeElement + getter addressSpace getter anchors getter applets getter body
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt index ffc219d..389dc39 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-shared-worker-expected.txt
@@ -631,6 +631,7 @@ [Worker] setter onmessage [Worker] setter onopen [Worker] interface WorkerGlobalScope : EventTarget +[Worker] getter addressSpace [Worker] getter console [Worker] getter crypto [Worker] getter indexedDB
diff --git a/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorld.cpp b/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorld.cpp index c48e4cb..62ee2276 100644 --- a/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorld.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/DOMWrapperWorld.cpp
@@ -176,7 +176,7 @@ ASSERT(isIsolatedWorldId(worldId)); WorldMap& map = isolatedWorldMap(); - WorldMap::AddResult result = map.add(worldId, 0); + WorldMap::AddResult result = map.add(worldId, nullptr); RefPtr<DOMWrapperWorld> world = result.storedValue->value; if (world) { ASSERT(world->worldId() == worldId);
diff --git a/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp b/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp index 6bcbf1c0..e6a30e4 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ScriptValueSerializer.cpp
@@ -586,7 +586,7 @@ ScriptValueSerializer::StateBase* ScriptValueSerializer::ObjectState::advance(ScriptValueSerializer& serializer) { if (m_propertyNames.IsEmpty()) { - if (!composite()->GetPropertyNames(serializer.context()).ToLocal(&m_propertyNames)) + if (!composite()->GetOwnPropertyNames(serializer.context()).ToLocal(&m_propertyNames)) return serializer.checkException(this); } return serializeProperties(false, serializer); @@ -1108,7 +1108,7 @@ ScriptValueSerializer::StateBase* ScriptValueSerializer::startArrayState(v8::Local<v8::Array> array, ScriptValueSerializer::StateBase* next) { v8::Local<v8::Array> propertyNames; - if (!array->GetPropertyNames(context()).ToLocal(&propertyNames)) + if (!array->GetOwnPropertyNames(context()).ToLocal(&propertyNames)) return checkException(next); uint32_t length = array->Length();
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Binding.h b/third_party/WebKit/Source/bindings/core/v8/V8Binding.h index 35200541..0b45e58 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Binding.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8Binding.h
@@ -724,10 +724,9 @@ template <typename T, typename V8T> HeapVector<Member<T>> toMemberNativeArray(v8::Local<v8::Value> value, int argumentIndex, v8::Isolate* isolate, ExceptionState& exceptionState) { - v8::Local<v8::Value> v8Value(v8::Local<v8::Value>::New(isolate, value)); uint32_t length = 0; if (value->IsArray()) { - length = v8::Local<v8::Array>::Cast(v8Value)->Length(); + length = v8::Local<v8::Array>::Cast(value)->Length(); } else if (!toV8Sequence(value, length, isolate, exceptionState)) { if (!exceptionState.hadException()) exceptionState.throwTypeError(ExceptionMessages::notAnArrayTypeArgumentOrValue(argumentIndex)); @@ -736,7 +735,7 @@ HeapVector<Member<T>> result; result.reserveInitialCapacity(length); - v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(v8Value); + v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value); v8::TryCatch block(isolate); for (uint32_t i = 0; i < length; ++i) { v8::Local<v8::Value> element; @@ -841,8 +840,7 @@ return false; } - v8::Local<v8::Value> v8Value(v8::Local<v8::Value>::New(isolate, value)); - v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(v8Value); + v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value); v8::Local<v8::String> lengthSymbol = v8AtomicString(isolate, "length"); // FIXME: The specification states that the length property should be used as fallback, if value
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.cpp b/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.cpp index baf982d..df87a675 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.cpp
@@ -138,7 +138,7 @@ } } -void installConstantInternal(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const V8DOMConfiguration::ConstantConfiguration& constant) +void installConstantInternal(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const V8DOMConfiguration::ConstantConfiguration& constant) { v8::Local<v8::String> constantName = v8AtomicString(isolate, constant.name); v8::PropertyAttribute attributes = @@ -160,7 +160,7 @@ default: ASSERT_NOT_REACHED(); } - functionDescriptor->Set(constantName, value, attributes); + interfaceTemplate->Set(constantName, value, attributes); prototypeTemplate->Set(constantName, value, attributes); } @@ -259,23 +259,23 @@ installAccessorInternal(isolate, instance, prototype, interface, signature, accessor, world); } -void V8DOMConfiguration::installConstants(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration* constants, size_t constantCount) +void V8DOMConfiguration::installConstants(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration* constants, size_t constantCount) { for (size_t i = 0; i < constantCount; ++i) - installConstantInternal(isolate, functionDescriptor, prototypeTemplate, constants[i]); + installConstantInternal(isolate, interfaceTemplate, prototypeTemplate, constants[i]); } -void V8DOMConfiguration::installConstant(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration& constant) +void V8DOMConfiguration::installConstant(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration& constant) { - installConstantInternal(isolate, functionDescriptor, prototypeTemplate, constant); + installConstantInternal(isolate, interfaceTemplate, prototypeTemplate, constant); } -void V8DOMConfiguration::installConstantWithGetter(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const char* name, v8::AccessorNameGetterCallback getter) +void V8DOMConfiguration::installConstantWithGetter(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const char* name, v8::AccessorNameGetterCallback getter) { v8::Local<v8::String> constantName = v8AtomicString(isolate, name); v8::PropertyAttribute attributes = static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); - functionDescriptor->SetNativeDataProperty(constantName, getter, 0, v8::Local<v8::Value>(), attributes); + interfaceTemplate->SetNativeDataProperty(constantName, getter, 0, v8::Local<v8::Value>(), attributes); prototypeTemplate->SetNativeDataProperty(constantName, getter, 0, v8::Local<v8::Value>(), attributes); } @@ -304,31 +304,26 @@ installMethodInternal(isolate, v8::Local<v8::ObjectTemplate>(), prototypeTemplate, v8::Local<v8::FunctionTemplate>(), signature, method, world); } -v8::Local<v8::Signature> V8DOMConfiguration::installDOMClassTemplate(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> functionDescriptor, const char* interfaceName, v8::Local<v8::FunctionTemplate> parentClass, size_t fieldCount, - const AttributeConfiguration* attributes, size_t attributeCount, - const AccessorConfiguration* accessors, size_t accessorCount, - const MethodConfiguration* methods, size_t methodCount) +void V8DOMConfiguration::initializeDOMInterfaceTemplate(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> interfaceTemplate, const char* interfaceName, v8::Local<v8::FunctionTemplate> parentInterfaceTemplate, size_t v8InternalFieldCount) { - functionDescriptor->SetClassName(v8AtomicString(isolate, interfaceName)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionDescriptor->InstanceTemplate(); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionDescriptor->PrototypeTemplate(); - instanceTemplate->SetInternalFieldCount(fieldCount); - if (!parentClass.IsEmpty()) { - functionDescriptor->Inherit(parentClass); + interfaceTemplate->SetClassName(v8AtomicString(isolate, interfaceName)); + interfaceTemplate->ReadOnlyPrototype(); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); + instanceTemplate->SetInternalFieldCount(v8InternalFieldCount); + // TODO(yukishiino): We should set the class string to the platform object + // (|instanceTemplate|), too. The reason that we don't set it is that + // it prevents minor GC to collect unreachable DOM objects (a layout test + // fast/dom/minor-dom-gc.html fails if we set the class string). + // See also http://heycam.github.io/webidl/#es-platform-objects + setClassString(isolate, prototypeTemplate, interfaceName); + if (!parentInterfaceTemplate.IsEmpty()) { + interfaceTemplate->Inherit(parentInterfaceTemplate); // Marks the prototype object as one of native-backed objects. // This is needed since bug 110436 asks WebKit to tell native-initiated prototypes from pure-JS ones. // This doesn't mark kinds "root" classes like Node, where setting this changes prototype chain structure. prototypeTemplate->SetInternalFieldCount(v8PrototypeInternalFieldcount); } - - v8::Local<v8::Signature> defaultSignature = v8::Signature::New(isolate, functionDescriptor); - if (attributeCount) - installAttributes(isolate, instanceTemplate, prototypeTemplate, attributes, attributeCount); - if (accessorCount) - installAccessors(isolate, instanceTemplate, prototypeTemplate, functionDescriptor, defaultSignature, accessors, accessorCount); - if (methodCount) - installMethods(isolate, instanceTemplate, prototypeTemplate, functionDescriptor, defaultSignature, methods, methodCount); - return defaultSignature; } v8::Local<v8::FunctionTemplate> V8DOMConfiguration::domClassTemplate(v8::Isolate* isolate, WrapperTypeInfo* wrapperTypeInfo, void (*configureDOMClassTemplate)(v8::Local<v8::FunctionTemplate>, v8::Isolate*))
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.h b/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.h index 3730ab3..e629ba6 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8DOMConfiguration.h
@@ -37,8 +37,7 @@ namespace blink { class CORE_EXPORT V8DOMConfiguration final { - DISALLOW_NEW(); - WTF_MAKE_NONCOPYABLE(V8DOMConfiguration); + STATIC_ONLY(V8DOMConfiguration); public: // The following Configuration structs and install methods are used for // setting multiple properties on ObjectTemplate / FunctionTemplate, used @@ -138,11 +137,11 @@ // installConstantWithGetter is used when some C++ code needs to be executed // when the constant is accessed, e.g. to handle deprecation or measuring // usage. The property appears the same to scripts, but is slower to access. - static void installConstants(v8::Isolate*, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration*, size_t constantCount); + static void installConstants(v8::Isolate*, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration*, size_t constantCount); - static void installConstant(v8::Isolate*, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration&); + static void installConstant(v8::Isolate*, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const ConstantConfiguration&); - static void installConstantWithGetter(v8::Isolate*, v8::Local<v8::FunctionTemplate> functionDescriptor, v8::Local<v8::ObjectTemplate> prototypeTemplate, const char* name, v8::AccessorNameGetterCallback); + static void installConstantWithGetter(v8::Isolate*, v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Local<v8::ObjectTemplate> prototypeTemplate, const char* name, v8::AccessorNameGetterCallback); // MethodConfiguration translates into calls to Set() for setting up an // object's callbacks. It sets the method on both the FunctionTemplate or @@ -191,10 +190,7 @@ static void installMethod(v8::Isolate*, v8::Local<v8::ObjectTemplate>, v8::Local<v8::Signature>, const SymbolKeyedMethodConfiguration&); - static v8::Local<v8::Signature> installDOMClassTemplate(v8::Isolate*, v8::Local<v8::FunctionTemplate>, const char* interfaceName, v8::Local<v8::FunctionTemplate> parentClass, size_t fieldCount, - const AttributeConfiguration*, size_t attributeCount, - const AccessorConfiguration*, size_t accessorCount, - const MethodConfiguration*, size_t methodCount); + static void initializeDOMInterfaceTemplate(v8::Isolate*, v8::Local<v8::FunctionTemplate> interfaceTemplate, const char* interfaceName, v8::Local<v8::FunctionTemplate> parentInterfaceTemplate, size_t v8InternalFieldCount); static v8::Local<v8::FunctionTemplate> domClassTemplate(v8::Isolate*, WrapperTypeInfo*, void (*)(v8::Local<v8::FunctionTemplate>, v8::Isolate*));
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.cpp b/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.cpp index c6eba598..dcb048c0 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8DOMWrapper.cpp
@@ -31,8 +31,6 @@ #include "bindings/core/v8/V8DOMWrapper.h" #include "bindings/core/v8/V8Binding.h" -#include "bindings/core/v8/V8HTMLCollection.h" -#include "bindings/core/v8/V8HTMLDocument.h" #include "bindings/core/v8/V8Location.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "bindings/core/v8/V8PerContextData.h" @@ -42,34 +40,6 @@ namespace blink { -static v8::Local<v8::Object> wrapInShadowTemplate(v8::Local<v8::Object> wrapper, ScriptWrappable* scriptWrappable, v8::Isolate* isolate) -{ - static int shadowTemplateKey; // This address is used for a key to look up the dom template. - V8PerIsolateData* data = V8PerIsolateData::from(isolate); - v8::Local<v8::FunctionTemplate> shadowTemplate = data->existingDOMTemplate(&shadowTemplateKey); - if (shadowTemplate.IsEmpty()) { - shadowTemplate = v8::FunctionTemplate::New(isolate); - if (shadowTemplate.IsEmpty()) - return v8::Local<v8::Object>(); - shadowTemplate->SetClassName(v8AtomicString(isolate, "HTMLDocument")); - shadowTemplate->Inherit(V8HTMLDocument::domTemplate(isolate)); - shadowTemplate->InstanceTemplate()->SetInternalFieldCount(V8HTMLDocument::internalFieldCount); - data->setDOMTemplate(&shadowTemplateKey, shadowTemplate); - } - - v8::Local<v8::Function> shadowConstructor; - if (!shadowTemplate->GetFunction(isolate->GetCurrentContext()).ToLocal(&shadowConstructor)) - return v8::Local<v8::Object>(); - - v8::Local<v8::Object> shadow; - if (!V8ScriptRunner::instantiateObject(isolate, shadowConstructor).ToLocal(&shadow)) - return v8::Local<v8::Object>(); - if (!v8CallBoolean(shadow->SetPrototype(isolate->GetCurrentContext(), wrapper))) - return v8::Local<v8::Object>(); - V8DOMWrapper::setNativeInfo(wrapper, &V8HTMLDocument::wrapperTypeInfo, scriptWrappable); - return shadow; -} - v8::Local<v8::Object> V8DOMWrapper::createWrapper(v8::Isolate* isolate, v8::Local<v8::Object> creationContext, const WrapperTypeInfo* type, ScriptWrappable* scriptWrappable) { ASSERT(!type->equals(&V8Window::wrapperTypeInfo)); @@ -88,9 +58,6 @@ return v8::Local<v8::Object>(); } - if (type == &V8HTMLDocument::wrapperTypeInfo && !wrapper.IsEmpty()) - wrapper = wrapInShadowTemplate(wrapper, scriptWrappable, isolate); - return wrapper; }
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp b/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp index f22eaf0..0555700 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/V8GCController.cpp
@@ -335,7 +335,7 @@ // v8::kGCCallbackFlagForced forces a Blink heap garbage collection // when a garbage collection was forced from V8. This is either used // for tests that force GCs from JavaScript to verify that objects die - // when expected, or when handling memory pressure notifications. + // when expected. if (flags & v8::kGCCallbackFlagForced) { // This single GC is not enough for two reasons: // (1) The GC is not precise because the GC scans on-stack pointers conservatively. @@ -346,7 +346,7 @@ // Regarding (1), we force a precise GC at the end of the current event loop. So if you want // to collect all garbage, you need to wait until the next event loop. // Regarding (2), it would be OK in practice to trigger only one GC per gcEpilogue, because - // GCController.collectAll() forces 7 V8's GC. + // GCController.collectAll() forces multiple V8's GC. Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); // Forces a precise GC at the end of the current event loop. @@ -356,6 +356,19 @@ } } + // v8::kGCCallbackFlagCollectAllAvailableGarbage is used when V8 handles + // low memory notifications. + if (flags & v8::kGCCallbackFlagCollectAllAvailableGarbage) { + // This single GC is not enough. See the above comment. + Heap::collectGarbage(BlinkGC::HeapPointersOnStack, BlinkGC::GCWithSweep, BlinkGC::ForcedGC); + + // Do not force a precise GC at the end of the current event loop. + // According to UMA stats, the collection rate of the precise GC + // scheduled at the end of the low memory handling is extremely low, + // because the above conservative GC is sufficient for collecting + // most objects. So we intentionally don't schedule a precise GC here. + } + TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data()); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp b/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp index 8752c97..b0564f6 100644 --- a/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/WindowProxy.cpp
@@ -74,7 +74,6 @@ static void checkDocumentWrapper(v8::Local<v8::Object> wrapper, Document* document) { ASSERT(V8Document::toImpl(wrapper) == document); - ASSERT(!document->isHTMLDocument() || (V8Document::toImpl(v8::Local<v8::Object>::Cast(wrapper->GetPrototype())) == document)); } PassOwnPtrWillBeRawPtr<WindowProxy> WindowProxy::create(v8::Isolate* isolate, Frame* frame, DOMWrapperWorld& world)
diff --git a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp index 72e250e5..c101782 100644 --- a/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/custom/V8HTMLAllCollectionCustom.cpp
@@ -57,10 +57,12 @@ } template<class CallbackInfo> -static v8::Local<v8::Value> getItem(HTMLAllCollection* collection, v8::Local<v8::Value> argument, const CallbackInfo& info) +static v8::Local<v8::Value> getItem(HTMLAllCollection* collection, v8::Local<v8::Value> argument, const CallbackInfo& info, + UseCounter::Feature namedFeature, UseCounter::Feature indexedFeature, UseCounter::Feature indexedWithNonNumberFeature) { v8::Local<v8::Uint32> index; if (!argument->ToArrayIndex(info.GetIsolate()->GetCurrentContext()).ToLocal(&index)) { + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), namedFeature); TOSTRING_DEFAULT(V8StringResource<>, name, argument, v8::Undefined(info.GetIsolate())); v8::Local<v8::Value> result = getNamedItems(collection, name, info); @@ -70,31 +72,45 @@ return result; } + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), indexedFeature); + if (!argument->IsNumber()) + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), indexedWithNonNumberFeature); + RefPtrWillBeRawPtr<Element> result = collection->item(index->Value()); return toV8(result.release(), info.Holder(), info.GetIsolate()); } void V8HTMLAllCollection::itemMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info) { + if (info.Length() < 1) { + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::DocumentAllItemNoArguments); + return; + } + HTMLAllCollection* impl = V8HTMLAllCollection::toImpl(info.Holder()); - v8SetReturnValue(info, getItem(impl, info[0], info)); + v8SetReturnValue(info, getItem(impl, info[0], info, UseCounter::DocumentAllItemNamed, + UseCounter::DocumentAllItemIndexed, UseCounter::DocumentAllItemIndexedWithNonNumber)); } void V8HTMLAllCollection::legacyCallCustom(const v8::FunctionCallbackInfo<v8::Value>& info) { - if (info.Length() < 1) - return; - - HTMLAllCollection* impl = V8HTMLAllCollection::toImpl(info.Holder()); - Node& ownerNode = impl->ownerNode(); - - UseCounter::countIfNotPrivateScript(info.GetIsolate(), ownerNode.document(), UseCounter::DocumentAllLegacyCall); - - if (info.Length() == 1) { - v8SetReturnValue(info, getItem(impl, info[0], info)); + if (info.Length() < 1) { + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::DocumentAllLegacyCallNoArguments); return; } + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::DocumentAllLegacyCall); + + HTMLAllCollection* impl = V8HTMLAllCollection::toImpl(info.Holder()); + + if (info.Length() == 1) { + v8SetReturnValue(info, getItem(impl, info[0], info, UseCounter::DocumentAllLegacyCallNamed, + UseCounter::DocumentAllLegacyCallIndexed, UseCounter::DocumentAllLegacyCallIndexedWithNonNumber)); + return; + } + + UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::DocumentAllLegacyCallTwoArguments); + // If there is a second argument it is the index of the item we want. TOSTRING_VOID(V8StringResource<>, name, info[0]); v8::Local<v8::Uint32> index;
diff --git a/third_party/WebKit/Source/bindings/templates/constants.cpp b/third_party/WebKit/Source/bindings/templates/constants.cpp index a0020c6be..6a9cef4 100644 --- a/third_party/WebKit/Source/bindings/templates/constants.cpp +++ b/third_party/WebKit/Source/bindings/templates/constants.cpp
@@ -33,7 +33,7 @@ {{constant_configuration(constant)}}, {% endfor %} }; -V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, {{v8_class}}Constants, WTF_ARRAY_LENGTH({{v8_class}}Constants)); +V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, {{v8_class}}Constants, WTF_ARRAY_LENGTH({{v8_class}}Constants)); {% endif %} {# Runtime-enabled constants #} {% for constant_tuple in runtime_enabled_constants %} @@ -41,13 +41,13 @@ {% for constant in constant_tuple[1] %} {% set constant_name = constant.name.title().replace('_', '') %} const V8DOMConfiguration::ConstantConfiguration constant{{constant_name}}Configuration = {{constant_configuration(constant)}}; -V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constant{{constant_name}}Configuration); +V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constant{{constant_name}}Configuration); {% endfor %} {% endfilter %} {% endfor %} {# Constants with [DeprecateAs] or [MeasureAs] or [OriginTrialEnabled] #} {% for constant in special_getter_constants %} -V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "{{constant.name}}", {{cpp_class}}V8Internal::{{constant.name}}ConstantGetterCallback); +V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "{{constant.name}}", {{cpp_class}}V8Internal::{{constant.name}}ConstantGetterCallback); {% endfor %} {# Check constants #} {% if not do_not_check_constants %}
diff --git a/third_party/WebKit/Source/bindings/templates/interface_base.cpp b/third_party/WebKit/Source/bindings/templates/interface_base.cpp index 593142c4..c242de8 100644 --- a/third_party/WebKit/Source/bindings/templates/interface_base.cpp +++ b/third_party/WebKit/Source/bindings/templates/interface_base.cpp
@@ -268,87 +268,83 @@ {% from 'attributes.cpp' import attribute_configuration with context %} {% from 'constants.cpp' import install_constants with context %} {% if has_partial_interface or is_partial %} -void {{v8_class_or_partial}}::install{{v8_class}}Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +void {{v8_class_or_partial}}::install{{v8_class}}Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) {% else %} -static void install{{v8_class}}Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void install{{v8_class}}Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) {% endif %} { + {% set newline = '' %} + // Initialize the interface object's template. {% if is_partial %} - {{v8_class}}::install{{v8_class}}Template(functionTemplate, isolate); + {{v8_class}}::install{{v8_class}}Template(interfaceTemplate, isolate); {% else %} - functionTemplate->ReadOnlyPrototype(); - {% endif %} - - v8::Local<v8::Signature> defaultSignature; - {% set parent_template = + {% set parent_interface_template = '%s::domTemplateForNamedPropertiesObject(isolate)' % v8_class if has_named_properties_object else 'V8%s::domTemplate(isolate)' % parent_interface - if parent_interface else 'v8::Local<v8::FunctionTemplate>()' %} - {% if runtime_enabled_function %} - if (!{{runtime_enabled_function}}()) - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, {{v8_class}}::wrapperTypeInfo.interfaceName, {{parent_template}}, {{v8_class}}::internalFieldCount, 0, 0, 0, 0, 0, 0); - else - {% endif %} - {% set runtime_enabled_indent = 4 if runtime_enabled_function else 0 %} - {% filter indent(runtime_enabled_indent, true) %} - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, {{v8_class}}::wrapperTypeInfo.interfaceName, {{parent_template}}, {{v8_class}}::internalFieldCount, - {# Test needed as size 0 arrays definitions are not allowed per standard - (so objects have distinct addresses), which is enforced by MSVC. - 8.5.1 Aggregates [dcl.init.aggr] - An array of unknown size initialized with a brace-enclosed - initializer-list containing n initializer-clauses, where n shall be - greater than zero, is defined as having n elements (8.3.4). #} - {% set attributes_name, attributes_length = - ('%sAttributes' % v8_class, - 'WTF_ARRAY_LENGTH(%sAttributes)' % v8_class) - if has_attribute_configuration else (0, 0) %} - {% set accessors_name, accessors_length = - ('%sAccessors' % v8_class, - 'WTF_ARRAY_LENGTH(%sAccessors)' % v8_class) - if has_accessor_configuration else (0, 0) %} - {% set methods_name, methods_length = - ('%sMethods' % v8_class, - 'WTF_ARRAY_LENGTH(%sMethods)' % v8_class) - if method_configuration_methods else (0, 0) %} - {{attributes_name}}, {{attributes_length}}, - {{accessors_name}}, {{accessors_length}}, - {{methods_name}}, {{methods_length}}); - {% endfilter %} - + if parent_interface else + 'v8::Local<v8::FunctionTemplate>()' %} + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, {{v8_class}}::wrapperTypeInfo.interfaceName, {{parent_interface_template}}, {{v8_class}}::internalFieldCount); {% if constructors or has_custom_constructor or has_event_constructor %} - functionTemplate->SetCallHandler({{v8_class}}::constructorCallback); - functionTemplate->SetLength({{interface_length}}); + interfaceTemplate->SetCallHandler({{v8_class}}::constructorCallback); + interfaceTemplate->SetLength({{interface_length}}); {% endif %} - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + {% endif %}{# is_partial #} + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - {% if not is_partial %} - {# TODO(yukishiino): We should set the class string to the platform object - (|instanceTemplate|), too. The reason that we don\'t set it is that - it prevents minor GC to collect unreachable DOM objects (a layout test - fast/dom/minor-dom-gc.html fails if we set the class string). - See also http://heycam.github.io/webidl/#es-platform-objects #} - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, {{v8_class}}::wrapperTypeInfo.interfaceName); + + {%- if not is_partial %} + {% if interface_name == 'Window' %}{{newline}} + prototypeTemplate->SetInternalFieldCount(V8Window::internalFieldCount); {% endif %} - {% if custom_registration_methods %} - ExecutionContext* context = currentExecutionContext(isolate); - ALLOW_UNUSED_LOCAL(context); + {% if is_global %}{{newline}} + interfaceTemplate->SetHiddenPrototype(true); {% endif %} - {% if has_access_check_callbacks %} + {% endif %} + + // Register DOM constants, attributes and operations. + {% if runtime_enabled_function %} + if ({{runtime_enabled_function}}()) { + {% endif %} + {% filter indent(4 if runtime_enabled_function else 0, true) %} + {% if constants %} + {{install_constants() | indent}} + {% endif %} + {% if has_attribute_configuration %} + V8DOMConfiguration::installAttributes(isolate, instanceTemplate, prototypeTemplate, {{'%sAttributes' % v8_class}}, {{'WTF_ARRAY_LENGTH(%sAttributes)' % v8_class}}); + {% endif %} + {% if has_accessor_configuration %} + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, {{'%sAccessors' % v8_class}}, {{'WTF_ARRAY_LENGTH(%sAccessors)' % v8_class}}); + {% endif %} + {% if method_configuration_methods %} + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, {{'%sMethods' % v8_class}}, {{'WTF_ARRAY_LENGTH(%sMethods)' % v8_class}}); + {% endif %} + {% endfilter %}{{newline}} + {% if runtime_enabled_function %} + } // if ({{runtime_enabled_function}}()) + {% endif %} + + {%- if has_access_check_callbacks %}{{newline}} + // Cross-origin access check instanceTemplate->SetAccessCheckCallback({{cpp_class}}V8Internal::securityCheck, v8::External::New(isolate, const_cast<WrapperTypeInfo*>(&{{v8_class}}::wrapperTypeInfo))); {% endif %} - {% if has_array_iterator %} + + {%- if has_array_iterator %}{{newline}} + // Array iterator {% filter runtime_enabled('RuntimeEnabledFeatures::iterableCollectionsEnabled') %} {% if is_global %} instanceTemplate->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); {% else %} prototypeTemplate->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); {% endif %} - {% endfilter %}{# runtime_enabled() #} + {% endfilter %} {% endif %} - {% set runtime_enabled_features = dict() %} + + {%- set runtime_enabled_features = dict() %} {% for attribute in attributes if attribute.runtime_enabled_function and not attribute.exposed_test %} @@ -357,7 +353,7 @@ {% endif %} {% set unused = runtime_enabled_features.get(attribute.runtime_enabled_function).append(attribute) %} {% endfor %} - {% for runtime_enabled_feature in runtime_enabled_features | sort %} + {% for runtime_enabled_feature in runtime_enabled_features | sort %}{{newline}} if ({{runtime_enabled_feature}}()) { {% set distinct_attributes = [] %} {% for attribute in runtime_enabled_features.get(runtime_enabled_feature) | sort @@ -370,37 +366,41 @@ {% else %} const V8DOMConfiguration::AccessorConfiguration accessor{{attribute.name}}Configuration = \ {{attribute_configuration(attribute)}}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessor{{attribute.name}}Configuration); + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessor{{attribute.name}}Configuration); {% endif %} {% endfor %} } {% endfor %} - {% if constants %} - {{install_constants() | indent}} - {% endif %} - {# Special operations #} - {% if indexed_property_getter %} + + {%- if indexed_property_getter %}{{newline}} + // Indexed properties {{install_indexed_property_handler('instanceTemplate') | indent}} {% endif %} {% if named_property_getter and not has_named_properties_object %} + // Named properties {{install_named_property_handler('instanceTemplate') | indent}} {% endif %} - {% if iterator_method %} + + {%- if iterator_method %}{{newline}} {% filter exposed(iterator_method.exposed_test) %} {% filter runtime_enabled(iterator_method.runtime_enabled_function) %} + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, {{cpp_class_or_partial}}V8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); - {% endfilter %}{# runtime_enabled() #} - {% endfilter %}{# exposed() #} + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); + {% endfilter %} + {% endfilter %} {% endif %} - {# End special operations #} - {% if has_custom_legacy_call_as_function %} - functionTemplate->InstanceTemplate()->SetCallAsFunctionHandler({{v8_class}}::legacyCallCustom); + + {%- if has_custom_legacy_call_as_function %}{{newline}} + instanceTemplate->SetCallAsFunctionHandler({{v8_class}}::legacyCallCustom); {% endif %} - {% if interface_name == 'HTMLAllCollection' %} - {# Needed for legacy support of document.all #} - functionTemplate->InstanceTemplate()->MarkAsUndetectable(); + + {%- if interface_name == 'HTMLAllCollection' %}{{newline}} + // Needed for legacy support of document.all + instanceTemplate->MarkAsUndetectable(); {% endif %} + + {%- if custom_registration_methods %}{{newline}} {% for method in custom_registration_methods %} {# install_custom_signature #} {% filter exposed(method.overloads.exposed_test_all @@ -411,23 +411,13 @@ method.runtime_enabled_function) %} {% if method.is_do_not_check_security %} {{install_do_not_check_security_method(method, '', 'instanceTemplate', 'prototypeTemplate') | indent}} - {% else %}{# is_do_not_check_security #} - {% set signature = 'v8::Local<v8::Signature>()' if method.is_do_not_check_signature else 'defaultSignature' %} - {{install_custom_signature(method, 'instanceTemplate', 'prototypeTemplate', 'functionTemplate', signature) | indent}} - {% endif %}{# is_do_not_check_security #} - {% endfilter %}{# runtime_enabled() #} - {% endfilter %}{# exposed() #} + {% else %} + {% set signature = 'v8::Local<v8::Signature>()' if method.is_do_not_check_signature else 'signature' %} + {{install_custom_signature(method, 'instanceTemplate', 'prototypeTemplate', 'interfaceTemplate', signature) | indent}} + {% endif %} + {% endfilter %} + {% endfilter %} {% endfor %} - {# Special interfaces #} - {% if not is_partial %} - {% if interface_name == 'Window' %} - - instanceTemplate->SetInternalFieldCount(V8Window::internalFieldCount); - prototypeTemplate->SetInternalFieldCount(V8Window::internalFieldCount); - {% endif %} - {% if is_global or interface_name == 'HTMLDocument' %} - functionTemplate->SetHiddenPrototype(true); - {% endif %} {% endif %} }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp index 8a7b4b4..17e5624c 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp
@@ -71,20 +71,18 @@ {"type", SVGTestInterfaceV8Internal::typeAttributeGetterCallback, SVGTestInterfaceV8Internal::typeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; -static void installV8SVGTestInterfaceTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8SVGTestInterfaceTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8SVGTestInterface::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8SVGTestInterface::internalFieldCount, - 0, 0, - V8SVGTestInterfaceAccessors, WTF_ARRAY_LENGTH(V8SVGTestInterfaceAccessors), - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8SVGTestInterface::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8SVGTestInterface::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8SVGTestInterface::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8SVGTestInterfaceAccessors, WTF_ARRAY_LENGTH(V8SVGTestInterfaceAccessors)); } v8::Local<v8::FunctionTemplate> V8SVGTestInterface::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp index 06ecd87..57790f6 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp
@@ -115,26 +115,25 @@ TestExceptionV8Internal::constructor(info); } -static void installV8TestExceptionTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestExceptionTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestException::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestException::internalFieldCount, - 0, 0, - V8TestExceptionAccessors, WTF_ARRAY_LENGTH(V8TestExceptionAccessors), - V8TestExceptionMethods, WTF_ARRAY_LENGTH(V8TestExceptionMethods)); - functionTemplate->SetCallHandler(V8TestException::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestException::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestException::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestException::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestException::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. const V8DOMConfiguration::ConstantConfiguration V8TestExceptionConstants[] = { {"UNSIGNED_SHORT_CONSTANT", 1, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, }; - V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8TestExceptionConstants, WTF_ARRAY_LENGTH(V8TestExceptionConstants)); + V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestExceptionConstants, WTF_ARRAY_LENGTH(V8TestExceptionConstants)); + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestExceptionAccessors, WTF_ARRAY_LENGTH(V8TestExceptionAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestExceptionMethods, WTF_ARRAY_LENGTH(V8TestExceptionMethods)); } v8::Local<v8::FunctionTemplate> V8TestException::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp index 7feb670..58857f8 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp
@@ -137,25 +137,29 @@ {"voidMethodDocument", TestIntegerIndexedV8Internal::voidMethodDocumentMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -static void installV8TestIntegerIndexedTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestIntegerIndexedTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestIntegerIndexed::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestIntegerIndexed::internalFieldCount, - 0, 0, - V8TestIntegerIndexedAccessors, WTF_ARRAY_LENGTH(V8TestIntegerIndexedAccessors), - V8TestIntegerIndexedMethods, WTF_ARRAY_LENGTH(V8TestIntegerIndexedMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestIntegerIndexed::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestIntegerIndexed::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestIntegerIndexed::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestIntegerIndexedAccessors, WTF_ARRAY_LENGTH(V8TestIntegerIndexedAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestIntegerIndexedMethods, WTF_ARRAY_LENGTH(V8TestIntegerIndexedMethods)); + + // Array iterator if (RuntimeEnabledFeatures::iterableCollectionsEnabled()) { prototypeTemplate->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); } + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestIntegerIndexedV8Internal::indexedPropertyGetterCallback, TestIntegerIndexedV8Internal::indexedPropertySetterCallback, 0, TestIntegerIndexedV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestIntegerIndexed>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestIntegerIndexedV8Internal::namedPropertyGetterCallback, TestIntegerIndexedV8Internal::namedPropertySetterCallback, TestIntegerIndexedV8Internal::namedPropertyQueryCallback, TestIntegerIndexedV8Internal::namedPropertyDeleterCallback, TestIntegerIndexedV8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp index afa280b4..464c770 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp
@@ -137,26 +137,30 @@ {"voidMethodDocument", TestIntegerIndexedGlobalV8Internal::voidMethodDocumentMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance}, }; -static void installV8TestIntegerIndexedGlobalTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestIntegerIndexedGlobalTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestIntegerIndexedGlobal::wrapperTypeInfo.interfaceName, V8TestIntegerIndexedGlobal::domTemplateForNamedPropertiesObject(isolate), V8TestIntegerIndexedGlobal::internalFieldCount, - 0, 0, - V8TestIntegerIndexedGlobalAccessors, WTF_ARRAY_LENGTH(V8TestIntegerIndexedGlobalAccessors), - V8TestIntegerIndexedGlobalMethods, WTF_ARRAY_LENGTH(V8TestIntegerIndexedGlobalMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestIntegerIndexedGlobal::wrapperTypeInfo.interfaceName, V8TestIntegerIndexedGlobal::domTemplateForNamedPropertiesObject(isolate), V8TestIntegerIndexedGlobal::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestIntegerIndexedGlobal::wrapperTypeInfo.interfaceName); + interfaceTemplate->SetHiddenPrototype(true); + + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestIntegerIndexedGlobalAccessors, WTF_ARRAY_LENGTH(V8TestIntegerIndexedGlobalAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestIntegerIndexedGlobalMethods, WTF_ARRAY_LENGTH(V8TestIntegerIndexedGlobalMethods)); + + // Array iterator if (RuntimeEnabledFeatures::iterableCollectionsEnabled()) { instanceTemplate->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); } + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestIntegerIndexedGlobalV8Internal::indexedPropertyGetterCallback, TestIntegerIndexedGlobalV8Internal::indexedPropertySetterCallback, 0, TestIntegerIndexedGlobalV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestIntegerIndexedGlobal>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); - functionTemplate->SetHiddenPrototype(true); } v8::Local<v8::FunctionTemplate> V8TestIntegerIndexedGlobal::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp index 799e8bf..974f3de 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp
@@ -137,26 +137,30 @@ {"voidMethodDocument", TestIntegerIndexedPrimaryGlobalV8Internal::voidMethodDocumentMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance}, }; -static void installV8TestIntegerIndexedPrimaryGlobalTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestIntegerIndexedPrimaryGlobalTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestIntegerIndexedPrimaryGlobal::wrapperTypeInfo.interfaceName, V8TestIntegerIndexedPrimaryGlobal::domTemplateForNamedPropertiesObject(isolate), V8TestIntegerIndexedPrimaryGlobal::internalFieldCount, - 0, 0, - V8TestIntegerIndexedPrimaryGlobalAccessors, WTF_ARRAY_LENGTH(V8TestIntegerIndexedPrimaryGlobalAccessors), - V8TestIntegerIndexedPrimaryGlobalMethods, WTF_ARRAY_LENGTH(V8TestIntegerIndexedPrimaryGlobalMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestIntegerIndexedPrimaryGlobal::wrapperTypeInfo.interfaceName, V8TestIntegerIndexedPrimaryGlobal::domTemplateForNamedPropertiesObject(isolate), V8TestIntegerIndexedPrimaryGlobal::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestIntegerIndexedPrimaryGlobal::wrapperTypeInfo.interfaceName); + interfaceTemplate->SetHiddenPrototype(true); + + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestIntegerIndexedPrimaryGlobalAccessors, WTF_ARRAY_LENGTH(V8TestIntegerIndexedPrimaryGlobalAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestIntegerIndexedPrimaryGlobalMethods, WTF_ARRAY_LENGTH(V8TestIntegerIndexedPrimaryGlobalMethods)); + + // Array iterator if (RuntimeEnabledFeatures::iterableCollectionsEnabled()) { instanceTemplate->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); } + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestIntegerIndexedPrimaryGlobalV8Internal::indexedPropertyGetterCallback, TestIntegerIndexedPrimaryGlobalV8Internal::indexedPropertySetterCallback, 0, TestIntegerIndexedPrimaryGlobalV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestIntegerIndexedPrimaryGlobal>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); - functionTemplate->SetHiddenPrototype(true); } v8::Local<v8::FunctionTemplate> V8TestIntegerIndexedPrimaryGlobal::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp index 626f824f..810b29a 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp
@@ -3044,63 +3044,17 @@ {"toString", TestInterfaceImplementationV8Internal::toStringMethodCallback, 0, 0, static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -void V8TestInterface::installV8TestInterfaceTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +void V8TestInterface::installV8TestInterfaceTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterface::wrapperTypeInfo.interfaceName, V8TestInterfaceEmpty::domTemplate(isolate), V8TestInterface::internalFieldCount, - V8TestInterfaceAttributes, WTF_ARRAY_LENGTH(V8TestInterfaceAttributes), - V8TestInterfaceAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceAccessors), - V8TestInterfaceMethods, WTF_ARRAY_LENGTH(V8TestInterfaceMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterface::wrapperTypeInfo.interfaceName, V8TestInterfaceEmpty::domTemplate(isolate), V8TestInterface::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterface::wrapperTypeInfo.interfaceName); - ExecutionContext* context = currentExecutionContext(isolate); - ALLOW_UNUSED_LOCAL(context); - if (RuntimeEnabledFeatures::featureNameEnabled()) { - const V8DOMConfiguration::AccessorConfiguration accessorconditionalReadOnlyLongAttributeConfiguration = \ - {"conditionalReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::conditionalReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorconditionalReadOnlyLongAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorstaticConditionalReadOnlyLongAttributeConfiguration = \ - {"staticConditionalReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::staticConditionalReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorstaticConditionalReadOnlyLongAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorconditionalLongAttributeConfiguration = \ - {"conditionalLongAttribute", TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorconditionalLongAttributeConfiguration); - } - if (RuntimeEnabledFeatures::implements2FeatureNameEnabled()) { - const V8DOMConfiguration::AccessorConfiguration accessorimplements2StaticStringAttributeConfiguration = \ - {"implements2StaticStringAttribute", TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorimplements2StaticStringAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorimplements2StringAttributeConfiguration = \ - {"implements2StringAttribute", TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorimplements2StringAttributeConfiguration); - } - if (RuntimeEnabledFeatures::implementsFeatureNameEnabled()) { - const V8DOMConfiguration::AccessorConfiguration accessorimplementsRuntimeEnabledNodeAttributeConfiguration = \ - {"implementsRuntimeEnabledNodeAttribute", TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorimplementsRuntimeEnabledNodeAttributeConfiguration); - } - if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { - const V8DOMConfiguration::AccessorConfiguration accessorpartialPartialEnumTypeAttributeConfiguration = \ - {"partialPartialEnumTypeAttribute", TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorpartialPartialEnumTypeAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorpartialCallWithExecutionContextLongAttributeConfiguration = \ - {"partialCallWithExecutionContextLongAttribute", TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorpartialCallWithExecutionContextLongAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorpartialLongAttributeConfiguration = \ - {"partialLongAttribute", TestInterfaceImplementationV8Internal::partialLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorpartialLongAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorpartialStaticLongAttributeConfiguration = \ - {"partialStaticLongAttribute", TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorpartialStaticLongAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorstringAttributeConfiguration = \ - {"stringAttribute", TestInterfaceImplementationV8Internal::stringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::stringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorstringAttributeConfiguration); - } + // Register DOM constants, attributes and operations. const V8DOMConfiguration::ConstantConfiguration V8TestInterfaceConstants[] = { {"UNSIGNED_LONG", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedLong}, {"CONST_JAVASCRIPT", 1, 0, V8DOMConfiguration::ConstantTypeShort}, @@ -3108,47 +3062,102 @@ {"IMPLEMENTS_CONSTANT_2", 2, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"PARTIAL2_UNSIGNED_SHORT", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, }; - V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8TestInterfaceConstants, WTF_ARRAY_LENGTH(V8TestInterfaceConstants)); + V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestInterfaceConstants, WTF_ARRAY_LENGTH(V8TestInterfaceConstants)); if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::ConstantConfiguration constantPartialUnsignedShortConfiguration = {"PARTIAL_UNSIGNED_SHORT", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantPartialUnsignedShortConfiguration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantPartialUnsignedShortConfiguration); const V8DOMConfiguration::ConstantConfiguration constantPartialDoubleConfiguration = {"PARTIAL_DOUBLE", 0, 3.14, V8DOMConfiguration::ConstantTypeDouble}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantPartialDoubleConfiguration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantPartialDoubleConfiguration); } + V8DOMConfiguration::installAttributes(isolate, instanceTemplate, prototypeTemplate, V8TestInterfaceAttributes, WTF_ARRAY_LENGTH(V8TestInterfaceAttributes)); + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceMethods, WTF_ARRAY_LENGTH(V8TestInterfaceMethods)); + + if (RuntimeEnabledFeatures::featureNameEnabled()) { + const V8DOMConfiguration::AccessorConfiguration accessorconditionalReadOnlyLongAttributeConfiguration = \ + {"conditionalReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::conditionalReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorconditionalReadOnlyLongAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorstaticConditionalReadOnlyLongAttributeConfiguration = \ + {"staticConditionalReadOnlyLongAttribute", TestInterfaceImplementationV8Internal::staticConditionalReadOnlyLongAttributeAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorstaticConditionalReadOnlyLongAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorconditionalLongAttributeConfiguration = \ + {"conditionalLongAttribute", TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::conditionalLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorconditionalLongAttributeConfiguration); + } + + if (RuntimeEnabledFeatures::implements2FeatureNameEnabled()) { + const V8DOMConfiguration::AccessorConfiguration accessorimplements2StaticStringAttributeConfiguration = \ + {"implements2StaticStringAttribute", TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements2StaticStringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorimplements2StaticStringAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorimplements2StringAttributeConfiguration = \ + {"implements2StringAttribute", TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implements2StringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorimplements2StringAttributeConfiguration); + } + + if (RuntimeEnabledFeatures::implementsFeatureNameEnabled()) { + const V8DOMConfiguration::AccessorConfiguration accessorimplementsRuntimeEnabledNodeAttributeConfiguration = \ + {"implementsRuntimeEnabledNodeAttribute", TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::implementsRuntimeEnabledNodeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorimplementsRuntimeEnabledNodeAttributeConfiguration); + } + + if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { + const V8DOMConfiguration::AccessorConfiguration accessorpartialPartialEnumTypeAttributeConfiguration = \ + {"partialPartialEnumTypeAttribute", TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialPartialEnumTypeAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialPartialEnumTypeAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorpartialCallWithExecutionContextLongAttributeConfiguration = \ + {"partialCallWithExecutionContextLongAttribute", TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialCallWithExecutionContextLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialCallWithExecutionContextLongAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorpartialLongAttributeConfiguration = \ + {"partialLongAttribute", TestInterfaceImplementationV8Internal::partialLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialLongAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorpartialStaticLongAttributeConfiguration = \ + {"partialStaticLongAttribute", TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::partialStaticLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorpartialStaticLongAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorstringAttributeConfiguration = \ + {"stringAttribute", TestInterfaceImplementationV8Internal::stringAttributeAttributeGetterCallback, TestInterfaceImplementationV8Internal::stringAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorstringAttributeConfiguration); + } + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestInterfaceImplementationV8Internal::indexedPropertyGetterCallback, TestInterfaceImplementationV8Internal::indexedPropertySetterCallback, 0, TestInterfaceImplementationV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestInterfaceImplementation>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kAllCanRead); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestInterfaceImplementationV8Internal::namedPropertyGetterCallback, TestInterfaceImplementationV8Internal::namedPropertySetterCallback, TestInterfaceImplementationV8Internal::namedPropertyQueryCallback, TestInterfaceImplementationV8Internal::namedPropertyDeleterCallback, TestInterfaceImplementationV8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kAllCanRead) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); + + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestInterfaceImplementationV8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); - functionTemplate->InstanceTemplate()->SetCallAsFunctionHandler(V8TestInterface::legacyCallCustom); + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); + + instanceTemplate->SetCallAsFunctionHandler(V8TestInterface::legacyCallCustom); + if (RuntimeEnabledFeatures::implements2FeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration implements2VoidMethodMethodConfiguration = {"implements2VoidMethod", TestInterfaceImplementationV8Internal::implements2VoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, implements2VoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, implements2VoidMethodMethodConfiguration); } if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration partialVoidMethodMethodConfiguration = {"partialVoidMethod", TestInterfaceImplementationV8Internal::partialVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, partialVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialVoidMethodMethodConfiguration); } if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration partialStaticVoidMethodMethodConfiguration = {"partialStaticVoidMethod", TestInterfaceImplementationV8Internal::partialStaticVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInterface}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, partialStaticVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialStaticVoidMethodMethodConfiguration); } if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration partialVoidMethodLongArgMethodConfiguration = {"partialVoidMethodLongArg", TestInterfaceImplementationV8Internal::partialVoidMethodLongArgMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, partialVoidMethodLongArgMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialVoidMethodLongArgMethodConfiguration); } if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration partialCallWithExecutionContextRaisesExceptionVoidMethodMethodConfiguration = {"partialCallWithExecutionContextRaisesExceptionVoidMethod", TestInterfaceImplementationV8Internal::partialCallWithExecutionContextRaisesExceptionVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, partialCallWithExecutionContextRaisesExceptionVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialCallWithExecutionContextRaisesExceptionVoidMethodMethodConfiguration); } if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration partialVoidMethodPartialCallbackTypeArgMethodConfiguration = {"partialVoidMethodPartialCallbackTypeArg", TestInterfaceImplementationV8Internal::partialVoidMethodPartialCallbackTypeArgMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, partialVoidMethodPartialCallbackTypeArgMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partialVoidMethodPartialCallbackTypeArgMethodConfiguration); } if (RuntimeEnabledFeatures::partialFeatureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration shortMethodWithShortArgumentImplementedInPrivateScriptMethodConfiguration = {"shortMethodWithShortArgumentImplementedInPrivateScript", TestInterfaceImplementationV8Internal::shortMethodWithShortArgumentImplementedInPrivateScriptMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, shortMethodWithShortArgumentImplementedInPrivateScriptMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, shortMethodWithShortArgumentImplementedInPrivateScriptMethodConfiguration); } }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp index a543415..bcd57c4f 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp
@@ -595,33 +595,36 @@ TestInterface2V8Internal::constructor(info); } -static void installV8TestInterface2Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterface2Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterface2::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterface2::internalFieldCount, - 0, 0, - 0, 0, - V8TestInterface2Methods, WTF_ARRAY_LENGTH(V8TestInterface2Methods)); - functionTemplate->SetCallHandler(V8TestInterface2::constructorCallback); - functionTemplate->SetLength(0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterface2::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterface2::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterface2::constructorCallback); + interfaceTemplate->SetLength(0); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterface2::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::ConstantConfiguration constantConstValue1Configuration = {"CONST_VALUE_1", 1, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantConstValue1Configuration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantConstValue1Configuration); } static_assert(1 == TestInterface2::CONST_VALUE_1, "the value of TestInterface2_CONST_VALUE_1 does not match with implementation"); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterface2Methods, WTF_ARRAY_LENGTH(V8TestInterface2Methods)); + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestInterface2V8Internal::indexedPropertyGetterCallback, TestInterface2V8Internal::indexedPropertySetterCallback, 0, TestInterface2V8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestInterface2>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestInterface2V8Internal::namedPropertyGetterCallback, TestInterface2V8Internal::namedPropertySetterCallback, TestInterface2V8Internal::namedPropertyQueryCallback, TestInterface2V8Internal::namedPropertyDeleterCallback, TestInterface2V8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); + + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestInterface2V8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); } v8::Local<v8::FunctionTemplate> V8TestInterface2::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp index fb5b337..f943789 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp
@@ -213,45 +213,47 @@ {"voidMethodDocument", TestInterface3V8Internal::voidMethodDocumentMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -static void installV8TestInterface3Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterface3Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterface3::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterface3::internalFieldCount, - 0, 0, - 0, 0, - V8TestInterface3Methods, WTF_ARRAY_LENGTH(V8TestInterface3Methods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterface3::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterface3::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterface3::wrapperTypeInfo.interfaceName); - ExecutionContext* context = currentExecutionContext(isolate); - ALLOW_UNUSED_LOCAL(context); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterface3Methods, WTF_ARRAY_LENGTH(V8TestInterface3Methods)); + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestInterface3V8Internal::indexedPropertyGetterCallback, TestInterface3V8Internal::indexedPropertySetterCallback, 0, TestInterface3V8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestInterface3>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestInterface3V8Internal::namedPropertyGetterCallback, TestInterface3V8Internal::namedPropertySetterCallback, TestInterface3V8Internal::namedPropertyQueryCallback, TestInterface3V8Internal::namedPropertyDeleterCallback, TestInterface3V8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); + if (RuntimeEnabledFeatures::featureNameEnabled()) { + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestInterface3V8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); } + if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration keysMethodConfiguration = {"keys", TestInterface3V8Internal::keysMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, keysMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, keysMethodConfiguration); } if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration valuesMethodConfiguration = {"values", TestInterface3V8Internal::valuesMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, valuesMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, valuesMethodConfiguration); } if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration entriesMethodConfiguration = {"entries", TestInterface3V8Internal::entriesMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, entriesMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, entriesMethodConfiguration); } if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration forEachMethodConfiguration = {"forEach", TestInterface3V8Internal::forEachMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, forEachMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, forEachMethodConfiguration); } }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp index b9549c8..94cac65 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp
@@ -479,23 +479,25 @@ {"voidMethod", TestInterfaceCheckSecurityV8Internal::voidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance}, }; -static void installV8TestInterfaceCheckSecurityTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceCheckSecurityTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceCheckSecurity::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceCheckSecurity::internalFieldCount, - 0, 0, - V8TestInterfaceCheckSecurityAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceCheckSecurityAccessors), - V8TestInterfaceCheckSecurityMethods, WTF_ARRAY_LENGTH(V8TestInterfaceCheckSecurityMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceCheckSecurity::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceCheckSecurity::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceCheckSecurity::wrapperTypeInfo.interfaceName); - ExecutionContext* context = currentExecutionContext(isolate); - ALLOW_UNUSED_LOCAL(context); + interfaceTemplate->SetHiddenPrototype(true); + + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceCheckSecurityAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceCheckSecurityAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceCheckSecurityMethods, WTF_ARRAY_LENGTH(V8TestInterfaceCheckSecurityMethods)); + + // Cross-origin access check instanceTemplate->SetAccessCheckCallback(TestInterfaceCheckSecurityV8Internal::securityCheck, v8::External::New(isolate, const_cast<WrapperTypeInfo*>(&V8TestInterfaceCheckSecurity::wrapperTypeInfo))); + const V8DOMConfiguration::AttributeConfiguration doNotCheckSecurityVoidMethodOriginSafeAttributeConfiguration = { "doNotCheckSecurityVoidMethod", TestInterfaceCheckSecurityV8Internal::doNotCheckSecurityVoidMethodOriginSafeMethodGetterCallback, TestInterfaceCheckSecurityV8Internal::TestInterfaceCheckSecurityOriginSafeMethodSetterCallback, 0, 0, &V8TestInterfaceCheckSecurity::wrapperTypeInfo, v8::ALL_CAN_READ, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder, }; @@ -512,7 +514,6 @@ "doNotCheckSecurityUnforgeableVoidMethod", TestInterfaceCheckSecurityV8Internal::doNotCheckSecurityUnforgeableVoidMethodOriginSafeMethodGetterCallback, 0, 0, 0, &V8TestInterfaceCheckSecurity::wrapperTypeInfo, v8::ALL_CAN_READ, static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder, }; V8DOMConfiguration::installAttribute(isolate, instanceTemplate, prototypeTemplate, doNotCheckSecurityUnforgeableVoidMethodOriginSafeAttributeConfiguration); - functionTemplate->SetHiddenPrototype(true); } v8::Local<v8::FunctionTemplate> V8TestInterfaceCheckSecurity::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp index 2687e99..021ed0e4 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp
@@ -367,22 +367,20 @@ TestInterfaceConstructorV8Internal::constructor(info); } -static void installV8TestInterfaceConstructorTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceConstructorTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - functionTemplate->SetCallHandler(V8TestInterfaceConstructor::constructorCallback); - functionTemplate->SetLength(0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceConstructor::constructorCallback); + interfaceTemplate->SetLength(0); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceConstructor::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructor::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp index 91d367a..5b669ff2 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp
@@ -219,22 +219,20 @@ TestInterfaceConstructor2V8Internal::constructor(info); } -static void installV8TestInterfaceConstructor2Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceConstructor2Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceConstructor2::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor2::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - functionTemplate->SetCallHandler(V8TestInterfaceConstructor2::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceConstructor2::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor2::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceConstructor2::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceConstructor2::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructor2::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp index 235cf26..f45b1a56 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp
@@ -69,22 +69,20 @@ TestInterfaceConstructor3V8Internal::constructor(info); } -static void installV8TestInterfaceConstructor3Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceConstructor3Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceConstructor3::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor3::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - functionTemplate->SetCallHandler(V8TestInterfaceConstructor3::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceConstructor3::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor3::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceConstructor3::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceConstructor3::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructor3::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp index 950490d0..a344850f 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp
@@ -106,22 +106,20 @@ TestInterfaceConstructor4V8Internal::constructor(info); } -static void installV8TestInterfaceConstructor4Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceConstructor4Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceConstructor4::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor4::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - functionTemplate->SetCallHandler(V8TestInterfaceConstructor4::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceConstructor4::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor4::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceConstructor4::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceConstructor4::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructor4::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp index f2e3df6e..b8edd8c 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp
@@ -51,22 +51,20 @@ V8TestInterfaceCustomConstructor::constructorCustom(info); } -static void installV8TestInterfaceCustomConstructorTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceCustomConstructorTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceCustomConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceCustomConstructor::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - functionTemplate->SetCallHandler(V8TestInterfaceCustomConstructor::constructorCallback); - functionTemplate->SetLength(0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceCustomConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceCustomConstructor::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceCustomConstructor::constructorCallback); + interfaceTemplate->SetLength(0); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceCustomConstructor::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceCustomConstructor::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp index 88ad514..c951873 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp
@@ -76,20 +76,18 @@ {"location", TestInterfaceDocumentV8Internal::locationAttributeGetterCallback, TestInterfaceDocumentV8Internal::locationAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::DontDelete), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder}, }; -static void installV8TestInterfaceDocumentTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceDocumentTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceDocument::wrapperTypeInfo.interfaceName, V8Document::domTemplate(isolate), V8TestInterfaceDocument::internalFieldCount, - 0, 0, - V8TestInterfaceDocumentAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceDocumentAccessors), - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceDocument::wrapperTypeInfo.interfaceName, V8Document::domTemplate(isolate), V8TestInterfaceDocument::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceDocument::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceDocumentAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceDocumentAccessors)); } v8::Local<v8::FunctionTemplate> V8TestInterfaceDocument::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp index 2073f38..7b4856b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp
@@ -35,20 +35,18 @@ } // namespace TestInterfaceEmptyV8Internal -static void installV8TestInterfaceEmptyTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceEmptyTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceEmpty::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceEmpty::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceEmpty::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceEmpty::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceEmpty::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceEmpty::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp index 0c34416..86af197 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp
@@ -110,26 +110,25 @@ TestInterfaceEventInitConstructorV8Internal::constructor(info); } -static void installV8TestInterfaceEventInitConstructorTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceEventInitConstructorTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceEventInitConstructor::wrapperTypeInfo.interfaceName, V8Event::domTemplate(isolate), V8TestInterfaceEventInitConstructor::internalFieldCount, - 0, 0, - V8TestInterfaceEventInitConstructorAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceEventInitConstructorAccessors), - 0, 0); - functionTemplate->SetCallHandler(V8TestInterfaceEventInitConstructor::constructorCallback); - functionTemplate->SetLength(2); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceEventInitConstructor::wrapperTypeInfo.interfaceName, V8Event::domTemplate(isolate), V8TestInterfaceEventInitConstructor::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceEventInitConstructor::constructorCallback); + interfaceTemplate->SetLength(2); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceEventInitConstructor::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceEventInitConstructorAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceEventInitConstructorAccessors)); + if (RuntimeEnabledFeatures::trustedEventsEnabled()) { const V8DOMConfiguration::AccessorConfiguration accessorisTrustedConfiguration = \ {"isTrusted", TestInterfaceEventInitConstructorV8Internal::isTrustedAttributeGetterCallback, 0, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::DontDelete), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorisTrustedConfiguration); + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorisTrustedConfiguration); } }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp index 2d050ed..e6db392c 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp
@@ -82,20 +82,18 @@ return result; } -static void installV8TestInterfaceEventTargetTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceEventTargetTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceEventTarget::wrapperTypeInfo.interfaceName, V8EventTarget::domTemplate(isolate), V8TestInterfaceEventTarget::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceEventTarget::wrapperTypeInfo.interfaceName, V8EventTarget::domTemplate(isolate), V8TestInterfaceEventTarget::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceEventTarget::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceEventTarget::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp index 3d6fd9fd..aea4e8da 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp
@@ -353,24 +353,25 @@ TestInterfaceGarbageCollectedV8Internal::constructor(info); } -static void installV8TestInterfaceGarbageCollectedTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceGarbageCollectedTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceGarbageCollected::wrapperTypeInfo.interfaceName, V8EventTarget::domTemplate(isolate), V8TestInterfaceGarbageCollected::internalFieldCount, - 0, 0, - V8TestInterfaceGarbageCollectedAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceGarbageCollectedAccessors), - V8TestInterfaceGarbageCollectedMethods, WTF_ARRAY_LENGTH(V8TestInterfaceGarbageCollectedMethods)); - functionTemplate->SetCallHandler(V8TestInterfaceGarbageCollected::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceGarbageCollected::wrapperTypeInfo.interfaceName, V8EventTarget::domTemplate(isolate), V8TestInterfaceGarbageCollected::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceGarbageCollected::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceGarbageCollected::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceGarbageCollectedAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceGarbageCollectedAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceGarbageCollectedMethods, WTF_ARRAY_LENGTH(V8TestInterfaceGarbageCollectedMethods)); + + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestInterfaceGarbageCollectedV8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); } v8::Local<v8::FunctionTemplate> V8TestInterfaceGarbageCollected::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp index c3b22754..b999817 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp
@@ -171,20 +171,18 @@ return result; } -static void installV8TestInterfaceNamedConstructorTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceNamedConstructorTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceNamedConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceNamedConstructor::internalFieldCount, - V8TestInterfaceNamedConstructorAttributes, WTF_ARRAY_LENGTH(V8TestInterfaceNamedConstructorAttributes), - 0, 0, - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceNamedConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceNamedConstructor::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceNamedConstructor::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAttributes(isolate, instanceTemplate, prototypeTemplate, V8TestInterfaceNamedConstructorAttributes, WTF_ARRAY_LENGTH(V8TestInterfaceNamedConstructorAttributes)); } v8::Local<v8::FunctionTemplate> V8TestInterfaceNamedConstructor::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp index 9de5af0..762dc78b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp
@@ -91,20 +91,18 @@ return result; } -static void installV8TestInterfaceNamedConstructor2Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceNamedConstructor2Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceNamedConstructor2::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceNamedConstructor2::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceNamedConstructor2::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceNamedConstructor2::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceNamedConstructor2::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + } v8::Local<v8::FunctionTemplate> V8TestInterfaceNamedConstructor2::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp index 7050062..330fc20c 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp
@@ -321,20 +321,19 @@ {"perWorldBindingsTestInterfaceEmptyMethodOptionalBooleanArg", TestInterfaceNodeV8Internal::perWorldBindingsTestInterfaceEmptyMethodOptionalBooleanArgMethodCallback, TestInterfaceNodeV8Internal::perWorldBindingsTestInterfaceEmptyMethodOptionalBooleanArgMethodCallbackForMainWorld, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -static void installV8TestInterfaceNodeTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceNodeTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceNode::wrapperTypeInfo.interfaceName, V8Node::domTemplate(isolate), V8TestInterfaceNode::internalFieldCount, - 0, 0, - V8TestInterfaceNodeAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceNodeAccessors), - V8TestInterfaceNodeMethods, WTF_ARRAY_LENGTH(V8TestInterfaceNodeMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceNode::wrapperTypeInfo.interfaceName, V8Node::domTemplate(isolate), V8TestInterfaceNode::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceNode::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceNodeAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceNodeAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceNodeMethods, WTF_ARRAY_LENGTH(V8TestInterfaceNodeMethods)); } v8::Local<v8::FunctionTemplate> V8TestInterfaceNode::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceWillBeGarbageCollected.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceWillBeGarbageCollected.cpp index 3c4b2c5..7edaa83e 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceWillBeGarbageCollected.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceWillBeGarbageCollected.cpp
@@ -188,22 +188,21 @@ TestInterfaceWillBeGarbageCollectedV8Internal::constructor(info); } -static void installV8TestInterfaceWillBeGarbageCollectedTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterfaceWillBeGarbageCollectedTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterfaceWillBeGarbageCollected::wrapperTypeInfo.interfaceName, V8EventTarget::domTemplate(isolate), V8TestInterfaceWillBeGarbageCollected::internalFieldCount, - 0, 0, - V8TestInterfaceWillBeGarbageCollectedAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceWillBeGarbageCollectedAccessors), - V8TestInterfaceWillBeGarbageCollectedMethods, WTF_ARRAY_LENGTH(V8TestInterfaceWillBeGarbageCollectedMethods)); - functionTemplate->SetCallHandler(V8TestInterfaceWillBeGarbageCollected::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceWillBeGarbageCollected::wrapperTypeInfo.interfaceName, V8EventTarget::domTemplate(isolate), V8TestInterfaceWillBeGarbageCollected::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestInterfaceWillBeGarbageCollected::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterfaceWillBeGarbageCollected::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceWillBeGarbageCollectedAccessors, WTF_ARRAY_LENGTH(V8TestInterfaceWillBeGarbageCollectedAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceWillBeGarbageCollectedMethods, WTF_ARRAY_LENGTH(V8TestInterfaceWillBeGarbageCollectedMethods)); } v8::Local<v8::FunctionTemplate> V8TestInterfaceWillBeGarbageCollected::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp index 8ba06ed..1d75158 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp
@@ -182,22 +182,20 @@ TestNodeV8Internal::constructor(info); } -static void installV8TestNodeTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestNodeTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestNode::wrapperTypeInfo.interfaceName, V8Node::domTemplate(isolate), V8TestNode::internalFieldCount, - 0, 0, - V8TestNodeAccessors, WTF_ARRAY_LENGTH(V8TestNodeAccessors), - 0, 0); - functionTemplate->SetCallHandler(V8TestNode::constructorCallback); - functionTemplate->SetLength(0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestNode::wrapperTypeInfo.interfaceName, V8Node::domTemplate(isolate), V8TestNode::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestNode::constructorCallback); + interfaceTemplate->SetLength(0); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestNode::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestNodeAccessors, WTF_ARRAY_LENGTH(V8TestNodeAccessors)); } v8::Local<v8::FunctionTemplate> V8TestNode::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp index 6095ced..8e79a8e 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp
@@ -12008,30 +12008,17 @@ {"toString", TestObjectV8Internal::toStringMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -static void installV8TestObjectTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestObjectTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestObject::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestObject::internalFieldCount, - V8TestObjectAttributes, WTF_ARRAY_LENGTH(V8TestObjectAttributes), - V8TestObjectAccessors, WTF_ARRAY_LENGTH(V8TestObjectAccessors), - V8TestObjectMethods, WTF_ARRAY_LENGTH(V8TestObjectMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestObject::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestObject::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestObject::wrapperTypeInfo.interfaceName); - ExecutionContext* context = currentExecutionContext(isolate); - ALLOW_UNUSED_LOCAL(context); - if (RuntimeEnabledFeatures::featureNameEnabled()) { - const V8DOMConfiguration::AccessorConfiguration accessorruntimeEnabledLongAttributeConfiguration = \ - {"runtimeEnabledLongAttribute", TestObjectV8Internal::runtimeEnabledLongAttributeAttributeGetterCallback, TestObjectV8Internal::runtimeEnabledLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorruntimeEnabledLongAttributeConfiguration); - const V8DOMConfiguration::AccessorConfiguration accessorunscopeableRuntimeEnabledLongAttributeConfiguration = \ - {"unscopeableRuntimeEnabledLongAttribute", TestObjectV8Internal::unscopeableRuntimeEnabledLongAttributeAttributeGetterCallback, TestObjectV8Internal::unscopeableRuntimeEnabledLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; - V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, accessorunscopeableRuntimeEnabledLongAttributeConfiguration); - } + // Register DOM constants, attributes and operations. const V8DOMConfiguration::ConstantConfiguration V8TestObjectConstants[] = { {"CONST_VALUE_0", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"CONST_VALUE_1", 1, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, @@ -12057,30 +12044,30 @@ {"CONST_VALUE_25", 0, 1, V8DOMConfiguration::ConstantTypeFloat}, {"CONST_JAVASCRIPT", 1, 0, V8DOMConfiguration::ConstantTypeShort}, }; - V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8TestObjectConstants, WTF_ARRAY_LENGTH(V8TestObjectConstants)); + V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestObjectConstants, WTF_ARRAY_LENGTH(V8TestObjectConstants)); if (RuntimeEnabledFeatures::featureName1Enabled()) { const V8DOMConfiguration::ConstantConfiguration constantFeature1EnabledConst1Configuration = {"FEATURE1_ENABLED_CONST1", 1, 0, V8DOMConfiguration::ConstantTypeShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantFeature1EnabledConst1Configuration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantFeature1EnabledConst1Configuration); const V8DOMConfiguration::ConstantConfiguration constantFeature1EnabledConst2Configuration = {"FEATURE1_ENABLED_CONST2", 2, 0, V8DOMConfiguration::ConstantTypeShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantFeature1EnabledConst2Configuration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantFeature1EnabledConst2Configuration); } if (RuntimeEnabledFeatures::featureName2Enabled()) { const V8DOMConfiguration::ConstantConfiguration constantFeature2EnabledConst1Configuration = {"FEATURE2_ENABLED_CONST1", 3, 0, V8DOMConfiguration::ConstantTypeShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantFeature2EnabledConst1Configuration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantFeature2EnabledConst1Configuration); const V8DOMConfiguration::ConstantConfiguration constantFeature2EnabledConst2Configuration = {"FEATURE2_ENABLED_CONST2", 4, 0, V8DOMConfiguration::ConstantTypeShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantFeature2EnabledConst2Configuration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantFeature2EnabledConst2Configuration); } if (RuntimeEnabledFeatures::featureName3Enabled()) { const V8DOMConfiguration::ConstantConfiguration constantFeature3EnabledConst1Configuration = {"FEATURE3_ENABLED_CONST1", 5, 0, V8DOMConfiguration::ConstantTypeShort}; - V8DOMConfiguration::installConstant(isolate, functionTemplate, prototypeTemplate, constantFeature3EnabledConst1Configuration); + V8DOMConfiguration::installConstant(isolate, interfaceTemplate, prototypeTemplate, constantFeature3EnabledConst1Configuration); } - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "DEPRECATED_CONSTANT", TestObjectV8Internal::DEPRECATED_CONSTANTConstantGetterCallback); - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "MEASURED_CONSTANT", TestObjectV8Internal::MEASURED_CONSTANTConstantGetterCallback); - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1", TestObjectV8Internal::FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1ConstantGetterCallback); - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2", TestObjectV8Internal::FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2ConstantGetterCallback); - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1", TestObjectV8Internal::FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1ConstantGetterCallback); - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2", TestObjectV8Internal::FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2ConstantGetterCallback); - V8DOMConfiguration::installConstantWithGetter(isolate, functionTemplate, prototypeTemplate, "FEATURE3_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1", TestObjectV8Internal::FEATURE3_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1ConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "DEPRECATED_CONSTANT", TestObjectV8Internal::DEPRECATED_CONSTANTConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "MEASURED_CONSTANT", TestObjectV8Internal::MEASURED_CONSTANTConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1", TestObjectV8Internal::FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1ConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2", TestObjectV8Internal::FEATURE1_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2ConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1", TestObjectV8Internal::FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1ConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2", TestObjectV8Internal::FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2ConstantGetterCallback); + V8DOMConfiguration::installConstantWithGetter(isolate, interfaceTemplate, prototypeTemplate, "FEATURE3_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1", TestObjectV8Internal::FEATURE3_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1ConstantGetterCallback); static_assert(0 == TestObject::CONST_VALUE_0, "the value of TestObject_CONST_VALUE_0 does not match with implementation"); static_assert(1 == TestObject::CONST_VALUE_1, "the value of TestObject_CONST_VALUE_1 does not match with implementation"); static_assert(2 == TestObject::CONST_VALUE_2, "the value of TestObject_CONST_VALUE_2 does not match with implementation"); @@ -12108,32 +12095,50 @@ static_assert(4 == TestObject::FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2, "the value of TestObject_FEATURE2_RUNTIME_AND_EXPERIMENT_ENABLED_CONST2 does not match with implementation"); static_assert(5 == TestObject::FEATURE3_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1, "the value of TestObject_FEATURE3_RUNTIME_AND_EXPERIMENT_ENABLED_CONST1 does not match with implementation"); static_assert(1 == TestObject::CONST_IMPL, "the value of TestObject_CONST_IMPL does not match with implementation"); + V8DOMConfiguration::installAttributes(isolate, instanceTemplate, prototypeTemplate, V8TestObjectAttributes, WTF_ARRAY_LENGTH(V8TestObjectAttributes)); + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestObjectAccessors, WTF_ARRAY_LENGTH(V8TestObjectAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestObjectMethods, WTF_ARRAY_LENGTH(V8TestObjectMethods)); + + if (RuntimeEnabledFeatures::featureNameEnabled()) { + const V8DOMConfiguration::AccessorConfiguration accessorruntimeEnabledLongAttributeConfiguration = \ + {"runtimeEnabledLongAttribute", TestObjectV8Internal::runtimeEnabledLongAttributeAttributeGetterCallback, TestObjectV8Internal::runtimeEnabledLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorruntimeEnabledLongAttributeConfiguration); + const V8DOMConfiguration::AccessorConfiguration accessorunscopeableRuntimeEnabledLongAttributeConfiguration = \ + {"unscopeableRuntimeEnabledLongAttribute", TestObjectV8Internal::unscopeableRuntimeEnabledLongAttributeAttributeGetterCallback, TestObjectV8Internal::unscopeableRuntimeEnabledLongAttributeAttributeSetterCallback, 0, 0, 0, v8::DEFAULT, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}; + V8DOMConfiguration::installAccessor(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, accessorunscopeableRuntimeEnabledLongAttributeConfiguration); + } + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestObjectV8Internal::indexedPropertyGetterCallback, TestObjectV8Internal::indexedPropertySetterCallback, 0, TestObjectV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestObject>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestObjectV8Internal::namedPropertyGetterCallback, TestObjectV8Internal::namedPropertySetterCallback, TestObjectV8Internal::namedPropertyQueryCallback, TestObjectV8Internal::namedPropertyDeleterCallback, TestObjectV8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); + + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestObjectV8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); + if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration unscopeableRuntimeEnabledVoidMethodMethodConfiguration = {"unscopeableRuntimeEnabledVoidMethod", TestObjectV8Internal::unscopeableRuntimeEnabledVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, unscopeableRuntimeEnabledVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, unscopeableRuntimeEnabledVoidMethodMethodConfiguration); } const V8DOMConfiguration::MethodConfiguration doNotCheckSignatureVoidMethodMethodConfiguration = {"doNotCheckSignatureVoidMethod", TestObjectV8Internal::doNotCheckSignatureVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, v8::Local<v8::Signature>(), doNotCheckSignatureVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, v8::Local<v8::Signature>(), doNotCheckSignatureVoidMethodMethodConfiguration); if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration runtimeEnabledVoidMethodMethodConfiguration = {"runtimeEnabledVoidMethod", TestObjectV8Internal::runtimeEnabledVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, runtimeEnabledVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, runtimeEnabledVoidMethodMethodConfiguration); } if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration perWorldBindingsRuntimeEnabledVoidMethodMethodConfiguration = {"perWorldBindingsRuntimeEnabledVoidMethod", TestObjectV8Internal::perWorldBindingsRuntimeEnabledVoidMethodMethodCallback, TestObjectV8Internal::perWorldBindingsRuntimeEnabledVoidMethodMethodCallbackForMainWorld, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, perWorldBindingsRuntimeEnabledVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, perWorldBindingsRuntimeEnabledVoidMethodMethodConfiguration); } if (RuntimeEnabledFeatures::featureNameEnabled()) { const V8DOMConfiguration::MethodConfiguration runtimeEnabledOverloadedVoidMethodMethodConfiguration = {"runtimeEnabledOverloadedVoidMethod", TestObjectV8Internal::runtimeEnabledOverloadedVoidMethodMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, runtimeEnabledOverloadedVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, runtimeEnabledOverloadedVoidMethodMethodConfiguration); } const V8DOMConfiguration::MethodConfiguration partiallyRuntimeEnabledOverloadedVoidMethodMethodConfiguration = {"partiallyRuntimeEnabledOverloadedVoidMethod", TestObjectV8Internal::partiallyRuntimeEnabledOverloadedVoidMethodMethodCallback, 0, TestObjectV8Internal::partiallyRuntimeEnabledOverloadedVoidMethodMethodLength(), v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}; - V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, functionTemplate, defaultSignature, partiallyRuntimeEnabledOverloadedVoidMethodMethodConfiguration); + V8DOMConfiguration::installMethod(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, partiallyRuntimeEnabledOverloadedVoidMethodMethodConfiguration); } v8::Local<v8::FunctionTemplate> V8TestObject::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp index 4b731ac..25950e4 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp
@@ -150,20 +150,19 @@ {"namedItem", TestSpecialOperationsV8Internal::namedItemMethodCallback, 0, 1, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -static void installV8TestSpecialOperationsTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestSpecialOperationsTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestSpecialOperations::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestSpecialOperations::internalFieldCount, - 0, 0, - 0, 0, - V8TestSpecialOperationsMethods, WTF_ARRAY_LENGTH(V8TestSpecialOperationsMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestSpecialOperations::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestSpecialOperations::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestSpecialOperations::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestSpecialOperationsMethods, WTF_ARRAY_LENGTH(V8TestSpecialOperationsMethods)); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestSpecialOperationsV8Internal::namedPropertyGetterCallback, TestSpecialOperationsV8Internal::namedPropertySetterCallback, TestSpecialOperationsV8Internal::namedPropertyQueryCallback, 0, TestSpecialOperationsV8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp index fc1291e..5f0b083 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp
@@ -65,22 +65,23 @@ } // namespace TestSpecialOperationsNotEnumerableV8Internal -static void installV8TestSpecialOperationsNotEnumerableTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestSpecialOperationsNotEnumerableTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestSpecialOperationsNotEnumerable::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestSpecialOperationsNotEnumerable::internalFieldCount, - 0, 0, - 0, 0, - 0, 0); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestSpecialOperationsNotEnumerable::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestSpecialOperationsNotEnumerable::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestSpecialOperationsNotEnumerable::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestSpecialOperationsNotEnumerableV8Internal::indexedPropertyGetterCallback, 0, 0, 0, 0, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestSpecialOperationsNotEnumerableV8Internal::namedPropertyGetterCallback, 0, 0, 0, 0, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp index 55e3da1..a202ca9 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp
@@ -354,22 +354,22 @@ TestTypedefsV8Internal::constructor(info); } -static void installV8TestTypedefsTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestTypedefsTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestTypedefs::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestTypedefs::internalFieldCount, - V8TestTypedefsAttributes, WTF_ARRAY_LENGTH(V8TestTypedefsAttributes), - V8TestTypedefsAccessors, WTF_ARRAY_LENGTH(V8TestTypedefsAccessors), - V8TestTypedefsMethods, WTF_ARRAY_LENGTH(V8TestTypedefsMethods)); - functionTemplate->SetCallHandler(V8TestTypedefs::constructorCallback); - functionTemplate->SetLength(1); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestTypedefs::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestTypedefs::internalFieldCount); + interfaceTemplate->SetCallHandler(V8TestTypedefs::constructorCallback); + interfaceTemplate->SetLength(1); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestTypedefs::wrapperTypeInfo.interfaceName); + // Register DOM constants, attributes and operations. + V8DOMConfiguration::installAttributes(isolate, instanceTemplate, prototypeTemplate, V8TestTypedefsAttributes, WTF_ARRAY_LENGTH(V8TestTypedefsAttributes)); + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestTypedefsAccessors, WTF_ARRAY_LENGTH(V8TestTypedefsAccessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestTypedefsMethods, WTF_ARRAY_LENGTH(V8TestTypedefsMethods)); } v8::Local<v8::FunctionTemplate> V8TestTypedefs::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp index a046f619..867b4b2 100644 --- a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp
@@ -840,35 +840,40 @@ {"toString", TestInterface5ImplementationV8Internal::toStringMethodCallback, 0, 0, static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -static void installV8TestInterface5Template(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +static void installV8TestInterface5Template(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - functionTemplate->ReadOnlyPrototype(); - - v8::Local<v8::Signature> defaultSignature; - if (!RuntimeEnabledFeatures::featureNameEnabled()) - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterface5::wrapperTypeInfo.interfaceName, V8TestInterfaceEmpty::domTemplate(isolate), V8TestInterface5::internalFieldCount, 0, 0, 0, 0, 0, 0); - else - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterface5::wrapperTypeInfo.interfaceName, V8TestInterfaceEmpty::domTemplate(isolate), V8TestInterface5::internalFieldCount, - V8TestInterface5Attributes, WTF_ARRAY_LENGTH(V8TestInterface5Attributes), - V8TestInterface5Accessors, WTF_ARRAY_LENGTH(V8TestInterface5Accessors), - V8TestInterface5Methods, WTF_ARRAY_LENGTH(V8TestInterface5Methods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterface5::wrapperTypeInfo.interfaceName, V8TestInterfaceEmpty::domTemplate(isolate), V8TestInterface5::internalFieldCount); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); - V8DOMConfiguration::setClassString(isolate, prototypeTemplate, V8TestInterface5::wrapperTypeInfo.interfaceName); - const V8DOMConfiguration::ConstantConfiguration V8TestInterface5Constants[] = { - {"UNSIGNED_LONG", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedLong}, - {"CONST_JAVASCRIPT", 1, 0, V8DOMConfiguration::ConstantTypeShort}, - }; - V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8TestInterface5Constants, WTF_ARRAY_LENGTH(V8TestInterface5Constants)); + // Register DOM constants, attributes and operations. + if (RuntimeEnabledFeatures::featureNameEnabled()) { + const V8DOMConfiguration::ConstantConfiguration V8TestInterface5Constants[] = { + {"UNSIGNED_LONG", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedLong}, + {"CONST_JAVASCRIPT", 1, 0, V8DOMConfiguration::ConstantTypeShort}, + }; + V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestInterface5Constants, WTF_ARRAY_LENGTH(V8TestInterface5Constants)); + V8DOMConfiguration::installAttributes(isolate, instanceTemplate, prototypeTemplate, V8TestInterface5Attributes, WTF_ARRAY_LENGTH(V8TestInterface5Attributes)); + V8DOMConfiguration::installAccessors(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterface5Accessors, WTF_ARRAY_LENGTH(V8TestInterface5Accessors)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterface5Methods, WTF_ARRAY_LENGTH(V8TestInterface5Methods)); + } // if (RuntimeEnabledFeatures::featureNameEnabled()) + + // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig(TestInterface5ImplementationV8Internal::indexedPropertyGetterCallback, TestInterface5ImplementationV8Internal::indexedPropertySetterCallback, 0, TestInterface5ImplementationV8Internal::indexedPropertyDeleterCallback, indexedPropertyEnumerator<TestInterface5Implementation>, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instanceTemplate->SetHandler(indexedPropertyHandlerConfig); + // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(TestInterface5ImplementationV8Internal::namedPropertyGetterCallback, TestInterface5ImplementationV8Internal::namedPropertySetterCallback, TestInterface5ImplementationV8Internal::namedPropertyQueryCallback, TestInterface5ImplementationV8Internal::namedPropertyDeleterCallback, TestInterface5ImplementationV8Internal::namedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instanceTemplate->SetHandler(namedPropertyHandlerConfig); + + // Iterator (@@iterator) const V8DOMConfiguration::SymbolKeyedMethodConfiguration symbolKeyedIteratorConfiguration = { v8::Symbol::GetIterator, TestInterface5ImplementationV8Internal::iteratorMethodCallback, 0, v8::DontDelete, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype }; - V8DOMConfiguration::installMethod(isolate, prototypeTemplate, defaultSignature, symbolKeyedIteratorConfiguration); - functionTemplate->InstanceTemplate()->SetCallAsFunctionHandler(V8TestInterface5::legacyCallCustom); + V8DOMConfiguration::installMethod(isolate, prototypeTemplate, signature, symbolKeyedIteratorConfiguration); + + instanceTemplate->SetCallAsFunctionHandler(V8TestInterface5::legacyCallCustom); } v8::Local<v8::FunctionTemplate> V8TestInterface5::domTemplate(v8::Isolate* isolate)
diff --git a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp index 1be53682..81c7f4f 100644 --- a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterfacePartial.cpp
@@ -312,24 +312,24 @@ {"unscopeableVoidMethod", TestInterfaceImplementationPartialV8Internal::unscopeableVoidMethodMethodCallback, 0, 0, v8::None, V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype}, }; -void V8TestInterfacePartial::installV8TestInterfaceTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) +void V8TestInterfacePartial::installV8TestInterfaceTemplate(v8::Local<v8::FunctionTemplate> interfaceTemplate, v8::Isolate* isolate) { - V8TestInterface::installV8TestInterfaceTemplate(functionTemplate, isolate); - - v8::Local<v8::Signature> defaultSignature; - defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, V8TestInterface::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterface::internalFieldCount, - 0, 0, - 0, 0, - V8TestInterfaceMethods, WTF_ARRAY_LENGTH(V8TestInterfaceMethods)); - v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); + // Initialize the interface object's template. + V8TestInterface::installV8TestInterfaceTemplate(interfaceTemplate, isolate); + v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate); + ALLOW_UNUSED_LOCAL(signature); + v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); - v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); + v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); + // Register DOM constants, attributes and operations. const V8DOMConfiguration::ConstantConfiguration V8TestInterfaceConstants[] = { {"PARTIAL3_UNSIGNED_SHORT", 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, }; - V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8TestInterfaceConstants, WTF_ARRAY_LENGTH(V8TestInterfaceConstants)); - functionTemplate->InstanceTemplate()->SetCallAsFunctionHandler(V8TestInterface::legacyCallCustom); + V8DOMConfiguration::installConstants(isolate, interfaceTemplate, prototypeTemplate, V8TestInterfaceConstants, WTF_ARRAY_LENGTH(V8TestInterfaceConstants)); + V8DOMConfiguration::installMethods(isolate, instanceTemplate, prototypeTemplate, interfaceTemplate, signature, V8TestInterfaceMethods, WTF_ARRAY_LENGTH(V8TestInterfaceMethods)); + + instanceTemplate->SetCallAsFunctionHandler(V8TestInterface::legacyCallCustom); } void V8TestInterfacePartial::preparePrototypeAndInterfaceObject(v8::Local<v8::Context> context, v8::Local<v8::Object> prototypeObject, v8::Local<v8::Function> interfaceObject, v8::Local<v8::FunctionTemplate> interfaceTemplate)
diff --git a/third_party/WebKit/Source/core/core.gypi b/third_party/WebKit/Source/core/core.gypi index 3cbe75ef..d26fff3 100644 --- a/third_party/WebKit/Source/core/core.gypi +++ b/third_party/WebKit/Source/core/core.gypi
@@ -2641,6 +2641,8 @@ 'dom/shadow/ShadowRootRareData.h', 'dom/shadow/SlotAssignment.cpp', 'dom/shadow/SlotAssignment.h', + 'dom/shadow/SlotScopedTraversal.cpp', + 'dom/shadow/SlotScopedTraversal.h', 'events/AnimationEvent.cpp', 'events/AnimationEvent.h', 'events/AnimationPlayerEvent.cpp', @@ -3907,6 +3909,7 @@ 'css/resolver/MatchResultTest.cpp', 'dom/ActiveDOMObjectTest.cpp', 'dom/AttrTest.cpp', + 'dom/CSSSelectorWatchTest.cpp', 'dom/CrossThreadTaskTest.cpp', 'dom/DOMImplementationTest.cpp', 'dom/DocumentStatisticsCollectorTest.cpp',
diff --git a/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h b/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h index 69efb0b3..cf2a87d 100644 --- a/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h +++ b/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h
@@ -233,34 +233,34 @@ { init(UnitType::ValueID); switch (e) { - case BNONE: + case BorderStyleNone: m_value.valueID = CSSValueNone; break; - case BHIDDEN: + case BorderStyleHidden: m_value.valueID = CSSValueHidden; break; - case INSET: + case BorderStyleInset: m_value.valueID = CSSValueInset; break; - case GROOVE: + case BorderStyleGroove: m_value.valueID = CSSValueGroove; break; - case RIDGE: + case BorderStyleRidge: m_value.valueID = CSSValueRidge; break; - case OUTSET: + case BorderStyleOutset: m_value.valueID = CSSValueOutset; break; - case DOTTED: + case BorderStyleDotted: m_value.valueID = CSSValueDotted; break; - case DASHED: + case BorderStyleDashed: m_value.valueID = CSSValueDashed; break; - case SOLID: + case BorderStyleSolid: m_value.valueID = CSSValueSolid; break; - case DOUBLE: + case BorderStyleDouble: m_value.valueID = CSSValueDouble; break; } @@ -270,15 +270,15 @@ { ASSERT(isValueID()); if (m_value.valueID == CSSValueAuto) // Valid for CSS outline-style - return DOTTED; + return BorderStyleDotted; return (EBorderStyle)(m_value.valueID - CSSValueNone); } template<> inline OutlineIsAuto CSSPrimitiveValue::convertTo() const { if (m_value.valueID == CSSValueAuto) - return AUTO_ON; - return AUTO_OFF; + return OutlineIsAutoOn; + return OutlineIsAutoOff; } template<> inline CSSPrimitiveValue::CSSPrimitiveValue(CompositeOperator e) @@ -763,10 +763,10 @@ { init(UnitType::ValueID); switch (e) { - case DSLICE: + case BoxDecorationBreakSlice: m_value.valueID = CSSValueSlice; break; - case DCLONE: + case BoxDecorationBreakClone: m_value.valueID = CSSValueClone; break; } @@ -777,15 +777,15 @@ ASSERT(isValueID()); switch (m_value.valueID) { case CSSValueSlice: - return DSLICE; + return BoxDecorationBreakSlice; case CSSValueClone: - return DCLONE; + return BoxDecorationBreakClone; default: break; } ASSERT_NOT_REACHED(); - return DSLICE; + return BoxDecorationBreakSlice; } template<> inline CSSPrimitiveValue::CSSPrimitiveValue(BackgroundEdgeOrigin e) @@ -833,10 +833,10 @@ { init(UnitType::ValueID); switch (e) { - case BORDER_BOX: + case BoxSizingBorderBox: m_value.valueID = CSSValueBorderBox; break; - case CONTENT_BOX: + case BoxSizingContentBox: m_value.valueID = CSSValueContentBox; break; } @@ -847,15 +847,15 @@ ASSERT(isValueID()); switch (m_value.valueID) { case CSSValueBorderBox: - return BORDER_BOX; + return BoxSizingBorderBox; case CSSValueContentBox: - return CONTENT_BOX; + return BoxSizingContentBox; default: break; } ASSERT_NOT_REACHED(); - return BORDER_BOX; + return BoxSizingBorderBox; } template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EBoxDirection e) @@ -1657,13 +1657,13 @@ { init(UnitType::ValueID); switch (e) { - case MCOLLAPSE: + case MarginCollapseCollapse: m_value.valueID = CSSValueCollapse; break; - case MSEPARATE: + case MarginCollapseSeparate: m_value.valueID = CSSValueSeparate; break; - case MDISCARD: + case MarginCollapseDiscard: m_value.valueID = CSSValueDiscard; break; } @@ -1674,17 +1674,17 @@ ASSERT(isValueID()); switch (m_value.valueID) { case CSSValueCollapse: - return MCOLLAPSE; + return MarginCollapseCollapse; case CSSValueSeparate: - return MSEPARATE; + return MarginCollapseSeparate; case CSSValueDiscard: - return MDISCARD; + return MarginCollapseDiscard; default: break; } ASSERT_NOT_REACHED(); - return MCOLLAPSE; + return MarginCollapseCollapse; } template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EOverflow e) @@ -3764,10 +3764,10 @@ { init(UnitType::ValueID); switch (e) { - case BSEPARATE: + case BorderCollapseSeparate: m_value.valueID = CSSValueSeparate; break; - case BCOLLAPSE: + case BorderCollapseCollapse: m_value.valueID = CSSValueCollapse; break; } @@ -3778,15 +3778,15 @@ ASSERT(isValueID()); switch (m_value.valueID) { case CSSValueSeparate: - return BSEPARATE; + return BorderCollapseSeparate; case CSSValueCollapse: - return BCOLLAPSE; + return BorderCollapseCollapse; default: break; } ASSERT_NOT_REACHED(); - return BSEPARATE; + return BorderCollapseSeparate; } template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EImageRendering e)
diff --git a/third_party/WebKit/Source/core/css/CSSValue.h b/third_party/WebKit/Source/core/css/CSSValue.h index 3b41ecd..8b52da1 100644 --- a/third_party/WebKit/Source/core/css/CSSValue.h +++ b/third_party/WebKit/Source/core/css/CSSValue.h
@@ -44,7 +44,8 @@ static void* allocateObject(size_t size, bool isEager) { ThreadState* state = ThreadStateFor<ThreadingTrait<CSSValue>::Affinity>::state(); - return Heap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::CSSValueArenaIndex, GCInfoTrait<CSSValue>::index()); + const char typeName[] = "blink::CSSValue"; + return Heap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::CSSValueArenaIndex, GCInfoTrait<CSSValue>::index(), typeName); } #else USING_FAST_MALLOC_WITH_TYPE_NAME(blink::CSSValue);
diff --git a/third_party/WebKit/Source/core/css/CSSVariableData.cpp b/third_party/WebKit/Source/core/css/CSSVariableData.cpp index 30c6d9c..7dfc352 100644 --- a/third_party/WebKit/Source/core/css/CSSVariableData.cpp +++ b/third_party/WebKit/Source/core/css/CSSVariableData.cpp
@@ -10,7 +10,7 @@ namespace blink { -const StylePropertySet* CSSVariableData::propertySet() +StylePropertySet* CSSVariableData::propertySet() { ASSERT(!m_needsVariableResolution); if (!m_cachedPropertySet) {
diff --git a/third_party/WebKit/Source/core/css/CSSVariableData.h b/third_party/WebKit/Source/core/css/CSSVariableData.h index 974a9bd..1de3837a 100644 --- a/third_party/WebKit/Source/core/css/CSSVariableData.h +++ b/third_party/WebKit/Source/core/css/CSSVariableData.h
@@ -37,7 +37,7 @@ bool needsVariableResolution() const { return m_needsVariableResolution; } - const StylePropertySet* propertySet(); + StylePropertySet* propertySet(); private: CSSVariableData(const CSSParserTokenRange&, bool needsVariableResolution);
diff --git a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp index 117e22fc..aaf667e 100644 --- a/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp +++ b/third_party/WebKit/Source/core/css/ComputedStyleCSSValueMapping.cpp
@@ -641,7 +641,7 @@ return LayoutRect(); const LayoutBox* box = toLayoutBox(layoutObject); - return box->style()->boxSizing() == BORDER_BOX ? box->borderBoxRect() : box->computedCSSContentBoxRect(); + return box->style()->boxSizing() == BoxSizingBorderBox ? box->borderBoxRect() : box->computedCSSContentBoxRect(); } static PassRefPtrWillBeRawPtr<CSSValue> renderTextDecorationFlagsToCSSValue(int textDecoration) @@ -1523,7 +1523,7 @@ case CSSPropertyWebkitBoxAlign: return cssValuePool().createValue(style.boxAlign()); case CSSPropertyWebkitBoxDecorationBreak: - if (style.boxDecorationBreak() == DSLICE) + if (style.boxDecorationBreak() == BoxDecorationBreakSlice) return cssValuePool().createIdentifierValue(CSSValueSlice); return cssValuePool().createIdentifierValue(CSSValueClone); case CSSPropertyWebkitBoxDirection: @@ -2117,7 +2117,7 @@ case CSSPropertyZoom: return cssValuePool().createValue(style.zoom(), CSSPrimitiveValue::UnitType::Number); case CSSPropertyBoxSizing: - if (style.boxSizing() == CONTENT_BOX) + if (style.boxSizing() == BoxSizingContentBox) return cssValuePool().createIdentifierValue(CSSValueContentBox); return cssValuePool().createIdentifierValue(CSSValueBorderBox); case CSSPropertyWebkitAppRegion:
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp index fb55527a9..2a43188 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
@@ -102,6 +102,34 @@ element.ensureElementAnimations().cssAnimations().setPendingUpdate(state.animationUpdate()); } +// Returns whether any @apply rule sets a custom property +bool cacheCustomPropertiesForApplyAtRules(StyleResolverState& state, const MatchedPropertiesRange& range) +{ + bool ruleSetsCustomProperty = false; + if (!state.style()->variables()) + return false; + for (const auto& matchedProperties : range) { + const StylePropertySet& properties = *matchedProperties.properties; + unsigned propertyCount = properties.propertyCount(); + for (unsigned i = 0; i < propertyCount; ++i) { + StylePropertySet::PropertyReference current = properties.propertyAt(i); + if (current.id() != CSSPropertyApplyAtRule) + continue; + AtomicString name(toCSSCustomIdentValue(current.value())->value()); + CSSVariableData* variableData = state.style()->variables()->getVariable(name); + if (!variableData) + continue; + StylePropertySet* customPropertySet = variableData->propertySet(); + if (!customPropertySet) + continue; + if (customPropertySet->findPropertyIndex(CSSPropertyVariable) != -1) + ruleSetsCustomProperty = true; + state.setCustomPropertySetForApplyAtRule(name, customPropertySet); + } + } + return ruleSetsCustomProperty; +} + } // namespace namespace blink { @@ -170,6 +198,7 @@ void StyleResolver::initWatchedSelectorRules() { + m_watchedSelectorsRules = nullptr; CSSSelectorWatch* watch = CSSSelectorWatch::fromIfExists(*m_document); if (!watch) return; @@ -1271,15 +1300,10 @@ template <CSSPropertyPriority priority> void StyleResolver::applyPropertiesForApplyAtRule(StyleResolverState& state, const CSSValue* value, bool isImportant, bool inheritedOnly, PropertyWhitelistType propertyWhitelistType) { - if (priority == ResolveVariables) - return; if (!state.style()->variables()) return; - AtomicString name(toCSSCustomIdentValue(value)->value()); - CSSVariableData* variableData = state.style()->variables()->getVariable(name); - if (!variableData) - return; - const StylePropertySet* propertySet = variableData->propertySet(); + const String& name = toCSSCustomIdentValue(value)->value(); + const StylePropertySet* propertySet = state.customPropertySetForApplyAtRule(name); if (propertySet) applyProperties<priority>(state, propertySet, isImportant, inheritedOnly, propertyWhitelistType); } @@ -1406,6 +1430,14 @@ CSSVariableResolver::resolveVariableDefinitions(state.style()->variables()); } + if (RuntimeEnabledFeatures::cssApplyAtRulesEnabled()) { + if (cacheCustomPropertiesForApplyAtRules(state, matchResult.authorRules())) { + applyMatchedProperties<ResolveVariables>(state, matchResult.authorRules(), false, applyInheritedOnly); + applyMatchedProperties<ResolveVariables>(state, matchResult.authorRules(), true, applyInheritedOnly); + CSSVariableResolver::resolveVariableDefinitions(state.style()->variables()); + } + } + // Now we have all of the matched rules in the appropriate order. Walk the rules and apply // high-priority properties first, i.e., those properties that other properties depend on. // The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolver.h b/third_party/WebKit/Source/core/css/resolver/StyleResolver.h index 14e13bb4..9976610 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolver.h +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
@@ -103,6 +103,7 @@ // https://bugs.webkit.org/show_bug.cgi?id=108890 void appendAuthorStyleSheets(const WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet>>&); void resetAuthorStyle(TreeScope&); + void resetRuleFeatures(); void finishAppendAuthorStyleSheets(); void lazyAppendAuthorStyleSheets(unsigned firstNew, const WillBeHeapVector<RefPtrWillBeMember<CSSStyleSheet>>&); @@ -174,14 +175,13 @@ DECLARE_TRACE(); void addTreeBoundaryCrossingScope(ContainerNode& scope); + void initWatchedSelectorRules(); private: explicit StyleResolver(Document&); PassRefPtr<ComputedStyle> initialStyleForElement(); - void initWatchedSelectorRules(); - // FIXME: This should probably go away, folded into FontBuilder. void updateFont(StyleResolverState&); @@ -197,7 +197,6 @@ void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool includeSMILProperties); void collectFeatures(); void collectTreeBoundaryCrossingRules(const Element&, ElementRuleCollector&); - void resetRuleFeatures(); void applyMatchedProperties(StyleResolverState&, const MatchResult&); bool applyAnimatedProperties(StyleResolverState&, const Element* animatingElement);
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp index 68279ec..4cb4c81 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp
@@ -22,6 +22,7 @@ #include "core/css/resolver/StyleResolverState.h" #include "core/animation/css/CSSAnimations.h" +#include "core/css/StylePropertySet.h" #include "core/dom/Node.h" #include "core/dom/NodeComputedStyle.h" #include "core/frame/FrameHost.h" @@ -67,4 +68,19 @@ return CSSToLengthConversionData(style(), fontSizes, viewportSize, 1); } +void StyleResolverState::loadPendingResources() +{ + m_elementStyleResources.loadPendingResources(style()); +} + +void StyleResolverState::setCustomPropertySetForApplyAtRule(const String& string, StylePropertySet* customPropertySet) +{ + m_customPropertySetsForApplyAtRule.set(string, customPropertySet); +} + +StylePropertySet* StyleResolverState::customPropertySetForApplyAtRule(const String& string) +{ + return m_customPropertySetsForApplyAtRule.get(string); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h index dec1395..fd6c844 100644 --- a/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h +++ b/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
@@ -113,6 +113,8 @@ ElementStyleResources& elementStyleResources() { return m_elementStyleResources; } + void loadPendingResources(); + // FIXME: Once styleImage can be made to not take a StyleResolverState // this convenience function should be removed. As-is, without this, call // sites are extremely verbose. @@ -154,6 +156,9 @@ void setHasDirAutoAttribute(bool value) { m_hasDirAutoAttribute = value; } bool hasDirAutoAttribute() const { return m_hasDirAutoAttribute; } + void setCustomPropertySetForApplyAtRule(const String&, StylePropertySet*); + StylePropertySet* customPropertySetForApplyAtRule(const String&); + private: ElementResolveContext m_elementContext; RawPtrWillBeMember<Document> m_document; @@ -178,6 +183,8 @@ OwnPtr<CachedUAStyle> m_cachedUAStyle; ElementStyleResources m_elementStyleResources; + + WillBeHeapHashMap<String, RefPtrWillBeMember<StylePropertySet>> m_customPropertySetsForApplyAtRule; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/AXObjectCache.h b/third_party/WebKit/Source/core/dom/AXObjectCache.h index 6bba7e582..d3291d17 100644 --- a/third_party/WebKit/Source/core/dom/AXObjectCache.h +++ b/third_party/WebKit/Source/core/dom/AXObjectCache.h
@@ -96,6 +96,7 @@ virtual void listboxOptionStateChanged(HTMLOptionElement*) = 0; virtual void listboxSelectedChildrenChanged(HTMLSelectElement*) = 0; virtual void listboxActiveIndexChanged(HTMLSelectElement*) = 0; + virtual void radiobuttonRemovedFromGroup(HTMLInputElement*) = 0; virtual void remove(LayoutObject*) = 0; virtual void remove(Node*) = 0;
diff --git a/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp b/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp index 7b2034c..d1d1ede 100644 --- a/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp +++ b/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp
@@ -34,6 +34,7 @@ #include "core/css/parser/CSSParser.h" #include "core/dom/Document.h" #include "core/dom/ExecutionContext.h" +#include "core/dom/StyleEngine.h" #include "core/frame/LocalFrame.h" #include "core/loader/FrameLoaderClient.h" #include "core/style/StyleRareNonInheritedData.h" @@ -158,7 +159,7 @@ m_watchedCallbackSelectors.append(StyleRule::create(std::move(selectorList), callbackPropertySet)); } - document().changedSelectorWatch(); + document().styleEngine().watchedSelectorsChanged(); } DEFINE_TRACE(CSSSelectorWatch)
diff --git a/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h b/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h index 6a331b73..57d21cc 100644 --- a/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h +++ b/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h
@@ -81,6 +81,8 @@ // When an element is reparented, the new location's style is evaluated after the expriation of the relayout timer. // We don't want to send redundant callbacks to the embedder, so this counter lets us wait another time around the event loop. int m_timerExpirations; + + friend class CSSSelectorWatchTest; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp b/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp new file mode 100644 index 0000000..fe7fcd4 --- /dev/null +++ b/third_party/WebKit/Source/core/dom/CSSSelectorWatchTest.cpp
@@ -0,0 +1,93 @@ +// 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 "core/dom/CSSSelectorWatch.h" + +#include "core/dom/Document.h" +#include "core/dom/StyleEngine.h" +#include "core/frame/FrameView.h" +#include "core/html/HTMLElement.h" +#include "core/testing/DummyPageHolder.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +class CSSSelectorWatchTest : public ::testing::Test { +protected: + void SetUp() override; + + Document& document() { return m_dummyPageHolder->document(); } + StyleEngine& styleEngine() { return document().styleEngine(); } + + static const HashSet<String> addedSelectors(const CSSSelectorWatch& watch) { return watch.m_addedSelectors; } + static const HashSet<String> removedSelectors(const CSSSelectorWatch& watch) { return watch.m_removedSelectors; } + static void clearAddedRemoved(CSSSelectorWatch&); + +private: + OwnPtr<DummyPageHolder> m_dummyPageHolder; +}; + +void CSSSelectorWatchTest::SetUp() +{ + m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600)); +} + +void CSSSelectorWatchTest::clearAddedRemoved(CSSSelectorWatch& watch) +{ + watch.m_addedSelectors.clear(); + watch.m_removedSelectors.clear(); +} + +TEST_F(CSSSelectorWatchTest, RecalcOnDocumentChange) +{ + document().body()->setInnerHTML( + "<div>" + " <span id='x' class='a'></span>" + " <span id='y' class='b'><span></span></span>" + " <span id='z'><span></span></span>" + "</div>", ASSERT_NO_EXCEPTION); + + CSSSelectorWatch& watch = CSSSelectorWatch::from(document()); + + Vector<String> selectors; + selectors.append(".a"); + watch.watchCSSSelectors(selectors); + + document().view()->updateAllLifecyclePhases(); + + selectors.clear(); + selectors.append(".b"); + selectors.append(".c"); + selectors.append("#nomatch"); + watch.watchCSSSelectors(selectors); + + document().view()->updateAllLifecyclePhases(); + + Element* x = document().getElementById("x"); + Element* y = document().getElementById("y"); + Element* z = document().getElementById("z"); + ASSERT_TRUE(x); + ASSERT_TRUE(y); + ASSERT_TRUE(z); + + x->removeAttribute(HTMLNames::classAttr); + y->removeAttribute(HTMLNames::classAttr); + z->setAttribute(HTMLNames::classAttr, "c"); + + clearAddedRemoved(watch); + + unsigned beforeCount = styleEngine().styleForElementCount(); + document().view()->updateAllLifecyclePhases(); + unsigned afterCount = styleEngine().styleForElementCount(); + + EXPECT_EQ(2u, afterCount - beforeCount); + + EXPECT_EQ(1u, addedSelectors(watch).size()); + EXPECT_TRUE(addedSelectors(watch).contains(".c")); + + EXPECT_EQ(1u, removedSelectors(watch).size()); + EXPECT_TRUE(removedSelectors(watch).contains(".b")); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index 906c2c8..ec2aa95a 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -1287,18 +1287,29 @@ void Document::setTitle(const String& title) { // Title set by JavaScript -- overrides any title elements. - if (!isHTMLDocument() && !isXHTMLDocument()) { - m_titleElement = nullptr; - } else if (!m_titleElement) { - HTMLElement* headElement = head(); - if (!headElement) - return; - m_titleElement = HTMLTitleElement::create(*this); - headElement->appendChild(m_titleElement.get()); + if (!m_titleElement) { + if (isHTMLDocument() || isXHTMLDocument()) { + HTMLElement* headElement = head(); + if (!headElement) + return; + m_titleElement = HTMLTitleElement::create(*this); + headElement->appendChild(m_titleElement.get()); + } else if (isSVGDocument()) { + Element* element = documentElement(); + if (!isSVGSVGElement(element)) + return; + m_titleElement = SVGTitleElement::create(*this); + element->insertBefore(m_titleElement.get(), element->firstChild()); + } + } else { + if (!isHTMLDocument() && !isXHTMLDocument() && !isSVGDocument()) + m_titleElement = nullptr; } if (isHTMLTitleElement(m_titleElement)) toHTMLTitleElement(m_titleElement)->setText(title); + else if (isSVGTitleElement(m_titleElement)) + toSVGTitleElement(m_titleElement)->setText(title); else updateTitle(title); } @@ -1316,6 +1327,25 @@ m_titleElement = titleElement; } + + if (isSVGDocument()) { + // If the root element that is <svg> element in the svg namespace is not the parent of <title> element, + // ignore <title> element. + if (isSVGSVGElement(documentElement()) && documentElement() != m_titleElement->parentNode()) { + m_titleElement = nullptr; + return; + } + + // If the root element is not <svg> element in the svg namespace and <title> element is in the svg namespace, + // or the root element is <svg> element in the svg namespace and <title> element is not in the svg namespace, + // ignore <title> element. + if ((!isSVGSVGElement(m_titleElement->parentNode()) && isSVGTitleElement(m_titleElement)) + || (isSVGSVGElement(m_titleElement->parentNode()) && !isSVGTitleElement(m_titleElement))) { + m_titleElement = nullptr; + return; + } + } + if (isHTMLTitleElement(m_titleElement)) updateTitle(toHTMLTitleElement(m_titleElement)->text()); else if (isSVGTitleElement(m_titleElement)) @@ -4917,8 +4947,6 @@ { ASSERT(!securityOrigin()); - setHostedInReservedIPRange(initializer.isHostedInReservedIPRange()); - if (!initializer.hasSecurityContext()) { // No source for a security context. // This can occur via document.implementation.createDocument(). @@ -4959,6 +4987,15 @@ setSecurityOrigin(SecurityOrigin::create(m_url)); } + // Set the address space before setting up CSP, as the latter may override + // the former via the 'treat-as-public-address' directive (see + // https://mikewest.github.io/cors-rfc1918/#csp). + if (initializer.isHostedInReservedIPRange()) { + setAddressSpace(securityOrigin()->isLocalhost() ? WebURLRequest::AddressSpaceLocal : WebURLRequest::AddressSpacePrivate); + } else { + setAddressSpace(WebURLRequest::AddressSpacePublic); + } + if (importsController()) { // If this document is an HTML import, grab a reference to it's master document's Content // Security Policy. We don't call 'initContentSecurityPolicy' in this case, as we can't @@ -5736,11 +5773,6 @@ styleEngine().resolverChanged(updateMode); } -void Document::changedSelectorWatch() -{ - styleEngine().resolverChanged(FullStyleUpdate); -} - TextAutosizer* Document::textAutosizer() { if (!m_textAutosizer)
diff --git a/third_party/WebKit/Source/core/dom/Document.h b/third_party/WebKit/Source/core/dom/Document.h index 74809e7..3088fc82 100644 --- a/third_party/WebKit/Source/core/dom/Document.h +++ b/third_party/WebKit/Source/core/dom/Document.h
@@ -386,7 +386,6 @@ // do something smarter. void removedStyleSheet(StyleSheet*, StyleResolverUpdateMode = FullStyleUpdate); void modifiedStyleSheet(StyleSheet*, StyleResolverUpdateMode = FullStyleUpdate); - void changedSelectorWatch(); void scheduleUseShadowTreeUpdate(SVGUseElement&); void unscheduleUseShadowTreeUpdate(SVGUseElement&);
diff --git a/third_party/WebKit/Source/core/dom/Document.idl b/third_party/WebKit/Source/core/dom/Document.idl index ceec172..0f309aa 100644 --- a/third_party/WebKit/Source/core/dom/Document.idl +++ b/third_party/WebKit/Source/core/dom/Document.idl
@@ -26,6 +26,9 @@ // http://www.w3.org/TR/page-visibility/#VisibilityState enum VisibilityState { "hidden", "visible", "prerender", "unloaded" }; +// https://mikewest.github.io/cors-rfc1918/#feature-detect +enum AddressSpace { "local", "private", "public" }; + // https://dom.spec.whatwg.org/#interface-document // FIXME: Document should have a constructor. crbug.com/238234 @@ -194,6 +197,10 @@ readonly attribute boolean hidden; readonly attribute VisibilityState visibilityState; + // CORS and RFC1918 + // https://mikewest.github.io/cors-rfc1918/#feature-detect + [RuntimeEnabled=CorsRFC1918, ImplementedAs=addressSpaceForBindings] readonly attribute AddressSpace addressSpace; + // Non-standard APIs [MeasureAs=DocumentCaretRangeFromPoint] Range caretRangeFromPoint([Default=Undefined] optional long x, [Default=Undefined] optional long y);
diff --git a/third_party/WebKit/Source/core/dom/Node.h b/third_party/WebKit/Source/core/dom/Node.h index 86635a6a..8f3aead06f 100644 --- a/third_party/WebKit/Source/core/dom/Node.h +++ b/third_party/WebKit/Source/core/dom/Node.h
@@ -182,7 +182,8 @@ static void* allocateObject(size_t size, bool isEager) { ThreadState* state = ThreadStateFor<ThreadingTrait<Node>::Affinity>::state(); - return Heap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::NodeArenaIndex, GCInfoTrait<EventTarget>::index()); + const char typeName[] = "blink::Node"; + return Heap::allocateOnArenaIndex(state, size, isEager ? BlinkGC::EagerSweepArenaIndex : BlinkGC::NodeArenaIndex, GCInfoTrait<EventTarget>::index(), typeName); } #else // !ENABLE(OILPAN) // All Nodes are placed in their own heap partition for security.
diff --git a/third_party/WebKit/Source/core/dom/NodeTraversal.h b/third_party/WebKit/Source/core/dom/NodeTraversal.h index 9062ab4..031b62a 100644 --- a/third_party/WebKit/Source/core/dom/NodeTraversal.h +++ b/third_party/WebKit/Source/core/dom/NodeTraversal.h
@@ -50,7 +50,7 @@ // This can be used to restrict traversal to a particular sub-tree. static Node* next(const Node& current) { return traverseNextTemplate(current); } static Node* next(const ContainerNode& current) { return traverseNextTemplate(current); } - static Node* next(const Node& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); } + CORE_EXPORT static Node* next(const Node& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); } static Node* next(const ContainerNode& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); } // Like next, but skips children and starts with the next sibling. @@ -63,7 +63,7 @@ static Node& lastWithinOrSelf(Node&); // Does a reverse pre-order traversal to find the node that comes before the current one in document order - static Node* previous(const Node&, const Node* stayWithin = 0); + CORE_EXPORT static Node* previous(const Node&, const Node* stayWithin = 0); // Like previous, but skips children and starts with the next sibling. static Node* previousSkippingChildren(const Node&, const Node* stayWithin = 0);
diff --git a/third_party/WebKit/Source/core/dom/SecurityContext.cpp b/third_party/WebKit/Source/core/dom/SecurityContext.cpp index 9b640af..716acfb 100644 --- a/third_party/WebKit/Source/core/dom/SecurityContext.cpp +++ b/third_party/WebKit/Source/core/dom/SecurityContext.cpp
@@ -34,7 +34,7 @@ SecurityContext::SecurityContext() : m_sandboxFlags(SandboxNone) - , m_hostedInReservedIPRange(false) + , m_addressSpace(WebURLRequest::AddressSpacePublic) , m_insecureRequestsPolicy(InsecureRequestsDoNotUpgrade) , m_enforceStrictMixedContentChecking(false) { @@ -69,12 +69,20 @@ } } -WebURLRequest::AddressSpace SecurityContext::addressSpace() const +String SecurityContext::addressSpaceForBindings() const { - if (m_hostedInReservedIPRange) - return securityOrigin()->isLocalhost() ? WebURLRequest::AddressSpaceLocal : WebURLRequest::AddressSpacePrivate; + switch (m_addressSpace) { + case WebURLRequest::AddressSpacePublic: + return "public"; - return WebURLRequest::AddressSpacePublic; + case WebURLRequest::AddressSpacePrivate: + return "private"; + + case WebURLRequest::AddressSpaceLocal: + return "local"; + } + ASSERT_NOT_REACHED(); + return "public"; } bool SecurityContext::hasSuborigin()
diff --git a/third_party/WebKit/Source/core/dom/SecurityContext.h b/third_party/WebKit/Source/core/dom/SecurityContext.h index 43eba5b..7c7143c5 100644 --- a/third_party/WebKit/Source/core/dom/SecurityContext.h +++ b/third_party/WebKit/Source/core/dom/SecurityContext.h
@@ -70,8 +70,9 @@ bool isSandboxed(SandboxFlags mask) const { return m_sandboxFlags & mask; } void enforceSandboxFlags(SandboxFlags mask); - void setHostedInReservedIPRange(bool value) { m_hostedInReservedIPRange = value; } - WebURLRequest::AddressSpace addressSpace() const; + void setAddressSpace(WebURLRequest::AddressSpace space) { m_addressSpace = space; } + WebURLRequest::AddressSpace addressSpace() const { return m_addressSpace; } + String addressSpaceForBindings() const; void setInsecureRequestsPolicy(InsecureRequestsPolicy policy) { m_insecureRequestsPolicy = policy; } InsecureRequestsPolicy getInsecureRequestsPolicy() const { return m_insecureRequestsPolicy; } @@ -98,7 +99,7 @@ SandboxFlags m_sandboxFlags; - bool m_hostedInReservedIPRange; + WebURLRequest::AddressSpace m_addressSpace; InsecureRequestsPolicy m_insecureRequestsPolicy; InsecureNavigationsSet m_insecureNavigationsToUpgrade; bool m_enforceStrictMixedContentChecking;
diff --git a/third_party/WebKit/Source/core/dom/SpaceSplitString.cpp b/third_party/WebKit/Source/core/dom/SpaceSplitString.cpp index 1932bc15..43fc98e 100644 --- a/third_party/WebKit/Source/core/dom/SpaceSplitString.cpp +++ b/third_party/WebKit/Source/core/dom/SpaceSplitString.cpp
@@ -174,7 +174,7 @@ PassRefPtr<SpaceSplitString::Data> SpaceSplitString::Data::create(const AtomicString& string) { - Data*& data = sharedDataMap().add(string, 0).storedValue->value; + Data*& data = sharedDataMap().add(string, nullptr).storedValue->value; if (!data) { data = new Data(string); return adoptRef(data);
diff --git a/third_party/WebKit/Source/core/dom/StyleChangeReason.cpp b/third_party/WebKit/Source/core/dom/StyleChangeReason.cpp index 985f674a..e3eda0fe 100644 --- a/third_party/WebKit/Source/core/dom/StyleChangeReason.cpp +++ b/third_party/WebKit/Source/core/dom/StyleChangeReason.cpp
@@ -18,6 +18,7 @@ const char CompositorProxy[] = "CompositorProxy"; const char ControlValue[] = "ControlValue"; const char Control[] = "Control"; +const char DeclarativeContent[] = "Extension declarativeContent.css"; const char DesignMode[] = "DesignMode"; const char Drag[] = "Drag"; const char FontSizeChange[] = "FontSizeChange";
diff --git a/third_party/WebKit/Source/core/dom/StyleChangeReason.h b/third_party/WebKit/Source/core/dom/StyleChangeReason.h index 0faa9b2b..f9ca4ebd 100644 --- a/third_party/WebKit/Source/core/dom/StyleChangeReason.h +++ b/third_party/WebKit/Source/core/dom/StyleChangeReason.h
@@ -22,6 +22,7 @@ extern const char CompositorProxy[]; extern const char ControlValue[]; extern const char Control[]; +extern const char DeclarativeContent[]; extern const char DesignMode[]; extern const char Drag[]; extern const char FontSizeChange[];
diff --git a/third_party/WebKit/Source/core/dom/StyleEngine.cpp b/third_party/WebKit/Source/core/dom/StyleEngine.cpp index 85c5bda..284f782 100644 --- a/third_party/WebKit/Source/core/dom/StyleEngine.cpp +++ b/third_party/WebKit/Source/core/dom/StyleEngine.cpp
@@ -149,7 +149,7 @@ { m_injectedAuthorStyleSheets.append(CSSStyleSheet::create(authorSheet, m_document)); markDocumentDirty(); - resolverChanged(FullStyleUpdate); + resolverChanged(AnalyzedStyleUpdate); } void StyleEngine::addPendingSheet() @@ -238,6 +238,15 @@ resolverChanged(FullStyleUpdate); } +void StyleEngine::watchedSelectorsChanged() +{ + if (m_resolver) { + m_resolver->initWatchedSelectorRules(); + m_resolver->resetRuleFeatures(); + } + document().setNeedsStyleRecalc(SubtreeStyleChange, StyleChangeReasonForTracing::create(StyleChangeReason::DeclarativeContent)); +} + bool StyleEngine::shouldUpdateDocumentStyleSheetCollection(StyleResolverUpdateMode updateMode) const { return m_documentScopeDirty || updateMode == FullStyleUpdate;
diff --git a/third_party/WebKit/Source/core/dom/StyleEngine.h b/third_party/WebKit/Source/core/dom/StyleEngine.h index 5b84af1..96d41060 100644 --- a/third_party/WebKit/Source/core/dom/StyleEngine.h +++ b/third_party/WebKit/Source/core/dom/StyleEngine.h
@@ -90,6 +90,7 @@ void removeStyleSheetCandidateNode(Node*); void removeStyleSheetCandidateNode(Node*, TreeScope&); void modifiedStyleSheetCandidateNode(Node*); + void watchedSelectorsChanged(); void injectAuthorSheet(PassRefPtrWillBeRawPtr<StyleSheetContents> authorSheet);
diff --git a/third_party/WebKit/Source/core/dom/StyleEngineTest.cpp b/third_party/WebKit/Source/core/dom/StyleEngineTest.cpp index 59348fd..1708917 100644 --- a/third_party/WebKit/Source/core/dom/StyleEngineTest.cpp +++ b/third_party/WebKit/Source/core/dom/StyleEngineTest.cpp
@@ -6,7 +6,9 @@ #include "core/css/StyleSheetContents.h" #include "core/dom/Document.h" +#include "core/dom/NodeComputedStyle.h" #include "core/frame/FrameView.h" +#include "core/html/HTMLElement.h" #include "core/testing/DummyPageHolder.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,4 +42,28 @@ EXPECT_TRUE(isDocumentStyleSheetCollectionClean()); } +TEST_F(StyleEngineTest, AnalyzedInject) +{ + document().body()->setInnerHTML("<style>div { color: red }</style><div id='t1'>Green</div><div></div>", ASSERT_NO_EXCEPTION); + document().view()->updateAllLifecyclePhases(); + + Element* t1 = document().getElementById("t1"); + ASSERT_TRUE(t1); + ASSERT_TRUE(t1->computedStyle()); + EXPECT_EQ(makeRGB(255, 0, 0), t1->computedStyle()->visitedDependentColor(CSSPropertyColor)); + + unsigned beforeCount = styleEngine().styleForElementCount(); + + RefPtrWillBeRawPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(CSSParserContext(document(), nullptr)); + parsedSheet->parseString("#t1 { color: green }"); + styleEngine().injectAuthorSheet(parsedSheet); + document().view()->updateAllLifecyclePhases(); + + unsigned afterCount = styleEngine().styleForElementCount(); + EXPECT_EQ(1u, afterCount - beforeCount); + + ASSERT_TRUE(t1->computedStyle()); + EXPECT_EQ(makeRGB(0, 128, 0), t1->computedStyle()->visitedDependentColor(CSSPropertyColor)); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/shadow/SlotScopedTraversal.cpp b/third_party/WebKit/Source/core/dom/shadow/SlotScopedTraversal.cpp new file mode 100644 index 0000000..92a75f5a --- /dev/null +++ b/third_party/WebKit/Source/core/dom/shadow/SlotScopedTraversal.cpp
@@ -0,0 +1,85 @@ +// 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 "core/dom/shadow/SlotScopedTraversal.h" + +#include "core/dom/Element.h" +#include "core/dom/ElementTraversal.h" +#include "core/html/HTMLSlotElement.h" + +namespace blink { + +HTMLSlotElement* SlotScopedTraversal::findScopeOwnerSlot(const Element& current) +{ + if (Element* nearestAncestorAssignedToSlot = SlotScopedTraversal::nearestAncestorAssignedToSlot(current)) + return nearestAncestorAssignedToSlot->assignedSlot(); + return nullptr; +} + +Element* SlotScopedTraversal::nearestAncestorAssignedToSlot(const Element& current) +{ + // nearestAncestorAssignedToSlot returns an ancestor element of current which is directly assigned to a slot. + Element* element = const_cast<Element*>(¤t); + for (; element; element = element->parentElement()) { + if (element->assignedSlot()) + break; + } + return element; +} + +Element* SlotScopedTraversal::next(const Element& current) +{ + // current.assignedSlot returns a slot only when current is assigned explicitly + // If current is assigned to a slot, return a descendant of current, which is in the assigned scope of the same slot as current. + HTMLSlotElement* slot = current.assignedSlot(); + Element* nearestAncestorAssignedToSlot = SlotScopedTraversal::nearestAncestorAssignedToSlot(current); + if (slot) { + if (Element* next = ElementTraversal::next(current, ¤t)) + return next; + } else { + // If current is in assigned scope, find an assigned ancestor. + ASSERT(nearestAncestorAssignedToSlot); + if (Element* next = ElementTraversal::next(current, nearestAncestorAssignedToSlot)) + return next; + slot = nearestAncestorAssignedToSlot->assignedSlot(); + ASSERT(slot); + } + WillBeHeapVector<RefPtrWillBeMember<Node>> assignedNodes = slot->getAssignedNodes(); + size_t currentIndex = assignedNodes.find(*nearestAncestorAssignedToSlot); + ASSERT(currentIndex != kNotFound); + for (++currentIndex; currentIndex < assignedNodes.size(); ++currentIndex) { + if (assignedNodes[currentIndex]->isElementNode()) + return toElement(assignedNodes[currentIndex]); + } + return nullptr; +} + +Element* SlotScopedTraversal::previous(const Element& current) +{ + Element* nearestAncestorAssignedToSlot = SlotScopedTraversal::nearestAncestorAssignedToSlot(current); + ASSERT(nearestAncestorAssignedToSlot); + // NodeTraversal within nearestAncestorAssignedToSlot + if (Element* previous = ElementTraversal::previous(current, nearestAncestorAssignedToSlot)) + return previous; + // If null, jump to previous assigned node's descendant + const WillBeHeapVector<RefPtrWillBeMember<Node>> assignedNodes = nearestAncestorAssignedToSlot->assignedSlot()->getAssignedNodes(); + size_t currentIndex = assignedNodes.reverseFind(*nearestAncestorAssignedToSlot); + ASSERT(currentIndex != kNotFound); + for (; currentIndex > 0; --currentIndex) { + const RefPtrWillBeMember<Node> assignedPrevious = assignedNodes[currentIndex - 1]; + if (assignedPrevious->isElementNode()) { + if (Element* last = ElementTraversal::lastWithin(*toElement(assignedPrevious))) + return last; + return toElement(assignedPrevious); + } + } + return nullptr; +} + +bool SlotScopedTraversal::isSlotScoped(const Element& current) +{ + return SlotScopedTraversal::nearestAncestorAssignedToSlot(current); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/dom/shadow/SlotScopedTraversal.h b/third_party/WebKit/Source/core/dom/shadow/SlotScopedTraversal.h new file mode 100644 index 0000000..7c52353a --- /dev/null +++ b/third_party/WebKit/Source/core/dom/shadow/SlotScopedTraversal.h
@@ -0,0 +1,24 @@ +// 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 SlotScopedTraversal_h +#define SlotScopedTraversal_h + +namespace blink { + +class Element; +class HTMLSlotElement; + +class SlotScopedTraversal { +public: + static HTMLSlotElement* findScopeOwnerSlot(const Element&); + static Element* nearestAncestorAssignedToSlot(const Element&); + static Element* next(const Element&); + static Element* previous(const Element&); + static bool isSlotScoped(const Element&); +}; + +} // namespace blink + +#endif
diff --git a/third_party/WebKit/Source/core/editing/Editor.cpp b/third_party/WebKit/Source/core/editing/Editor.cpp index 98bdea11..4c303e6 100644 --- a/third_party/WebKit/Source/core/editing/Editor.cpp +++ b/third_party/WebKit/Source/core/editing/Editor.cpp
@@ -796,9 +796,10 @@ if (!selection.isContentEditable()) return false; - frame().selection().setSelection(selection); + spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0])); + // Insert the text - TypingCommand::insertText(*selection.start().document(), text, + TypingCommand::insertText(*selection.start().document(), text, selection, selectInsertedText ? TypingCommand::SelectInsertedText : 0, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
diff --git a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp index 363ea972..f80bd883 100644 --- a/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/EditorCommand.cpp
@@ -1683,7 +1683,7 @@ for (size_t i = 0; i < WTF_ARRAY_LENGTH(commands); ++i) { const CommandEntry& command = commands[i]; ASSERT(!commandMap.get(command.name)); - commandMap.set(command.name, &command.command); + commandMap.set(String(command.name), &command.command); #if ENABLE(ASSERT) ASSERT(!idSet.contains(command.command.idForUserMetrics)); idSet.add(command.command.idForUserMetrics);
diff --git a/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp b/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp index 53c3557..d85b5ea 100644 --- a/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/ReplaceSelectionCommand.cpp
@@ -58,6 +58,7 @@ #include "core/html/HTMLSpanElement.h" #include "core/layout/LayoutObject.h" #include "core/layout/LayoutText.h" +#include "platform/TraceEvent.h" #include "wtf/StdLibExtras.h" #include "wtf/Vector.h" @@ -155,6 +156,7 @@ if (!m_fragment || !m_fragment->hasChildren()) return; + TRACE_EVENT0("blink", "ReplacementFragment constructor"); RefPtrWillBeRawPtr<Element> editableRoot = selection.rootEditableElement(); ASSERT(editableRoot); if (!editableRoot) @@ -257,6 +259,7 @@ PassRefPtrWillBeRawPtr<HTMLElement> ReplacementFragment::insertFragmentForTestRendering(Element* rootEditableElement) { + TRACE_EVENT0("blink", "ReplacementFragment::insertFragmentForTestRendering"); ASSERT(m_document); RefPtrWillBeRawPtr<HTMLElement> holder = createDefaultParagraphElement(*m_document.get()); @@ -948,6 +951,7 @@ void ReplaceSelectionCommand::doApply(EditingState* editingState) { + TRACE_EVENT0("blink", "ReplaceSelectionCommand::doApply"); const VisibleSelection selection = endingSelection(); ASSERT(selection.isCaretOrRange()); ASSERT(selection.start().anchorNode());
diff --git a/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.cpp b/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.cpp index c1fc6cdd..4cfbda5 100644 --- a/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.cpp
@@ -39,32 +39,18 @@ { } -String dispatchBeforeTextInsertedEvent(const String& text, const VisibleSelection& selectionForInsertion, bool insertionIsForUpdatingComposition) +void TextInsertionBaseCommand::applyTextInsertionCommand(LocalFrame* frame, PassRefPtrWillBeRawPtr<TextInsertionBaseCommand> command, const VisibleSelection& selectionForInsertion, const VisibleSelection& endingSelection) { - if (insertionIsForUpdatingComposition) - return text; - - String newText = text; - if (Node* startNode = selectionForInsertion.start().computeContainerNode()) { - if (startNode->rootEditableElement()) { - // Send BeforeTextInsertedEvent. The event handler will update text if necessary. - RefPtrWillBeRawPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text); - startNode->rootEditableElement()->dispatchEvent(evt); - newText = evt->text(); - } + bool changeSelection = !equalSelectionsInDOMTree(selectionForInsertion, endingSelection); + if (changeSelection) { + command->setStartingSelection(selectionForInsertion); + command->setEndingSelection(selectionForInsertion); } - return newText; -} - -bool canAppendNewLineFeedToSelection(const VisibleSelection& selection) -{ - Element* element = selection.rootEditableElement(); - if (!element) - return false; - - RefPtrWillBeRawPtr<BeforeTextInsertedEvent> event = BeforeTextInsertedEvent::create(String("\n")); - element->dispatchEvent(event); - return event->text().length(); + command->apply(); + if (changeSelection) { + command->setEndingSelection(endingSelection); + frame->selection().setSelection(endingSelection); + } } } // namespace blink
diff --git a/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.h b/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.h index d58b89c..40c0f01c 100644 --- a/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.h +++ b/third_party/WebKit/Source/core/editing/commands/TextInsertionBaseCommand.h
@@ -40,33 +40,9 @@ protected: explicit TextInsertionBaseCommand(Document&); + static void applyTextInsertionCommand(LocalFrame*, PassRefPtrWillBeRawPtr<TextInsertionBaseCommand>, const VisibleSelection& selectionForInsertion, const VisibleSelection& endingSelection); }; -String dispatchBeforeTextInsertedEvent(const String& text, const VisibleSelection& selectionForInsertion, bool insertionIsForUpdatingComposition); -bool canAppendNewLineFeedToSelection(const VisibleSelection&); - -// LineOperation should define member function "opeartor (size_t lineOffset, size_t lineLength, bool isLastLine)". -// lienLength doesn't include the newline character. So the value of lineLength could be 0. -template <class LineOperation> -void forEachLineInString(const String& string, const LineOperation& operation, EditingState* editingState) -{ - unsigned offset = 0; - size_t newline; - while ((newline = string.find('\n', offset)) != kNotFound) { - operation(offset, newline - offset, false, editingState); - if (editingState->isAborted()) - return; - offset = newline + 1; - } - if (!offset) { - operation(0, string.length(), true, editingState); - } else { - unsigned length = string.length(); - if (length != offset) - operation(offset, length - offset, true, editingState); - } -} - } // namespace blink #endif
diff --git a/third_party/WebKit/Source/core/editing/commands/TypingCommand.cpp b/third_party/WebKit/Source/core/editing/commands/TypingCommand.cpp index 02af6d74..65a3e20 100644 --- a/third_party/WebKit/Source/core/editing/commands/TypingCommand.cpp +++ b/third_party/WebKit/Source/core/editing/commands/TypingCommand.cpp
@@ -39,6 +39,7 @@ #include "core/editing/commands/InsertParagraphSeparatorCommand.h" #include "core/editing/commands/InsertTextCommand.h" #include "core/editing/spellcheck/SpellChecker.h" +#include "core/events/BeforeTextInsertedEvent.h" #include "core/frame/LocalFrame.h" #include "core/html/HTMLBRElement.h" #include "core/layout/LayoutObject.h" @@ -165,7 +166,24 @@ typingCommand->setEndingSelection(currentSelection); } -void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType compositionType) +static String dispatchBeforeTextInsertedEvent(const String& text, const VisibleSelection& selectionForInsertion, bool insertionIsForUpdatingComposition) +{ + if (insertionIsForUpdatingComposition) + return text; + + String newText = text; + if (Node* startNode = selectionForInsertion.start().computeContainerNode()) { + if (startNode->rootEditableElement()) { + // Send BeforeTextInsertedEvent. The event handler will update text if necessary. + RefPtrWillBeRawPtr<BeforeTextInsertedEvent> evt = BeforeTextInsertedEvent::create(text); + startNode->rootEditableElement()->dispatchEvent(evt); + newText = evt->text(); + } + } + return newText; +} + +void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition) { LocalFrame* frame = document.frame(); ASSERT(frame); @@ -173,17 +191,26 @@ if (!text.isEmpty()) document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0])); - const VisibleSelection& currentSelection = frame->selection().selection(); + insertText(document, text, frame->selection().selection(), options, composition); +} - String newText = dispatchBeforeTextInsertedEvent(text, currentSelection, compositionType == TextCompositionUpdate); +// FIXME: We shouldn't need to take selectionForInsertion. It should be identical to FrameSelection's current selection. +void TypingCommand::insertText(Document& document, const String& text, const VisibleSelection& selectionForInsertion, Options options, TextCompositionType compositionType) +{ + RefPtrWillBeRawPtr<LocalFrame> frame = document.frame(); + ASSERT(frame); + + VisibleSelection currentSelection = frame->selection().selection(); + + String newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion, compositionType == TextCompositionUpdate); // Set the starting and ending selection appropriately if we are using a selection // that is different from the current selection. In the future, we should change EditCommand // to deal with custom selections in a general way that can be used by all of the commands. - if (RefPtrWillBeRawPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) { - if (!equalSelectionsInDOMTree(lastTypingCommand->endingSelection(), currentSelection)) { - lastTypingCommand->setStartingSelection(currentSelection); - lastTypingCommand->setEndingSelection(currentSelection); + if (RefPtrWillBeRawPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame.get())) { + if (!equalSelectionsInDOMTree(lastTypingCommand->endingSelection(), selectionForInsertion)) { + lastTypingCommand->setStartingSelection(selectionForInsertion); + lastTypingCommand->setEndingSelection(selectionForInsertion); } lastTypingCommand->setCompositionType(compositionType); @@ -196,7 +223,7 @@ } RefPtrWillBeRawPtr<TypingCommand> cmd = TypingCommand::create(document, InsertText, newText, options, compositionType); - cmd->apply(); + applyTextInsertionCommand(frame.get(), cmd, selectionForInsertion, currentSelection); } bool TypingCommand::insertLineBreak(Document& document) @@ -338,6 +365,28 @@ frame->editor().appliedEditing(this); } +// LineOperation should define member function "opeartor (size_t lineOffset, size_t lineLength, bool isLastLine)". +// lienLength doesn't include the newline character. So the value of lineLength could be 0. +template <class LineOperation> +static void forEachLineInString(const String& string, const LineOperation& operation, EditingState* editingState) +{ + unsigned offset = 0; + size_t newline; + while ((newline = string.find('\n', offset)) != kNotFound) { + operation(offset, newline - offset, false, editingState); + if (editingState->isAborted()) + return; + offset = newline + 1; + } + if (!offset) { + operation(0, string.length(), true, editingState); + } else { + unsigned length = string.length(); + if (length != offset) + operation(offset, length - offset, true, editingState); + } +} + void TypingCommand::insertText(const String &text, bool selectInsertedText, EditingState* editingState) { // FIXME: Need to implement selectInsertedText for cases where more than one insert is involved. @@ -360,6 +409,17 @@ typingAddedToOpenCommand(InsertText); } +static bool canAppendNewLineFeedToSelection(const VisibleSelection& selection) +{ + Element* element = selection.rootEditableElement(); + if (!element) + return false; + + RefPtrWillBeRawPtr<BeforeTextInsertedEvent> event = BeforeTextInsertedEvent::create(String("\n")); + element->dispatchEvent(event); + return event->text().length(); +} + void TypingCommand::insertLineBreak(EditingState* editingState) { if (!canAppendNewLineFeedToSelection(endingSelection()))
diff --git a/third_party/WebKit/Source/core/editing/commands/TypingCommand.h b/third_party/WebKit/Source/core/editing/commands/TypingCommand.h index 04d12b8..a2fc7f7 100644 --- a/third_party/WebKit/Source/core/editing/commands/TypingCommand.h +++ b/third_party/WebKit/Source/core/editing/commands/TypingCommand.h
@@ -61,6 +61,7 @@ static void deleteKeyPressed(Document&, Options, TextGranularity = CharacterGranularity); static void forwardDeleteKeyPressed(Document&, EditingState*, Options = 0, TextGranularity = CharacterGranularity); static void insertText(Document&, const String&, Options, TextCompositionType = TextCompositionNone); + static void insertText(Document&, const String&, const VisibleSelection&, Options, TextCompositionType = TextCompositionNone); static bool insertLineBreak(Document&); static bool insertParagraphSeparator(Document&); static bool insertParagraphSeparatorInQuotedContent(Document&);
diff --git a/third_party/WebKit/Source/core/fetch/DocumentResource.h b/third_party/WebKit/Source/core/fetch/DocumentResource.h index 56c7e83f..44d0cec3 100644 --- a/third_party/WebKit/Source/core/fetch/DocumentResource.h +++ b/third_party/WebKit/Source/core/fetch/DocumentResource.h
@@ -33,7 +33,7 @@ class FetchRequest; class ResourceFetcher; -class DocumentResource final : public Resource { +class CORE_EXPORT DocumentResource final : public Resource { public: using ClientType = ResourceClient; @@ -70,7 +70,7 @@ DEFINE_TYPE_CASTS(DocumentResource, Resource, resource, resource->getType() == Resource::SVGDocument, resource.getType() == Resource::SVGDocument); \ inline DocumentResource* toDocumentResource(const RefPtrWillBeRawPtr<Resource>& ptr) { return toDocumentResource(ptr.get()); } -class DocumentResourceClient : public ResourceClient { +class CORE_EXPORT DocumentResourceClient : public ResourceClient { public: ~DocumentResourceClient() override {} static bool isExpectedType(ResourceClient* client) { return client->getResourceClientType() == DocumentType; }
diff --git a/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp b/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp index 6df47ed..85a7555 100644 --- a/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp +++ b/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp
@@ -385,6 +385,26 @@ } } +void ResourceFetcher::updateMemoryCacheStats(Resource* resource, RevalidationPolicy policy, const FetchRequest& request, const ResourceFactory& factory, bool isStaticData) const +{ + if (isStaticData) + return; + + if (request.forPreload()) { + DEFINE_RESOURCE_HISTOGRAM("Preload."); + } else { + DEFINE_RESOURCE_HISTOGRAM(""); + } + + // Aims to count Resource only referenced from MemoryCache (i.e. what + // would be dead if MemoryCache holds weak references to Resource). + // Currently we check references to Resource from ResourceClient and + // |m_preloads| only, because they are major sources of references. + if (resource && !resource->hasClients() && (!m_preloads || !m_preloads->contains(resource))) { + DEFINE_RESOURCE_HISTOGRAM("Dead."); + } +} + PassRefPtrWillBeRawPtr<Resource> ResourceFetcher::requestResource(FetchRequest& request, const ResourceFactory& factory, const SubstituteData& substituteData) { ASSERT(request.options().synchronousPolicy == RequestAsynchronously || factory.type() == Resource::Raw || factory.type() == Resource::XSLStyleSheet); @@ -434,18 +454,7 @@ const RevalidationPolicy policy = determineRevalidationPolicy(factory.type(), request, resource.get(), isStaticData); - if (request.forPreload()) { - DEFINE_RESOURCE_HISTOGRAM("Preload."); - } else { - DEFINE_RESOURCE_HISTOGRAM(""); - } - // Aims to count Resource only referenced from MemoryCache (i.e. what - // would be dead if MemoryCache holds weak references to Resource). - // Currently we check references to Resource from ResourceClient and - // |m_preloads| only, because they are major sources of references. - if (resource && !resource->hasClients() && (!m_preloads || !m_preloads->contains(resource)) && !isStaticData) { - DEFINE_RESOURCE_HISTOGRAM("Dead."); - } + updateMemoryCacheStats(resource.get(), policy, request, factory, isStaticData); switch (policy) { case Reload: @@ -1068,11 +1077,6 @@ return context().defersLoading(); } -bool ResourceFetcher::isLoadedBy(ResourceFetcher* possibleOwner) const -{ - return this == possibleOwner; -} - bool ResourceFetcher::canAccessRedirect(Resource* resource, ResourceRequest& newRequest, const ResourceResponse& redirectResponse, ResourceLoaderOptions& options) { if (!context().canRequest(resource->getType(), newRequest, newRequest.url(), options, resource->isUnusedPreload(), FetchRequest::UseDefaultOriginRestrictionForType))
diff --git a/third_party/WebKit/Source/core/fetch/ResourceFetcher.h b/third_party/WebKit/Source/core/fetch/ResourceFetcher.h index f895462..c74f71b 100644 --- a/third_party/WebKit/Source/core/fetch/ResourceFetcher.h +++ b/third_party/WebKit/Source/core/fetch/ResourceFetcher.h
@@ -118,7 +118,6 @@ void didInitializeResourceLoader(ResourceLoader*); void willStartLoadingResource(Resource*, ResourceRequest&); bool defersLoading() const; - bool isLoadedBy(ResourceFetcher*) const; enum AccessControlLoggingDecision { ShouldLogAccessControlErrors, @@ -182,6 +181,8 @@ void willTerminateResourceLoader(ResourceLoader*); + void updateMemoryCacheStats(Resource*, RevalidationPolicy, const FetchRequest&, const ResourceFactory&, bool isStaticData) const; + Member<FetchContext> m_context; HashSet<String> m_validatedURLs;
diff --git a/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp b/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp index 0e14f963..b44b22a8 100644 --- a/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp +++ b/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
@@ -66,7 +66,6 @@ ResourceLoader::ResourceLoader(ResourceFetcher* fetcher, Resource* resource, const ResourceLoaderOptions& options) : m_fetcher(fetcher) , m_notifiedLoadComplete(false) - , m_defersLoading(fetcher->defersLoading()) , m_loadingMultipartContent(false) , m_options(options) , m_resource(resource) @@ -103,7 +102,6 @@ m_loader->cancel(); m_loader.clear(); } - m_deferredRequest = ResourceRequest(); m_fetcher.clear(); } @@ -120,28 +118,20 @@ { ASSERT(!m_loader); ASSERT(!m_request.isNull()); - ASSERT(m_deferredRequest.isNull()); m_fetcher->willStartLoadingResource(m_resource.get(), m_request); - - if (m_defersLoading) { - m_deferredRequest = m_request; - return; - } - - if (m_options.synchronousPolicy == RequestSynchronously) { - requestSynchronously(); - return; - } - RELEASE_ASSERT(m_state == ConnectionStateNew); m_state = ConnectionStateStarted; m_loader = adoptPtr(Platform::current()->createURLLoader()); + m_loader->setDefersLoading(m_fetcher->defersLoading()); ASSERT(m_loader); m_loader->setLoadingTaskRunner(m_fetcher->loadingTaskRunner()); - WrappedResourceRequest wrappedRequest(m_request); - m_loader->loadAsynchronously(wrappedRequest, this); + + if (m_options.synchronousPolicy == RequestSynchronously) + requestSynchronously(); + else + m_loader->loadAsynchronously(WrappedResourceRequest(m_request), this); } void ResourceLoader::changeToSynchronous() @@ -150,21 +140,17 @@ ASSERT(m_loader); m_loader->cancel(); m_loader.clear(); + m_loader = adoptPtr(Platform::current()->createURLLoader()); + ASSERT(m_loader); m_request.setPriority(ResourceLoadPriorityHighest); - m_state = ConnectionStateNew; + m_state = ConnectionStateStarted; requestSynchronously(); } void ResourceLoader::setDefersLoading(bool defers) { - m_defersLoading = defers; - if (m_loader) - m_loader->setDefersLoading(defers); - if (!defers && !m_deferredRequest.isNull()) { - m_request = applyOptions(m_deferredRequest); - m_deferredRequest = ResourceRequest(); - start(); - } + ASSERT(m_loader); + m_loader->setDefersLoading(defers); } void ResourceLoader::didDownloadData(WebURLLoader*, int length, int encodedDataLength) @@ -430,30 +416,24 @@ releaseResources(); } -bool ResourceLoader::isLoadedBy(ResourceFetcher* loader) const -{ - return m_fetcher->isLoadedBy(loader); -} - void ResourceLoader::requestSynchronously() { - OwnPtr<WebURLLoader> loader = adoptPtr(Platform::current()->createURLLoader()); - ASSERT(loader); - // downloadToFile is not supported for synchronous requests. ASSERT(!m_request.downloadToFile()); + ASSERT(m_loader); + + if (m_fetcher->defersLoading()) { + cancel(); + return; + } RefPtrWillBeRawPtr<Resource> protectResource(m_resource.get()); - - RELEASE_ASSERT(m_state == ConnectionStateNew); - m_state = ConnectionStateStarted; - WrappedResourceRequest requestIn(m_request); WebURLResponse responseOut; responseOut.initialize(); WebURLError errorOut; WebData dataOut; - loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut); + m_loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut); if (errorOut.reason) { if (m_state == ConnectionStateReleased) { // A message dispatched while synchronously fetching the resource
diff --git a/third_party/WebKit/Source/core/fetch/ResourceLoader.h b/third_party/WebKit/Source/core/fetch/ResourceLoader.h index 66a9320..d4630f5b 100644 --- a/third_party/WebKit/Source/core/fetch/ResourceLoader.h +++ b/third_party/WebKit/Source/core/fetch/ResourceLoader.h
@@ -40,7 +40,6 @@ namespace blink { class Resource; -class KURL; class ResourceError; class ResourceFetcher; @@ -64,9 +63,6 @@ const ResourceRequest& originalRequest() const { return m_originalRequest; } void setDefersLoading(bool); - bool defersLoading() const { return m_defersLoading; } - - void releaseResources(); void didChangePriority(ResourceLoadPriority, int intraPriorityValue); @@ -81,11 +77,6 @@ void didFail(WebURLLoader*, const WebURLError&) override; void didDownloadData(WebURLLoader*, int, int) override; - const KURL& url() const { return m_request.url(); } - bool isLoadedBy(ResourceFetcher*) const; - - const ResourceRequest& request() const { return m_request; } - bool loadingMultipartContent() const { return m_loadingMultipartContent; } private: @@ -101,6 +92,8 @@ ResourceRequest& applyOptions(ResourceRequest&) const; + void releaseResources(); + OwnPtr<WebURLLoader> m_loader; Member<ResourceFetcher> m_fetcher; @@ -109,9 +102,7 @@ bool m_notifiedLoadComplete; - bool m_defersLoading; bool m_loadingMultipartContent; - ResourceRequest m_deferredRequest; ResourceLoaderOptions m_options; enum ConnectionState {
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp index 94efad2e..fdb16e9dc 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.cpp +++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -1797,6 +1797,8 @@ if (!shouldThrottleRendering()) page()->animator().scheduleVisualUpdate(m_frame.get()); + // TODO(chrishtr): this is dangerous and probably incorrect, since layout can be rescheduled during + // the lifecycle in cases such as change of containing block chain. Remove it. lifecycle().ensureStateAtMost(DocumentLifecycle::StyleClean); }
diff --git a/third_party/WebKit/Source/core/frame/ImageBitmap.cpp b/third_party/WebKit/Source/core/frame/ImageBitmap.cpp index b11c575..ed6061d2 100644 --- a/third_party/WebKit/Source/core/frame/ImageBitmap.cpp +++ b/third_party/WebKit/Source/core/frame/ImageBitmap.cpp
@@ -429,7 +429,7 @@ if (options.premultiplyAlpha() == imageBitmapOptionNone) { m_isPremultiplied = false; } else { - ASSERT(options.premultiplyAlpha() == "default"); + ASSERT(options.premultiplyAlpha() == "default" || options.premultiplyAlpha() == "premultiply"); } }
diff --git a/third_party/WebKit/Source/core/frame/Location.cpp b/third_party/WebKit/Source/core/frame/Location.cpp index 4b4985a..41184f7 100644 --- a/third_party/WebKit/Source/core/frame/Location.cpp +++ b/third_party/WebKit/Source/core/frame/Location.cpp
@@ -217,18 +217,18 @@ setLocation(url.getString(), currentWindow, enteredWindow); } -void Location::assign(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String& url) +void Location::assign(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String& url, ExceptionState& exceptionState) { if (!m_frame) return; - setLocation(url, currentWindow, enteredWindow); + setLocation(url, currentWindow, enteredWindow, &exceptionState); } -void Location::replace(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String& url) +void Location::replace(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String& url, ExceptionState& exceptionState) { if (!m_frame) return; - setLocation(url, currentWindow, enteredWindow, SetLocation::ReplaceThisFrame); + setLocation(url, currentWindow, enteredWindow, &exceptionState, SetLocation::ReplaceThisFrame); } void Location::reload(LocalDOMWindow* currentWindow) @@ -240,7 +240,7 @@ m_frame->reload(FrameLoadTypeReload, ClientRedirect); } -void Location::setLocation(const String& url, LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, SetLocation locationPolicy) +void Location::setLocation(const String& url, LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, ExceptionState* exceptionState, SetLocation locationPolicy) { ASSERT(m_frame); if (!m_frame || !m_frame->host()) @@ -256,6 +256,10 @@ KURL completedURL = enteredDocument->completeURL(url); if (completedURL.isNull()) return; + if (exceptionState && !completedURL.isValid()) { + exceptionState->throwDOMException(SyntaxError, "'" + url + "' is not a valid URL."); + return; + } if (m_frame->domWindow()->isInsecureScriptAccess(*currentWindow, completedURL)) return;
diff --git a/third_party/WebKit/Source/core/frame/Location.h b/third_party/WebKit/Source/core/frame/Location.h index 003347b3..57e3938 100644 --- a/third_party/WebKit/Source/core/frame/Location.h +++ b/third_party/WebKit/Source/core/frame/Location.h
@@ -63,8 +63,8 @@ void setHref(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String&); String href() const; - void assign(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String&); - void replace(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String&); + void assign(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String&, ExceptionState&); + void replace(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String&, ExceptionState&); void reload(LocalDOMWindow* currentWindow); void setProtocol(LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, const String&, ExceptionState&); @@ -96,7 +96,7 @@ explicit Location(Frame*); enum class SetLocation { Normal, ReplaceThisFrame }; - void setLocation(const String&, LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, SetLocation = SetLocation::Normal); + void setLocation(const String&, LocalDOMWindow* currentWindow, LocalDOMWindow* enteredWindow, ExceptionState* = nullptr, SetLocation = SetLocation::Normal); const KURL& url() const;
diff --git a/third_party/WebKit/Source/core/frame/Location.idl b/third_party/WebKit/Source/core/frame/Location.idl index 3fc6853..7d08340e 100644 --- a/third_party/WebKit/Source/core/frame/Location.idl +++ b/third_party/WebKit/Source/core/frame/Location.idl
@@ -38,8 +38,8 @@ // property of an *existing* document at a different origin. // However, *reading* |href|, or accessing any component, is a security // problem, since that allows tracking navigation. - [CallWith=(CurrentWindow,EnteredWindow), DoNotCheckSecurity] void assign(DOMString url); - [CallWith=(CurrentWindow,EnteredWindow), DoNotCheckSecurity] void replace(DOMString url); + [CallWith=(CurrentWindow,EnteredWindow), DoNotCheckSecurity, RaisesException] void assign(DOMString url); + [CallWith=(CurrentWindow,EnteredWindow), DoNotCheckSecurity, RaisesException] void replace(DOMString url); [CallWith=CurrentWindow] void reload(); // TODO(philipj): ancestorOrigins should have [SameObject] and be of type
diff --git a/third_party/WebKit/Source/core/frame/UseCounter.h b/third_party/WebKit/Source/core/frame/UseCounter.h index 9ca5873..fe3a242 100644 --- a/third_party/WebKit/Source/core/frame/UseCounter.h +++ b/third_party/WebKit/Source/core/frame/UseCounter.h
@@ -1075,9 +1075,20 @@ ApplicationCacheManifestSelectSecureOrigin = 1246, ApplicationCacheAPIInsecureOrigin = 1247, ApplicationCacheAPISecureOrigin = 1248, + // The above items are available in M50 branch + CSSAtRuleApply = 1249, CSSSelectorPseudoAny = 1250, PannerNodeSetVelocity = 1251, + DocumentAllItemNoArguments = 1252, + DocumentAllItemNamed = 1253, + DocumentAllItemIndexed = 1254, + DocumentAllItemIndexedWithNonNumber = 1255, + DocumentAllLegacyCallNoArguments = 1256, + DocumentAllLegacyCallNamed = 1257, + DocumentAllLegacyCallIndexed = 1258, + DocumentAllLegacyCallIndexedWithNonNumber = 1259, + DocumentAllLegacyCallTwoArguments = 1260, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp index 2fd11fd9..6827097 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicy.cpp
@@ -177,7 +177,7 @@ if (m_enforceStrictMixedContentChecking) document->enforceStrictMixedContentChecking(); if (m_treatAsPublicAddress) - document->setHostedInReservedIPRange(false); + document->setAddressSpace(WebURLRequest::AddressSpacePublic); if (m_insecureRequestsPolicy == SecurityContext::InsecureRequestsUpgrade) { UseCounter::count(document, UseCounter::UpgradeInsecureRequestsEnabled); document->setInsecureRequestsPolicy(m_insecureRequestsPolicy);
diff --git a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp index ffe17992..60b2495 100644 --- a/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp +++ b/third_party/WebKit/Source/core/frame/csp/ContentSecurityPolicyTest.cpp
@@ -61,7 +61,7 @@ TEST_F(ContentSecurityPolicyTest, ParseEnforceTreatAsPublicAddressDisabled) { RuntimeEnabledFeatures::setCorsRFC1918Enabled(false); - document->setHostedInReservedIPRange(true); + document->setAddressSpace(WebURLRequest::AddressSpacePrivate); EXPECT_EQ(WebURLRequest::AddressSpacePrivate, document->addressSpace()); csp->didReceiveHeader("treat-as-public-address", ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceHTTP); @@ -72,7 +72,7 @@ TEST_F(ContentSecurityPolicyTest, ParseEnforceTreatAsPublicAddressEnabled) { RuntimeEnabledFeatures::setCorsRFC1918Enabled(true); - document->setHostedInReservedIPRange(true); + document->setAddressSpace(WebURLRequest::AddressSpacePrivate); EXPECT_EQ(WebURLRequest::AddressSpacePrivate, document->addressSpace()); csp->didReceiveHeader("treat-as-public-address", ContentSecurityPolicyHeaderTypeEnforce, ContentSecurityPolicyHeaderSourceHTTP);
diff --git a/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp b/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp index f9c89be..44a97178e 100644 --- a/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
@@ -214,6 +214,13 @@ return true; } +bool HTMLButtonElement::matchesDefaultPseudoClass() const +{ + // HTMLFormElement::findDefaultButton() traverses the tree. So we check + // canBeSuccessfulSubmitButton() first for early return. + return canBeSuccessfulSubmitButton() && form() && form()->findDefaultButton() == this; +} + Node::InsertionNotificationRequest HTMLButtonElement::insertedInto(ContainerNode* insertionPoint) { InsertionNotificationRequest request = HTMLFormControlElement::insertedInto(insertionPoint);
diff --git a/third_party/WebKit/Source/core/html/HTMLButtonElement.h b/third_party/WebKit/Source/core/html/HTMLButtonElement.h index ffc3df0..21f3731e6 100644 --- a/third_party/WebKit/Source/core/html/HTMLButtonElement.h +++ b/third_party/WebKit/Source/core/html/HTMLButtonElement.h
@@ -62,6 +62,7 @@ bool supportLabels() const override { return true; } bool isInteractiveContent() const override; bool supportsAutofocus() const override; + bool matchesDefaultPseudoClass() const override; bool canBeSuccessfulSubmitButton() const override; bool isActivatedSubmit() const override;
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp index a26795b8..65729e11 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
@@ -635,13 +635,6 @@ return canBeSuccessfulSubmitButton() && !isDisabledFormControl(); } -bool HTMLFormControlElement::matchesDefaultPseudoClass() const -{ - // HTMLFormElement::findDefaultButton() traverses the tree. So we check - // canBeSuccessfulSubmitButton() first for early return. - return canBeSuccessfulSubmitButton() && form() && form()->findDefaultButton() == this; -} - HTMLFormControlElement* HTMLFormControlElement::enclosingFormControlElement(Node* node) { if (!node)
diff --git a/third_party/WebKit/Source/core/html/HTMLFormControlElement.h b/third_party/WebKit/Source/core/html/HTMLFormControlElement.h index 4a3df3e..b29083d 100644 --- a/third_party/WebKit/Source/core/html/HTMLFormControlElement.h +++ b/third_party/WebKit/Source/core/html/HTMLFormControlElement.h
@@ -166,7 +166,6 @@ short tabIndex() const final; - bool matchesDefaultPseudoClass() const final; bool isValidElement() override; bool matchesValidityPseudoClasses() const override; void updateAncestorDisabledState() const;
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp index 1a52b21e..93a646b 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
@@ -1658,6 +1658,11 @@ return m_inputType->isInteractiveContent(); } +bool HTMLInputElement::matchesDefaultPseudoClass() const +{ + return m_inputType->matchesDefaultPseudoClass(); +} + bool HTMLInputElement::shouldAppearChecked() const { return checked() && m_inputType->isCheckable(); @@ -1759,6 +1764,14 @@ return nullptr; } +unsigned HTMLInputElement::sizeOfRadioGroup() const +{ + RadioButtonGroupScope* scope = radioButtonGroupScope(); + if (!scope) + return 0; + return scope->groupSizeFor(this); +} + inline void HTMLInputElement::addToRadioButtonGroup() { if (RadioButtonGroupScope* scope = radioButtonGroupScope())
diff --git a/third_party/WebKit/Source/core/html/HTMLInputElement.h b/third_party/WebKit/Source/core/html/HTMLInputElement.h index aa90370f..a94aece 100644 --- a/third_party/WebKit/Source/core/html/HTMLInputElement.h +++ b/third_party/WebKit/Source/core/html/HTMLInputElement.h
@@ -268,6 +268,8 @@ bool isPlaceholderVisible() const override { return m_isPlaceholderVisible; } void setPlaceholderVisibility(bool) override; + unsigned sizeOfRadioGroup() const; + protected: HTMLInputElement(Document&, HTMLFormElement*, bool createdByParser); @@ -292,6 +294,7 @@ bool isEnumeratable() const final; bool isInteractiveContent() const final; bool supportLabels() const final; + bool matchesDefaultPseudoClass() const override; bool isTextFormControl() const final { return isTextField(); }
diff --git a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp index 612f4cd2..854d842 100644 --- a/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -874,14 +874,15 @@ if (mode == attribute) { m_loadState = LoadingFromSrcAttr; + const AtomicString& srcValue = fastGetAttribute(srcAttr); // If the src attribute's value is the empty string ... jump down to the failed step below - KURL mediaURL = getNonEmptyURLAttribute(srcAttr); - if (mediaURL.isEmpty()) { + if (srcValue.isEmpty()) { mediaLoadingFailed(WebMediaPlayer::NetworkStateFormatError); WTF_LOG(Media, "HTMLMediaElement::selectMediaResource(%p), empty 'src'", this); return; } + KURL mediaURL = document().completeURL(srcValue); if (!isSafeToLoadURL(mediaURL, Complain)) { mediaLoadingFailed(WebMediaPlayer::NetworkStateFormatError); return; @@ -2640,15 +2641,31 @@ source = toHTMLSourceElement(node); - // If candidate does not have a src attribute, or if its src attribute's value is the empty string ... jump down to the failed step below - mediaURL = source->getNonEmptyURLAttribute(srcAttr); + // 2. If candidate does not have a src attribute, or if its src + // attribute's value is the empty string ... jump down to the failed + // step below + const AtomicString& srcValue = source->fastGetAttribute(srcAttr); #if !LOG_DISABLED if (shouldLog) WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild(%p) - 'src' is %s", this, urlForLoggingMedia(mediaURL).utf8().data()); #endif - if (mediaURL.isEmpty()) + if (srcValue.isEmpty()) goto checkAgain; + // 3. Let urlString be the resulting URL string that would have resulted + // from parsing the URL specified by candidate's src attribute's value + // relative to the candidate's node document when the src attribute was + // last changed. + mediaURL = source->document().completeURL(srcValue); + + // 4. If urlString was not obtained successfully, then end the + // synchronous section, and jump down to the failed with elements step + // below. + if (!isSafeToLoadURL(mediaURL, actionIfInvalid)) + goto checkAgain; + + // 5. If candidate has a type attribute whose value, when parsed as a + // MIME type ... type = source->type(); if (type.isEmpty() && mediaURL.protocolIsData()) type = mimeTypeFromDataURL(mediaURL); @@ -2661,10 +2678,6 @@ goto checkAgain; } - // Is it safe to load this url? - if (!isSafeToLoadURL(mediaURL, actionIfInvalid)) - goto checkAgain; - // Making it this far means the <source> looks reasonable. canUseSourceElement = true;
diff --git a/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp b/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp index 4c8bf90..3a1b25d0 100644 --- a/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp
@@ -115,6 +115,11 @@ return HTMLElement::supportsFocus(); } +bool HTMLOptionElement::matchesDefaultPseudoClass() const +{ + return fastHasAttribute(selectedAttr); +} + String HTMLOptionElement::displayLabel() const { Document& document = this->document();
diff --git a/third_party/WebKit/Source/core/html/HTMLOptionElement.h b/third_party/WebKit/Source/core/html/HTMLOptionElement.h index 695a2c4..edf7cd7 100644 --- a/third_party/WebKit/Source/core/html/HTMLOptionElement.h +++ b/third_party/WebKit/Source/core/html/HTMLOptionElement.h
@@ -91,6 +91,7 @@ ~HTMLOptionElement(); bool supportsFocus() const override; + bool matchesDefaultPseudoClass() const override; void attach(const AttachContext& = AttachContext()) override; void detach(const AttachContext& = AttachContext()) override; void parseAttribute(const QualifiedName&, const AtomicString&, const AtomicString&) override;
diff --git a/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp b/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp index 9eb0bba..8cf28d0 100644 --- a/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp
@@ -34,6 +34,7 @@ #include "core/HTMLNames.h" #include "core/dom/Text.h" #include "core/dom/shadow/ShadowRoot.h" +#include "core/html/HTMLFormElement.h" #include "core/html/HTMLInputElement.h" #include "core/html/parser/HTMLParserIdioms.h" #include "core/layout/LayoutButton.h" @@ -82,4 +83,11 @@ element().setAttribute(valueAttr, AtomicString(sanitizedValue)); } +bool BaseButtonInputType::matchesDefaultPseudoClass() +{ + // HTMLFormElement::findDefaultButton() traverses the tree. So we check + // canBeSuccessfulSubmitButton() first for early return. + return canBeSuccessfulSubmitButton() && element().form() && element().form()->findDefaultButton() == &element(); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h b/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h index 26f0934..7f92bb1 100644 --- a/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h +++ b/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h
@@ -48,6 +48,7 @@ LayoutObject* createLayoutObject(const ComputedStyle&) const override; bool storesValueSeparateFromAttribute() override; void setValue(const String&, bool, TextFieldEventBehavior) override; + bool matchesDefaultPseudoClass() override; String displayValue() const; };
diff --git a/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp b/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp index f30b2e6..bd286ca9 100644 --- a/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp
@@ -88,6 +88,11 @@ element().dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents); } +bool BaseCheckableInputType::matchesDefaultPseudoClass() +{ + return element().fastHasAttribute(checkedAttr); +} + String BaseCheckableInputType::fallbackValue() const { return "on";
diff --git a/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h b/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h index c95763a..be3fe504 100644 --- a/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h +++ b/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h
@@ -54,6 +54,7 @@ void handleKeypressEvent(KeyboardEvent*) final; bool canSetStringValue() const final; void accessKeyAction(bool sendMouseEvents) final; + bool matchesDefaultPseudoClass() override; String fallbackValue() const final; bool storesValueSeparateFromAttribute() final; void setValue(const String&, bool, TextFieldEventBehavior) final;
diff --git a/third_party/WebKit/Source/core/html/forms/InputType.cpp b/third_party/WebKit/Source/core/html/forms/InputType.cpp index fe24b7fa..dffeacf 100644 --- a/third_party/WebKit/Source/core/html/forms/InputType.cpp +++ b/third_party/WebKit/Source/core/html/forms/InputType.cpp
@@ -518,6 +518,11 @@ return false; } +bool InputType::matchesDefaultPseudoClass() +{ + return false; +} + bool InputType::layoutObjectIsNeeded() { return true;
diff --git a/third_party/WebKit/Source/core/html/forms/InputType.h b/third_party/WebKit/Source/core/html/forms/InputType.h index 9341378..b30cfef 100644 --- a/third_party/WebKit/Source/core/html/forms/InputType.h +++ b/third_party/WebKit/Source/core/html/forms/InputType.h
@@ -148,6 +148,7 @@ virtual void disableSecureTextInput(); virtual void accessKeyAction(bool sendMouseEvents); virtual bool canBeSuccessfulSubmitButton(); + virtual bool matchesDefaultPseudoClass(); // Miscellaneous functions
diff --git a/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp b/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp index a09c670..c60402ae 100644 --- a/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp +++ b/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.cpp
@@ -38,6 +38,7 @@ void requiredAttributeChanged(HTMLInputElement*); void remove(HTMLInputElement*); bool contains(HTMLInputElement*) const; + unsigned size() const; DECLARE_TRACE(); @@ -180,6 +181,13 @@ // valid only if the group was invalid. button->setNeedsValidityCheck(); } + + // Send notification to update AX attributes for AXObjects which radiobutton group has. + if (!m_members.isEmpty()) { + HTMLInputElement* input = m_members.begin()->key; + if (AXObjectCache* cache = input->document().existingAXObjectCache()) + cache->radiobuttonRemovedFromGroup(input); + } } void RadioButtonGroup::setNeedsValidityCheckForAllButtons() @@ -196,6 +204,11 @@ return m_members.contains(button); } +unsigned RadioButtonGroup::size() const +{ + return m_members.size(); +} + DEFINE_TRACE(RadioButtonGroup) { #if ENABLE(OILPAN) @@ -277,6 +290,17 @@ return group && group->isRequired() && group->contains(element); } +unsigned RadioButtonGroupScope::groupSizeFor(const HTMLInputElement* element) const +{ + if (!m_nameToGroupMap) + return 0; + + RadioButtonGroup* group = m_nameToGroupMap->get(element->name()); + if (!group) + return 0; + return group->size(); +} + void RadioButtonGroupScope::removeButton(HTMLInputElement* element) { ASSERT(element->type() == InputTypeNames::radio);
diff --git a/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.h b/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.h index 48c6e2f..845b489 100644 --- a/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.h +++ b/third_party/WebKit/Source/core/html/forms/RadioButtonGroupScope.h
@@ -44,6 +44,7 @@ void removeButton(HTMLInputElement*); HTMLInputElement* checkedButtonForGroup(const AtomicString& groupName) const; bool isInRequiredGroup(HTMLInputElement*) const; + unsigned groupSizeFor(const HTMLInputElement*) const; private: using NameToGroupMap = WillBeHeapHashMap<AtomicString, OwnPtrWillBeMember<RadioButtonGroup>, CaseFoldingHash>;
diff --git a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapOptions.idl b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapOptions.idl index a0df035..3ed9742 100644 --- a/third_party/WebKit/Source/core/imagebitmap/ImageBitmapOptions.idl +++ b/third_party/WebKit/Source/core/imagebitmap/ImageBitmapOptions.idl
@@ -5,7 +5,7 @@ // https://html.spec.whatwg.org/#imagebitmapoptions [RuntimeEnabled=ExperimentalCanvasFeatures] enum ImageOrientation { "none", "flipY" }; -[RuntimeEnabled=ExperimentalCanvasFeatures] enum PremultiplyAlpha { "none", "default" }; +[RuntimeEnabled=ExperimentalCanvasFeatures] enum PremultiplyAlpha { "none", "premultiply", "default" }; dictionary ImageBitmapOptions { [RuntimeEnabled=ExperimentalCanvasFeatures] PremultiplyAlpha premultiplyAlpha = "default"; [RuntimeEnabled=ExperimentalCanvasFeatures] ImageOrientation imageOrientation = "none";
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp index 9854ebc..6bf5d94 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.cpp
@@ -164,16 +164,14 @@ float DevToolsHost::zoomFactor() { - return m_frontendFrame ? m_frontendFrame->pageZoomFactor() : 1; -} - -float DevToolsHost::convertLengthForEmbedder(float length) -{ if (!m_frontendFrame) - return length; + return 1; + float zoomFactor = m_frontendFrame->pageZoomFactor(); + // Cancel the device scale factor applied to the zoom factor in + // use-zoom-for-dsf mode. const HostWindow* hostWindow = m_frontendFrame->view()->hostWindow(); - IntRect screen = hostWindow->viewportToScreen(IntRect(0, 0, length, 0)); - return screen.width(); + float windowToViewportRatio = hostWindow->windowToViewportScalar(1.0f); + return zoomFactor / windowToViewportRatio; } void DevToolsHost::setInjectedScriptForOrigin(const String& origin, const String& script)
diff --git a/third_party/WebKit/Source/core/inspector/DevToolsHost.idl b/third_party/WebKit/Source/core/inspector/DevToolsHost.idl index c2846c0..096fd64 100644 --- a/third_party/WebKit/Source/core/inspector/DevToolsHost.idl +++ b/third_party/WebKit/Source/core/inspector/DevToolsHost.idl
@@ -36,8 +36,6 @@ ] interface DevToolsHost { float zoomFactor(); - float convertLengthForEmbedder(float length); - void setInjectedScriptForOrigin(DOMString origin, DOMString script); void copyText(DOMString text);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl index 260db42..a1aeedf 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl +++ b/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
@@ -342,7 +342,7 @@ void didFireAnimationFrame(const InspectorInstrumentationCookie&); [Worker] - void didStartWorker(ExecutionContext*, WorkerInspectorProxy* proxy, const KURL& url); + void didStartWorker(ExecutionContext*, WorkerInspectorProxy* proxy, const KURL& url, bool waitingForDebugger); [Worker, PageConsole] void workerTerminated(ExecutionContext*, WorkerInspectorProxy* proxy); @@ -447,7 +447,7 @@ bool forcePseudoState([Keep] Element* element, CSSSelector::PseudoType pseudoState); [Worker, Inline=FastReturn] - bool shouldPauseDedicatedWorkerOnStart(ExecutionContext* context); + bool shouldWaitForDebuggerOnWorkerStart(ExecutionContext* context); [Resource, Inline=FastReturn] bool shouldForceCORSPreflight(Document*);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp index 5473a3c..123d5b3 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
@@ -154,11 +154,6 @@ m_client->resumeStartup(); } -void InspectorRuntimeAgent::isRunRequired(ErrorString* errorString, bool* outResult) -{ - *outResult = m_client->isRunRequired(); -} - void InspectorRuntimeAgent::setCustomObjectFormatterEnabled(ErrorString* errorString, bool enabled) { m_v8RuntimeAgent->setCustomObjectFormatterEnabled(errorString, enabled);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h index 1cf7d36..d82bfc0a 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
@@ -63,7 +63,6 @@ virtual ~Client() { } virtual void resumeStartup() { } - virtual bool isRunRequired() { return false; } }; ~InspectorRuntimeAgent() override; @@ -86,7 +85,6 @@ void run(ErrorString*) override; void enable(ErrorString*) override; void disable(ErrorString*) override; - void isRunRequired(ErrorString*, bool* result) override; void setCustomObjectFormatterEnabled(ErrorString*, bool enabled) override; void compileScript(ErrorString*, const String& expression, const String& sourceURL, bool persistScript, int executionContextId, Maybe<String>* scriptId, Maybe<protocol::Runtime::ExceptionDetails>*) override; void runScript(ErrorString*, const String& scriptId, int executionContextId, const Maybe<String>& objectGroup, const Maybe<bool>& doNotPauseOnExceptionsAndMuteConsole, const Maybe<bool>& includeCommandLineAPI, OwnPtr<protocol::Runtime::RemoteObject>* result, Maybe<protocol::Runtime::ExceptionDetails>*) override;
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp b/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp index 0f7c5ddc..3d31d0a 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.cpp
@@ -4,10 +4,6 @@ #include "core/inspector/InspectorTaskRunner.h" -#include "wtf/Deque.h" -#include "wtf/ThreadingPrimitives.h" -#include <v8.h> - namespace blink { InspectorTaskRunner::IgnoreInterruptsScope::IgnoreInterruptsScope(InspectorTaskRunner* taskRunner) @@ -23,32 +19,9 @@ m_taskRunner->m_ignoreInterrupts = m_wasIgnoring; } -class InspectorTaskRunner::ThreadSafeTaskQueue { - WTF_MAKE_NONCOPYABLE(ThreadSafeTaskQueue); -public: - ThreadSafeTaskQueue() { } - PassOwnPtr<Task> tryTake() - { - MutexLocker lock(m_mutex); - if (m_queue.isEmpty()) - return nullptr; - return m_queue.takeFirst().release(); - } - void append(PassOwnPtr<Task> task) - { - MutexLocker lock(m_mutex); - m_queue.append(task); - } -private: - Mutex m_mutex; - Deque<OwnPtr<Task>> m_queue; -}; - - -InspectorTaskRunner::InspectorTaskRunner(v8::Isolate* isolate) - : m_isolate(isolate) - , m_taskQueue(adoptPtr(new ThreadSafeTaskQueue)) - , m_ignoreInterrupts(false) +InspectorTaskRunner::InspectorTaskRunner() + : m_ignoreInterrupts(false) + , m_killed(false) { } @@ -56,19 +29,50 @@ { } -void InspectorTaskRunner::interruptAndRun(PassOwnPtr<Task> task) +void InspectorTaskRunner::appendTask(PassOwnPtr<Task> task) { - m_taskQueue->append(task); - m_isolate->RequestInterrupt(&v8InterruptCallback, this); + MutexLocker lock(m_mutex); + m_queue.append(task); + m_condition.signal(); } -void InspectorTaskRunner::runPendingTasks() +PassOwnPtr<InspectorTaskRunner::Task> InspectorTaskRunner::takeNextTask(InspectorTaskRunner::WaitMode waitMode) +{ + MutexLocker lock(m_mutex); + bool timedOut = false; + + static double infiniteTime = std::numeric_limits<double>::max(); + double absoluteTime = waitMode == WaitForTask ? infiniteTime : 0.0; + while (!m_killed && !timedOut && m_queue.isEmpty()) + timedOut = !m_condition.timedWait(m_mutex, absoluteTime); + ASSERT(!timedOut || absoluteTime != infiniteTime); + + if (m_killed || timedOut) + return nullptr; + + ASSERT_WITH_SECURITY_IMPLICATION(!m_queue.isEmpty()); + return m_queue.takeFirst().release(); +} + +void InspectorTaskRunner::kill() +{ + MutexLocker lock(m_mutex); + m_killed = true; + m_condition.broadcast(); +} + +void InspectorTaskRunner::interruptAndRunAllTasksDontWait(v8::Isolate* isolate) +{ + isolate->RequestInterrupt(&v8InterruptCallback, this); +} + +void InspectorTaskRunner::runAllTasksDontWait() { while (true) { - OwnPtr<Task> task = m_taskQueue->tryTake(); + OwnPtr<Task> task = takeNextTask(DontWaitForTask); if (!task) return; - task->run(); + (*task)(); } } @@ -77,7 +81,7 @@ InspectorTaskRunner* runner = static_cast<InspectorTaskRunner*>(data); if (runner->m_ignoreInterrupts) return; - runner->runPendingTasks(); + runner->runAllTasksDontWait(); } } // namespace blink
diff --git a/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.h b/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.h index ec9066c2..39eab97b 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.h +++ b/third_party/WebKit/Source/core/inspector/InspectorTaskRunner.h
@@ -7,10 +7,13 @@ #include "core/CoreExport.h" #include "wtf/Allocator.h" +#include "wtf/Deque.h" #include "wtf/Forward.h" +#include "wtf/Functional.h" #include "wtf/Noncopyable.h" #include "wtf/OwnPtr.h" #include "wtf/PassOwnPtr.h" +#include "wtf/ThreadingPrimitives.h" #include <v8.h> namespace blink { @@ -19,19 +22,19 @@ WTF_MAKE_NONCOPYABLE(InspectorTaskRunner); USING_FAST_MALLOC(InspectorTaskRunner); public: - explicit InspectorTaskRunner(v8::Isolate*); + InspectorTaskRunner(); ~InspectorTaskRunner(); - class Task { - USING_FAST_MALLOC(Task); - public: - virtual ~Task() { } - virtual void run() = 0; - }; - // This method can be called on any thread. It is caller's responsibility to make sure that - // this V8Debugger and corresponding v8::Isolate exist while this method is running. - void interruptAndRun(PassOwnPtr<Task>); - void runPendingTasks(); + using Task = WTF::Closure; + void appendTask(PassOwnPtr<Task>); + + enum WaitMode { WaitForTask, DontWaitForTask }; + PassOwnPtr<Task> takeNextTask(WaitMode); + + void interruptAndRunAllTasksDontWait(v8::Isolate*); + void runAllTasksDontWait(); + + void kill(); class CORE_EXPORT IgnoreInterruptsScope final { USING_FAST_MALLOC(IgnoreInterruptsScope); @@ -47,10 +50,11 @@ private: static void v8InterruptCallback(v8::Isolate*, void* data); - v8::Isolate* m_isolate; - class ThreadSafeTaskQueue; - OwnPtr<ThreadSafeTaskQueue> m_taskQueue; bool m_ignoreInterrupts; + Mutex m_mutex; + ThreadCondition m_condition; + Deque<OwnPtr<Task>> m_queue; + bool m_killed; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp index 3ab12a76..ce9fef9 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp
@@ -43,7 +43,7 @@ namespace WorkerAgentState { static const char workerInspectionEnabled[] = "workerInspectionEnabled"; -static const char autoconnectToWorkers[] = "autoconnectToWorkers"; +static const char waitForDebuggerOnStart[] = "waitForDebuggerOnStart"; }; PassOwnPtrWillBeRawPtr<InspectorWorkerAgent> InspectorWorkerAgent::create(InspectedFrames* inspectedFrames, PageConsoleAgent* consoleAgent) @@ -61,7 +61,7 @@ InspectorWorkerAgent::~InspectorWorkerAgent() { #if !ENABLE(OILPAN) - m_instrumentingAgents->setInspectorWorkerAgent(0); + m_instrumentingAgents->setInspectorWorkerAgent(nullptr); #endif } @@ -87,28 +87,10 @@ void InspectorWorkerAgent::disable(ErrorString*) { m_state->setBoolean(WorkerAgentState::workerInspectionEnabled, false); - m_state->setBoolean(WorkerAgentState::autoconnectToWorkers, false); + m_state->setBoolean(WorkerAgentState::waitForDebuggerOnStart, false); destroyWorkerAgentClients(); } -void InspectorWorkerAgent::connectToWorker(ErrorString* error, const String& workerId) -{ - WorkerAgentClient* client = m_idToClient.get(workerId); - if (client) - client->connectToWorker(); - else - *error = "Worker is gone"; -} - -void InspectorWorkerAgent::disconnectFromWorker(ErrorString* error, const String& workerId) -{ - WorkerAgentClient* client = m_idToClient.get(workerId); - if (client) - client->dispose(); - else - *error = "Worker is gone"; -} - void InspectorWorkerAgent::sendMessageToWorker(ErrorString* error, const String& workerId, const String& message) { WorkerAgentClient* client = m_idToClient.get(workerId); @@ -118,9 +100,9 @@ *error = "Worker is gone"; } -void InspectorWorkerAgent::setAutoconnectToWorkers(ErrorString*, bool value) +void InspectorWorkerAgent::setWaitForDebuggerOnStart(ErrorString*, bool value) { - m_state->setBoolean(WorkerAgentState::autoconnectToWorkers, value); + m_state->setBoolean(WorkerAgentState::waitForDebuggerOnStart, value); } void InspectorWorkerAgent::setTracingSessionId(const String& sessionId) @@ -132,17 +114,17 @@ info.key->writeTimelineStartedEvent(sessionId, info.value.id); } -bool InspectorWorkerAgent::shouldPauseDedicatedWorkerOnStart() +bool InspectorWorkerAgent::shouldWaitForDebuggerOnWorkerStart() { - return m_state->booleanProperty(WorkerAgentState::autoconnectToWorkers, false); + return m_state->booleanProperty(WorkerAgentState::workerInspectionEnabled, false) && m_state->booleanProperty(WorkerAgentState::waitForDebuggerOnStart, false); } -void InspectorWorkerAgent::didStartWorker(WorkerInspectorProxy* workerInspectorProxy, const KURL& url) +void InspectorWorkerAgent::didStartWorker(WorkerInspectorProxy* workerInspectorProxy, const KURL& url, bool waitingForDebugger) { String id = "dedicated:" + IdentifiersFactory::createIdentifier(); m_workerInfos.set(workerInspectorProxy, WorkerInfo(url.getString(), id)); if (frontend() && m_state->booleanProperty(WorkerAgentState::workerInspectionEnabled, false)) - createWorkerAgentClient(workerInspectorProxy, url.getString(), id); + createWorkerAgentClient(workerInspectorProxy, url.getString(), id, waitingForDebugger); if (!m_tracingSessionId.isEmpty()) workerInspectorProxy->writeTimelineStartedEvent(m_tracingSessionId, id); } @@ -163,7 +145,7 @@ void InspectorWorkerAgent::createWorkerAgentClientsForExistingWorkers() { for (auto& info : m_workerInfos) - createWorkerAgentClient(info.key, info.value.url, info.value.id); + createWorkerAgentClient(info.key, info.value.url, info.value.id, false); } void InspectorWorkerAgent::destroyWorkerAgentClients() @@ -189,17 +171,15 @@ m_workerInfos.clear(); } -void InspectorWorkerAgent::createWorkerAgentClient(WorkerInspectorProxy* workerInspectorProxy, const String& url, const String& id) +void InspectorWorkerAgent::createWorkerAgentClient(WorkerInspectorProxy* workerInspectorProxy, const String& url, const String& id, bool waitingForDebugger) { OwnPtrWillBeRawPtr<WorkerAgentClient> client = WorkerAgentClient::create(frontend(), workerInspectorProxy, id, m_consoleAgent); WorkerAgentClient* rawClient = client.get(); m_idToClient.set(id, client.release()); + rawClient->connectToWorker(); ASSERT(frontend()); - bool autoconnectToWorkers = m_state->booleanProperty(WorkerAgentState::autoconnectToWorkers, false); - if (autoconnectToWorkers) - rawClient->connectToWorker(); - frontend()->workerCreated(id, url, autoconnectToWorkers); + frontend()->workerCreated(id, url, waitingForDebugger); } DEFINE_TRACE(InspectorWorkerAgent) @@ -257,6 +237,7 @@ { m_frontend->dispatchMessageFromWorker(m_id, message); } + void InspectorWorkerAgent::WorkerAgentClient::workerConsoleAgentEnabled(WorkerGlobalScopeProxy* proxy) { m_consoleAgent->workerConsoleAgentEnabled(proxy);
diff --git a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h index 84b0c3d..508dea80 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.h
@@ -58,16 +58,14 @@ void didCommitLoadForLocalFrame(LocalFrame*) override; // Called from InspectorInstrumentation - bool shouldPauseDedicatedWorkerOnStart(); - void didStartWorker(WorkerInspectorProxy*, const KURL&); + bool shouldWaitForDebuggerOnWorkerStart(); + void didStartWorker(WorkerInspectorProxy*, const KURL&, bool waitingForDebugger); void workerTerminated(WorkerInspectorProxy*); // Called from Dispatcher void enable(ErrorString*) override; - void connectToWorker(ErrorString*, const String& workerId) override; - void disconnectFromWorker(ErrorString*, const String& workerId) override; void sendMessageToWorker(ErrorString*, const String& workerId, const String& message) override; - void setAutoconnectToWorkers(ErrorString*, bool value) override; + void setWaitForDebuggerOnStart(ErrorString*, bool value) override; void setTracingSessionId(const String&); @@ -100,7 +98,7 @@ private: InspectorWorkerAgent(InspectedFrames*, PageConsoleAgent*); void createWorkerAgentClientsForExistingWorkers(); - void createWorkerAgentClient(WorkerInspectorProxy*, const String& url, const String& id); + void createWorkerAgentClient(WorkerInspectorProxy*, const String& url, const String& id, bool waitingForDebugger); void destroyWorkerAgentClients(); class WorkerInfo {
diff --git a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp index 15c1e3f6..c827274a 100644 --- a/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp +++ b/third_party/WebKit/Source/core/inspector/MainThreadDebugger.cpp
@@ -63,7 +63,7 @@ MainThreadDebugger::MainThreadDebugger(PassOwnPtr<ClientMessageLoop> clientMessageLoop, v8::Isolate* isolate) : ThreadDebugger(isolate) , m_clientMessageLoop(clientMessageLoop) - , m_taskRunner(adoptPtr(new InspectorTaskRunner(isolate))) + , m_taskRunner(adoptPtr(new InspectorTaskRunner())) { MutexLocker locker(creationMutex()); ASSERT(!s_instance); @@ -104,8 +104,10 @@ void MainThreadDebugger::interruptMainThreadAndRun(PassOwnPtr<InspectorTaskRunner::Task> task) { MutexLocker locker(creationMutex()); - if (s_instance) - s_instance->m_taskRunner->interruptAndRun(task); + if (s_instance) { + s_instance->m_taskRunner->appendTask(task); + s_instance->m_taskRunner->interruptAndRunAllTasksDontWait(s_instance->m_isolate); + } } void MainThreadDebugger::runMessageLoopOnPause(int contextGroupId)
diff --git a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp index 84a9434..1d10f94 100644 --- a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp +++ b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
@@ -92,7 +92,6 @@ void WorkerInspectorController::connectFrontend() { ASSERT(!m_frontend); - InspectorTaskRunner::IgnoreInterruptsScope scope(m_workerGlobalScope->thread()->inspectorTaskRunner()); m_frontend = adoptPtr(new protocol::Frontend(this)); m_backendDispatcher = protocol::Dispatcher::create(this); m_agents.registerInDispatcher(m_backendDispatcher.get()); @@ -104,7 +103,6 @@ { if (!m_frontend) return; - InspectorTaskRunner::IgnoreInterruptsScope scope(m_workerGlobalScope->thread()->inspectorTaskRunner()); m_backendDispatcher->clearFrontend(); m_backendDispatcher.clear(); m_agents.clearFrontend(); @@ -114,7 +112,6 @@ void WorkerInspectorController::dispatchMessageFromFrontend(const String& message) { - InspectorTaskRunner::IgnoreInterruptsScope scope(m_workerGlobalScope->thread()->inspectorTaskRunner()); if (m_backendDispatcher) { // sessionId will be overwritten by WebDevToolsAgent::sendProtocolNotifications call. m_backendDispatcher->dispatch(0, message); @@ -132,11 +129,6 @@ m_workerGlobalScope->thread()->stopRunningDebuggerTasksOnPause(); } -bool WorkerInspectorController::isRunRequired() -{ - return m_workerGlobalScope->thread()->isRunningDebuggerTasksOnPause(); -} - void WorkerInspectorController::sendProtocolResponse(int sessionId, int callId, PassOwnPtr<protocol::DictionaryValue> message) { // Worker messages are wrapped, no need to handle callId.
diff --git a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h index d59bef9..7157e5179 100644 --- a/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h +++ b/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
@@ -72,7 +72,6 @@ // InspectorRuntimeAgent::Client implementation. void resumeStartup() override; - bool isRunRequired() override; // protocol::FrontendChannel implementation. void sendProtocolResponse(int sessionId, int callId, PassOwnPtr<protocol::DictionaryValue> message) override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp index 050901b..c32c6c3 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp
@@ -834,7 +834,7 @@ if (logicalHeight() > 0 || isTable() || borderAndPaddingLogicalHeight() || style()->logicalMinHeight().isPositive() - || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE) + || style()->marginBeforeCollapse() == MarginCollapseSeparate || style()->marginAfterCollapse() == MarginCollapseSeparate) return false; Length logicalHeightLength = style()->logicalHeight(); @@ -954,7 +954,7 @@ // If we use border-box sizing, have percentage padding, and our parent has changed width then the width available to our children has changed even // though our own width has remained the same. - widthAvailableToChildrenHasChanged |= style()->boxSizing() == BORDER_BOX && needsPreferredWidthsRecalculation() && view()->layoutState()->containingBlockLogicalWidthChanged(); + widthAvailableToChildrenHasChanged |= style()->boxSizing() == BoxSizingBorderBox && needsPreferredWidthsRecalculation() && view()->layoutState()->containingBlockLogicalWidthChanged(); return widthAvailableToChildrenHasChanged; } @@ -1050,7 +1050,7 @@ static inline bool changeInAvailableLogicalHeightAffectsChild(LayoutBlock* parent, LayoutBox& child) { - if (parent->style()->boxSizing() != BORDER_BOX) + if (parent->style()->boxSizing() != BoxSizingBorderBox) return false; return parent->style()->isHorizontalWritingMode() && !child.style()->isHorizontalWritingMode(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp index 5c07b9d..b901749 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
@@ -1068,14 +1068,14 @@ ASSERT(blockFlow->isLayoutView() || blockFlow->parent()); m_canCollapseWithChildren = !blockFlow->createsNewFormattingContext() && !blockFlow->isLayoutFlowThread() && !blockFlow->isLayoutView(); - m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle.marginBeforeCollapse() != MSEPARATE; + m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle.marginBeforeCollapse() != MarginCollapseSeparate; // If any height other than auto is specified in CSS, then we don't collapse our bottom // margins with our children's margins. To do otherwise would be to risk odd visual // effects when the children overflow out of the parent block and yet still collapse // with it. We also don't collapse if we have any bottom border/padding. m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding - && (blockStyle.logicalHeight().isAuto() && !blockStyle.logicalHeight().value()) && blockStyle.marginAfterCollapse() != MSEPARATE; + && (blockStyle.logicalHeight().isAuto() && !blockStyle.logicalHeight().value()) && blockStyle.marginAfterCollapse() != MarginCollapseSeparate; m_quirkContainer = blockFlow->isTableCell() || blockFlow->isBody(); @@ -1372,7 +1372,7 @@ marginInfo.setAtBeforeSideOfBlock(false); // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value. - setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD); + setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MarginCollapseDiscard); } return yPos + heightIncrease; @@ -1409,12 +1409,12 @@ // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky. // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing. // FIXME: Use writing mode independent accessor for marginBeforeCollapse. - if ((document().inQuirksMode() && hasMarginBeforeQuirk(&child) && (isTableCell() || isBody())) || child.style()->marginBeforeCollapse() == MSEPARATE) + if ((document().inQuirksMode() && hasMarginBeforeQuirk(&child) && (isTableCell() || isBody())) || child.style()->marginBeforeCollapse() == MarginCollapseSeparate) return; // The margins are discarded by a child that specified -webkit-margin-collapse: discard. // FIXME: Use writing mode independent accessor for marginBeforeCollapse. - if (child.style()->marginBeforeCollapse() == MDISCARD) { + if (child.style()->marginBeforeCollapse() == MarginCollapseDiscard) { positiveMarginBefore = LayoutUnit(); negativeMarginBefore = LayoutUnit(); discardMarginBefore = true; @@ -1566,7 +1566,7 @@ void LayoutBlockFlow::setMustDiscardMarginBefore(bool value) { - if (style()->marginBeforeCollapse() == MDISCARD) { + if (style()->marginBeforeCollapse() == MarginCollapseDiscard) { ASSERT(value); return; } @@ -1582,7 +1582,7 @@ void LayoutBlockFlow::setMustDiscardMarginAfter(bool value) { - if (style()->marginAfterCollapse() == MDISCARD) { + if (style()->marginAfterCollapse() == MarginCollapseDiscard) { ASSERT(value); return; } @@ -1598,21 +1598,21 @@ bool LayoutBlockFlow::mustDiscardMarginBefore() const { - return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore); + return style()->marginBeforeCollapse() == MarginCollapseDiscard || (m_rareData && m_rareData->m_discardMarginBefore); } bool LayoutBlockFlow::mustDiscardMarginAfter() const { - return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter); + return style()->marginAfterCollapse() == MarginCollapseDiscard || (m_rareData && m_rareData->m_discardMarginAfter); } bool LayoutBlockFlow::mustDiscardMarginBeforeForChild(const LayoutBox& child) const { ASSERT(!child.selfNeedsLayout()); if (!child.isWritingModeRoot()) - return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginBefore() : (child.style()->marginBeforeCollapse() == MDISCARD); + return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginBefore() : (child.style()->marginBeforeCollapse() == MarginCollapseDiscard); if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) - return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginAfter() : (child.style()->marginAfterCollapse() == MDISCARD); + return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginAfter() : (child.style()->marginAfterCollapse() == MarginCollapseDiscard); // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end. // In case the boxes are perpendicular we assume the property is not specified. @@ -1623,9 +1623,9 @@ { ASSERT(!child.selfNeedsLayout()); if (!child.isWritingModeRoot()) - return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginAfter() : (child.style()->marginAfterCollapse() == MDISCARD); + return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginAfter() : (child.style()->marginAfterCollapse() == MarginCollapseDiscard); if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) - return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginBefore() : (child.style()->marginBeforeCollapse() == MDISCARD); + return child.isLayoutBlockFlow() ? toLayoutBlockFlow(&child)->mustDiscardMarginBefore() : (child.style()->marginBeforeCollapse() == MarginCollapseDiscard); // FIXME: See |mustDiscardMarginBeforeForChild| above. return false; @@ -1658,9 +1658,9 @@ ASSERT(!child.selfNeedsLayout()); const ComputedStyle& childStyle = child.styleRef(); if (!child.isWritingModeRoot()) - return childStyle.marginBeforeCollapse() == MSEPARATE; + return childStyle.marginBeforeCollapse() == MarginCollapseSeparate; if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) - return childStyle.marginAfterCollapse() == MSEPARATE; + return childStyle.marginAfterCollapse() == MarginCollapseSeparate; // FIXME: See |mustDiscardMarginBeforeForChild| above. return false; @@ -1671,9 +1671,9 @@ ASSERT(!child.selfNeedsLayout()); const ComputedStyle& childStyle = child.styleRef(); if (!child.isWritingModeRoot()) - return childStyle.marginAfterCollapse() == MSEPARATE; + return childStyle.marginAfterCollapse() == MarginCollapseSeparate; if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) - return childStyle.marginBeforeCollapse() == MSEPARATE; + return childStyle.marginBeforeCollapse() == MarginCollapseSeparate; // FIXME: See |mustDiscardMarginBeforeForChild| above. return false;
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.cpp b/third_party/WebKit/Source/core/layout/LayoutBox.cpp index d125094..469e8e29 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBox.cpp
@@ -1159,7 +1159,7 @@ { LayoutUnit bordersPlusPadding = borderAndPaddingLogicalWidth(); LayoutUnit result(width); - if (style()->boxSizing() == CONTENT_BOX) + if (style()->boxSizing() == BoxSizingContentBox) return result + bordersPlusPadding; return std::max(result, bordersPlusPadding); } @@ -1168,7 +1168,7 @@ { LayoutUnit bordersPlusPadding = borderAndPaddingLogicalHeight(); LayoutUnit result(height); - if (style()->boxSizing() == CONTENT_BOX) + if (style()->boxSizing() == BoxSizingContentBox) return result + bordersPlusPadding; return std::max(result, bordersPlusPadding); } @@ -1176,7 +1176,7 @@ LayoutUnit LayoutBox::adjustContentBoxLogicalWidthForBoxSizing(float width) const { LayoutUnit result(width); - if (style()->boxSizing() == BORDER_BOX) + if (style()->boxSizing() == BoxSizingBorderBox) result -= borderAndPaddingLogicalWidth(); return std::max(LayoutUnit(), result); } @@ -1184,7 +1184,7 @@ LayoutUnit LayoutBox::adjustContentBoxLogicalHeightForBoxSizing(float height) const { LayoutUnit result(height); - if (style()->boxSizing() == BORDER_BOX) + if (style()->boxSizing() == BoxSizingBorderBox) result -= borderAndPaddingLogicalHeight(); return std::max(LayoutUnit(), result); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.cpp b/third_party/WebKit/Source/core/layout/LayoutTable.cpp index 6e9bc1b..e551da7 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTable.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTable.cpp
@@ -335,7 +335,7 @@ // HTML tables' width styles already include borders and paddings, but CSS tables' width styles do not. LayoutUnit borders; bool isCSSTable = !isHTMLTableElement(node()); - if (isCSSTable && styleLogicalWidth.isSpecified() && styleLogicalWidth.isPositive() && style()->boxSizing() == CONTENT_BOX) + if (isCSSTable && styleLogicalWidth.isSpecified() && styleLogicalWidth.isPositive() && style()->boxSizing() == BoxSizingContentBox) borders = borderStart() + borderEnd() + (collapseBorders() ? LayoutUnit() : paddingStart() + paddingEnd()); return minimumValueForLength(styleLogicalWidth, availableWidth) + borders; @@ -351,7 +351,7 @@ // HTML tables size as though CSS height includes border/padding, CSS tables do not. LayoutUnit borders = LayoutUnit(); // FIXME: We cannot apply box-sizing: content-box on <table> which other browsers allow. - if (isHTMLTableElement(node()) || style()->boxSizing() == BORDER_BOX) { + if (isHTMLTableElement(node()) || style()->boxSizing() == BoxSizingBorderBox) { borders = borderAndPadding; } computedLogicalHeight = LayoutUnit(styleLogicalHeight.value() - borders); @@ -927,42 +927,42 @@ int borderWidth = 0; const BorderValue& tableStartBorder = style()->borderStart(); - if (tableStartBorder.style() == BHIDDEN) + if (tableStartBorder.style() == BorderStyleHidden) return 0; - if (tableStartBorder.style() > BHIDDEN) + if (tableStartBorder.style() > BorderStyleHidden) borderWidth = tableStartBorder.width(); // TODO(dgrogan): This logic doesn't properly account for the first column in the first column-group case. if (LayoutTableCol* column = colElementAtAbsoluteColumn(0).innermostColOrColGroup()) { // FIXME: We don't account for direction on columns and column groups. const BorderValue& columnAdjoiningBorder = column->style()->borderStart(); - if (columnAdjoiningBorder.style() == BHIDDEN) + if (columnAdjoiningBorder.style() == BorderStyleHidden) return 0; - if (columnAdjoiningBorder.style() > BHIDDEN) + if (columnAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, columnAdjoiningBorder.width()); } if (const LayoutTableSection* topNonEmptySection = this->topNonEmptySection()) { const BorderValue& sectionAdjoiningBorder = topNonEmptySection->borderAdjoiningTableStart(); - if (sectionAdjoiningBorder.style() == BHIDDEN) + if (sectionAdjoiningBorder.style() == BorderStyleHidden) return 0; - if (sectionAdjoiningBorder.style() > BHIDDEN) + if (sectionAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, sectionAdjoiningBorder.width()); if (const LayoutTableCell* adjoiningStartCell = topNonEmptySection->firstRowCellAdjoiningTableStart()) { // FIXME: Make this work with perpendicular and flipped cells. const BorderValue& startCellAdjoiningBorder = adjoiningStartCell->borderAdjoiningTableStart(); - if (startCellAdjoiningBorder.style() == BHIDDEN) + if (startCellAdjoiningBorder.style() == BorderStyleHidden) return 0; const BorderValue& firstRowAdjoiningBorder = adjoiningStartCell->row()->borderAdjoiningTableStart(); - if (firstRowAdjoiningBorder.style() == BHIDDEN) + if (firstRowAdjoiningBorder.style() == BorderStyleHidden) return 0; - if (startCellAdjoiningBorder.style() > BHIDDEN) + if (startCellAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, startCellAdjoiningBorder.width()); - if (firstRowAdjoiningBorder.style() > BHIDDEN) + if (firstRowAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, firstRowAdjoiningBorder.width()); } } @@ -981,9 +981,9 @@ int borderWidth = 0; const BorderValue& tableEndBorder = style()->borderEnd(); - if (tableEndBorder.style() == BHIDDEN) + if (tableEndBorder.style() == BorderStyleHidden) return 0; - if (tableEndBorder.style() > BHIDDEN) + if (tableEndBorder.style() > BorderStyleHidden) borderWidth = tableEndBorder.width(); unsigned endColumn = numEffectiveColumns() - 1; @@ -992,33 +992,33 @@ if (LayoutTableCol* column = colElementAtAbsoluteColumn(endColumn).innermostColOrColGroup()) { // FIXME: We don't account for direction on columns and column groups. const BorderValue& columnAdjoiningBorder = column->style()->borderEnd(); - if (columnAdjoiningBorder.style() == BHIDDEN) + if (columnAdjoiningBorder.style() == BorderStyleHidden) return 0; - if (columnAdjoiningBorder.style() > BHIDDEN) + if (columnAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, columnAdjoiningBorder.width()); } if (const LayoutTableSection* topNonEmptySection = this->topNonEmptySection()) { const BorderValue& sectionAdjoiningBorder = topNonEmptySection->borderAdjoiningTableEnd(); - if (sectionAdjoiningBorder.style() == BHIDDEN) + if (sectionAdjoiningBorder.style() == BorderStyleHidden) return 0; - if (sectionAdjoiningBorder.style() > BHIDDEN) + if (sectionAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, sectionAdjoiningBorder.width()); if (const LayoutTableCell* adjoiningEndCell = topNonEmptySection->firstRowCellAdjoiningTableEnd()) { // FIXME: Make this work with perpendicular and flipped cells. const BorderValue& endCellAdjoiningBorder = adjoiningEndCell->borderAdjoiningTableEnd(); - if (endCellAdjoiningBorder.style() == BHIDDEN) + if (endCellAdjoiningBorder.style() == BorderStyleHidden) return 0; const BorderValue& firstRowAdjoiningBorder = adjoiningEndCell->row()->borderAdjoiningTableEnd(); - if (firstRowAdjoiningBorder.style() == BHIDDEN) + if (firstRowAdjoiningBorder.style() == BorderStyleHidden) return 0; - if (endCellAdjoiningBorder.style() > BHIDDEN) + if (endCellAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, endCellAdjoiningBorder.width()); - if (firstRowAdjoiningBorder.style() > BHIDDEN) + if (firstRowAdjoiningBorder.style() > BorderStyleHidden) borderWidth = std::max(borderWidth, firstRowAdjoiningBorder.width()); } } @@ -1061,9 +1061,9 @@ return 0; // Overridden by hidden } const BorderValue& tb = style()->borderBefore(); - if (tb.style() == BHIDDEN) + if (tb.style() == BorderStyleHidden) return 0; - if (tb.style() > BHIDDEN) + if (tb.style() > BorderStyleHidden) borderWidth = std::max<int>(borderWidth, tb.width() / 2); return borderWidth; } @@ -1080,9 +1080,9 @@ return 0; // Overridden by hidden } const BorderValue& tb = style()->borderAfter(); - if (tb.style() == BHIDDEN) + if (tb.style() == BorderStyleHidden) return 0; - if (tb.style() > BHIDDEN) + if (tb.style() > BorderStyleHidden) borderWidth = std::max<int>(borderWidth, (tb.width() + 1) / 2); return borderWidth; } @@ -1095,9 +1095,9 @@ int borderWidth = 0; const BorderValue& tb = style()->borderStart(); - if (tb.style() == BHIDDEN) + if (tb.style() == BorderStyleHidden) return 0; - if (tb.style() > BHIDDEN) + if (tb.style() > BorderStyleHidden) borderWidth = (tb.width() + (style()->isLeftToRightDirection() ? 0 : 1)) / 2; bool allHidden = true; @@ -1122,9 +1122,9 @@ int borderWidth = 0; const BorderValue& tb = style()->borderEnd(); - if (tb.style() == BHIDDEN) + if (tb.style() == BorderStyleHidden) return 0; - if (tb.style() > BHIDDEN) + if (tb.style() > BorderStyleHidden) borderWidth = (tb.width() + (style()->isLeftToRightDirection() ? 1 : 0)) / 2; bool allHidden = true;
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp index 5e8e9eefd..c985282e 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp
@@ -430,21 +430,21 @@ return -1; // Rule #1 above. - if (border2.style() == BHIDDEN) { - if (border1.style() == BHIDDEN) + if (border2.style() == BorderStyleHidden) { + if (border1.style() == BorderStyleHidden) return 0; return -1; } - if (border1.style() == BHIDDEN) + if (border1.style() == BorderStyleHidden) return 1; // Rule #2 above. A style of 'none' has lowest priority and always loses to any other border. - if (border2.style() == BNONE) { - if (border1.style() == BNONE) + if (border2.style() == BorderStyleNone) { + if (border1.style() == BorderStyleNone) return 0; return 1; } - if (border1.style() == BNONE) + if (border1.style() == BorderStyleNone) return -1; // The first part of rule #3 above. Wider borders win. @@ -496,12 +496,12 @@ // (1) Our start border. int startColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderStartColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; int endColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderEndColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; - CollapsedBorderValue result(style()->borderStart(), includeColor ? resolveColor(startColorProperty) : Color(), BCELL); + CollapsedBorderValue result(style()->borderStart(), includeColor ? resolveColor(startColorProperty) : Color(), BorderPrecedenceCell); // (2) The end border of the preceding cell. LayoutTableCell* cellBefore = table->cellBefore(this); if (cellBefore) { - CollapsedBorderValue cellBeforeAdjoiningBorder = CollapsedBorderValue(cellBefore->borderAdjoiningCellAfter(this), includeColor ? cellBefore->resolveColor(endColorProperty) : Color(), BCELL); + CollapsedBorderValue cellBeforeAdjoiningBorder = CollapsedBorderValue(cellBefore->borderAdjoiningCellAfter(this), includeColor ? cellBefore->resolveColor(endColorProperty) : Color(), BorderPrecedenceCell); // |result| should be the 2nd argument as |cellBefore| should win in case of equality per CSS 2.1 (Border conflict resolution, point 4). result = chooseBorder(cellBeforeAdjoiningBorder, result); if (!result.exists()) @@ -511,12 +511,12 @@ bool startBorderAdjoinsTable = hasStartBorderAdjoiningTable(); if (startBorderAdjoinsTable) { // (3) Our row's start border. - result = chooseBorder(result, CollapsedBorderValue(row()->borderAdjoiningStartCell(this), includeColor ? parent()->resolveColor(startColorProperty) : Color(), BROW)); + result = chooseBorder(result, CollapsedBorderValue(row()->borderAdjoiningStartCell(this), includeColor ? parent()->resolveColor(startColorProperty) : Color(), BorderPrecedenceRow)); if (!result.exists()) return result; // (4) Our row group's start border. - result = chooseBorder(result, CollapsedBorderValue(section()->borderAdjoiningStartCell(this), includeColor ? section()->resolveColor(startColorProperty) : Color(), BROWGROUP)); + result = chooseBorder(result, CollapsedBorderValue(section()->borderAdjoiningStartCell(this), includeColor ? section()->resolveColor(startColorProperty) : Color(), BorderPrecedenceRowGroup)); if (!result.exists()) return result; } @@ -525,7 +525,7 @@ LayoutTable::ColAndColGroup colAndColGroup = table->colElementAtAbsoluteColumn(absoluteColumnIndex()); if (colAndColGroup.colgroup && colAndColGroup.adjoinsStartBorderOfColGroup) { // Only apply the colgroup's border if this cell touches the colgroup edge. - result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellStartBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(startColorProperty) : Color(), BCOLGROUP)); + result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellStartBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(startColorProperty) : Color(), BorderPrecedenceColumnGroup)); if (!result.exists()) return result; } @@ -533,7 +533,7 @@ // Always apply the col's border irrespective of whether this cell touches it. This is per HTML5: // "For the purposes of the CSS table model, the col element is expected to be treated as if it // "was present as many times as its span attribute specifies". - result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellStartBorder(this), includeColor ? colAndColGroup.col->resolveColor(startColorProperty) : Color(), BCOL)); + result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellStartBorder(this), includeColor ? colAndColGroup.col->resolveColor(startColorProperty) : Color(), BorderPrecedenceColumn)); if (!result.exists()) return result; } @@ -543,7 +543,7 @@ LayoutTable::ColAndColGroup colAndColGroup = table->colElementAtAbsoluteColumn(absoluteColumnIndex() - 1); // Only apply the colgroup's border if this cell touches the colgroup edge. if (colAndColGroup.colgroup && colAndColGroup.adjoinsEndBorderOfColGroup) { - result = chooseBorder(CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellEndBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(endColorProperty) : Color(), BCOLGROUP), result); + result = chooseBorder(CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellEndBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(endColorProperty) : Color(), BorderPrecedenceColumnGroup), result); if (!result.exists()) return result; } @@ -551,7 +551,7 @@ // "For the purposes of the CSS table model, the col element is expected to be treated as if it // "was present as many times as its span attribute specifies". if (colAndColGroup.col) { - result = chooseBorder(CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellAfter(this), includeColor ? colAndColGroup.col->resolveColor(endColorProperty) : Color(), BCOL), result); + result = chooseBorder(CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellAfter(this), includeColor ? colAndColGroup.col->resolveColor(endColorProperty) : Color(), BorderPrecedenceColumn), result); if (!result.exists()) return result; } @@ -559,7 +559,7 @@ if (startBorderAdjoinsTable) { // (7) The table's start border. - result = chooseBorder(result, CollapsedBorderValue(table->tableStartBorderAdjoiningCell(this), includeColor ? table->resolveColor(startColorProperty) : Color(), BTABLE)); + result = chooseBorder(result, CollapsedBorderValue(table->tableStartBorderAdjoiningCell(this), includeColor ? table->resolveColor(startColorProperty) : Color(), BorderPrecedenceTable)); if (!result.exists()) return result; } @@ -578,12 +578,12 @@ // (1) Our end border. int startColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderStartColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; int endColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderEndColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; - CollapsedBorderValue result = CollapsedBorderValue(style()->borderEnd(), includeColor ? resolveColor(endColorProperty) : Color(), BCELL); + CollapsedBorderValue result = CollapsedBorderValue(style()->borderEnd(), includeColor ? resolveColor(endColorProperty) : Color(), BorderPrecedenceCell); // (2) The start border of the following cell. if (!isEndColumn) { if (LayoutTableCell* cellAfter = table->cellAfter(this)) { - CollapsedBorderValue cellAfterAdjoiningBorder = CollapsedBorderValue(cellAfter->borderAdjoiningCellBefore(this), includeColor ? cellAfter->resolveColor(startColorProperty) : Color(), BCELL); + CollapsedBorderValue cellAfterAdjoiningBorder = CollapsedBorderValue(cellAfter->borderAdjoiningCellBefore(this), includeColor ? cellAfter->resolveColor(startColorProperty) : Color(), BorderPrecedenceCell); result = chooseBorder(result, cellAfterAdjoiningBorder); if (!result.exists()) return result; @@ -593,12 +593,12 @@ bool endBorderAdjoinsTable = hasEndBorderAdjoiningTable(); if (endBorderAdjoinsTable) { // (3) Our row's end border. - result = chooseBorder(result, CollapsedBorderValue(row()->borderAdjoiningEndCell(this), includeColor ? parent()->resolveColor(endColorProperty) : Color(), BROW)); + result = chooseBorder(result, CollapsedBorderValue(row()->borderAdjoiningEndCell(this), includeColor ? parent()->resolveColor(endColorProperty) : Color(), BorderPrecedenceRow)); if (!result.exists()) return result; // (4) Our row group's end border. - result = chooseBorder(result, CollapsedBorderValue(section()->borderAdjoiningEndCell(this), includeColor ? section()->resolveColor(endColorProperty) : Color(), BROWGROUP)); + result = chooseBorder(result, CollapsedBorderValue(section()->borderAdjoiningEndCell(this), includeColor ? section()->resolveColor(endColorProperty) : Color(), BorderPrecedenceRowGroup)); if (!result.exists()) return result; } @@ -607,7 +607,7 @@ LayoutTable::ColAndColGroup colAndColGroup = table->colElementAtAbsoluteColumn(absoluteColumnIndex() + colSpan() - 1); if (colAndColGroup.colgroup && colAndColGroup.adjoinsEndBorderOfColGroup) { // Only apply the colgroup's border if this cell touches the colgroup edge. - result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellEndBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(endColorProperty) : Color(), BCOLGROUP)); + result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellEndBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(endColorProperty) : Color(), BorderPrecedenceColumnGroup)); if (!result.exists()) return result; } @@ -615,7 +615,7 @@ // Always apply the col's border irrespective of whether this cell touches it. This is per HTML5: // "For the purposes of the CSS table model, the col element is expected to be treated as if it // "was present as many times as its span attribute specifies". - result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellEndBorder(this), includeColor ? colAndColGroup.col->resolveColor(endColorProperty) : Color(), BCOL)); + result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellEndBorder(this), includeColor ? colAndColGroup.col->resolveColor(endColorProperty) : Color(), BorderPrecedenceColumn)); if (!result.exists()) return result; } @@ -625,7 +625,7 @@ LayoutTable::ColAndColGroup colAndColGroup = table->colElementAtAbsoluteColumn(absoluteColumnIndex() + colSpan()); if (colAndColGroup.colgroup && colAndColGroup.adjoinsStartBorderOfColGroup) { // Only apply the colgroup's border if this cell touches the colgroup edge. - result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellStartBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(startColorProperty) : Color(), BCOLGROUP)); + result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.colgroup->borderAdjoiningCellStartBorder(this), includeColor ? colAndColGroup.colgroup->resolveColor(startColorProperty) : Color(), BorderPrecedenceColumnGroup)); if (!result.exists()) return result; } @@ -633,7 +633,7 @@ // Always apply the col's border irrespective of whether this cell touches it. This is per HTML5: // "For the purposes of the CSS table model, the col element is expected to be treated as if it // "was present as many times as its span attribute specifies". - result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellBefore(this), includeColor ? colAndColGroup.col->resolveColor(startColorProperty) : Color(), BCOL)); + result = chooseBorder(result, CollapsedBorderValue(colAndColGroup.col->borderAdjoiningCellBefore(this), includeColor ? colAndColGroup.col->resolveColor(startColorProperty) : Color(), BorderPrecedenceColumn)); if (!result.exists()) return result; } @@ -641,7 +641,7 @@ if (endBorderAdjoinsTable) { // (7) The table's end border. - result = chooseBorder(result, CollapsedBorderValue(table->tableEndBorderAdjoiningCell(this), includeColor ? table->resolveColor(endColorProperty) : Color(), BTABLE)); + result = chooseBorder(result, CollapsedBorderValue(table->tableEndBorderAdjoiningCell(this), includeColor ? table->resolveColor(endColorProperty) : Color(), BorderPrecedenceTable)); if (!result.exists()) return result; } @@ -657,18 +657,18 @@ // (1) Our before border. int beforeColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderBeforeColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; int afterColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderAfterColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; - CollapsedBorderValue result = CollapsedBorderValue(style()->borderBefore(), includeColor ? resolveColor(beforeColorProperty) : Color(), BCELL); + CollapsedBorderValue result = CollapsedBorderValue(style()->borderBefore(), includeColor ? resolveColor(beforeColorProperty) : Color(), BorderPrecedenceCell); LayoutTableCell* prevCell = table->cellAbove(this); if (prevCell) { // (2) A before cell's after border. - result = chooseBorder(CollapsedBorderValue(prevCell->style()->borderAfter(), includeColor ? prevCell->resolveColor(afterColorProperty) : Color(), BCELL), result); + result = chooseBorder(CollapsedBorderValue(prevCell->style()->borderAfter(), includeColor ? prevCell->resolveColor(afterColorProperty) : Color(), BorderPrecedenceCell), result); if (!result.exists()) return result; } // (3) Our row's before border. - result = chooseBorder(result, CollapsedBorderValue(parent()->style()->borderBefore(), includeColor ? parent()->resolveColor(beforeColorProperty) : Color(), BROW)); + result = chooseBorder(result, CollapsedBorderValue(parent()->style()->borderBefore(), includeColor ? parent()->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceRow)); if (!result.exists()) return result; @@ -681,7 +681,7 @@ prevRow = prevCell->section()->lastRow(); if (prevRow) { - result = chooseBorder(CollapsedBorderValue(prevRow->style()->borderAfter(), includeColor ? prevRow->resolveColor(afterColorProperty) : Color(), BROW), result); + result = chooseBorder(CollapsedBorderValue(prevRow->style()->borderAfter(), includeColor ? prevRow->resolveColor(afterColorProperty) : Color(), BorderPrecedenceRow), result); if (!result.exists()) return result; } @@ -691,14 +691,14 @@ LayoutTableSection* currSection = section(); if (!rowIndex()) { // (5) Our row group's before border. - result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderBefore(), includeColor ? currSection->resolveColor(beforeColorProperty) : Color(), BROWGROUP)); + result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderBefore(), includeColor ? currSection->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceRowGroup)); if (!result.exists()) return result; // (6) Previous row group's after border. currSection = table->sectionAbove(currSection, SkipEmptySections); if (currSection) { - result = chooseBorder(CollapsedBorderValue(currSection->style()->borderAfter(), includeColor ? currSection->resolveColor(afterColorProperty) : Color(), BROWGROUP), result); + result = chooseBorder(CollapsedBorderValue(currSection->style()->borderAfter(), includeColor ? currSection->resolveColor(afterColorProperty) : Color(), BorderPrecedenceRowGroup), result); if (!result.exists()) return result; } @@ -708,18 +708,18 @@ // (8) Our column and column group's before borders. LayoutTableCol* colElt = table->colElementAtAbsoluteColumn(absoluteColumnIndex()).innermostColOrColGroup(); if (colElt) { - result = chooseBorder(result, CollapsedBorderValue(colElt->style()->borderBefore(), includeColor ? colElt->resolveColor(beforeColorProperty) : Color(), BCOL)); + result = chooseBorder(result, CollapsedBorderValue(colElt->style()->borderBefore(), includeColor ? colElt->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceColumn)); if (!result.exists()) return result; if (LayoutTableCol* enclosingColumnGroup = colElt->enclosingColumnGroup()) { - result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->style()->borderBefore(), includeColor ? enclosingColumnGroup->resolveColor(beforeColorProperty) : Color(), BCOLGROUP)); + result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->style()->borderBefore(), includeColor ? enclosingColumnGroup->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceColumnGroup)); if (!result.exists()) return result; } } // (9) The table's before border. - result = chooseBorder(result, CollapsedBorderValue(table->style()->borderBefore(), includeColor ? table->resolveColor(beforeColorProperty) : Color(), BTABLE)); + result = chooseBorder(result, CollapsedBorderValue(table->style()->borderBefore(), includeColor ? table->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceTable)); if (!result.exists()) return result; } @@ -735,24 +735,24 @@ // (1) Our after border. int beforeColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderBeforeColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; int afterColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderAfterColor, styleForCellFlow().direction(), styleForCellFlow().getWritingMode()) : 0; - CollapsedBorderValue result = CollapsedBorderValue(style()->borderAfter(), includeColor ? resolveColor(afterColorProperty) : Color(), BCELL); + CollapsedBorderValue result = CollapsedBorderValue(style()->borderAfter(), includeColor ? resolveColor(afterColorProperty) : Color(), BorderPrecedenceCell); LayoutTableCell* nextCell = table->cellBelow(this); if (nextCell) { // (2) An after cell's before border. - result = chooseBorder(result, CollapsedBorderValue(nextCell->style()->borderBefore(), includeColor ? nextCell->resolveColor(beforeColorProperty) : Color(), BCELL)); + result = chooseBorder(result, CollapsedBorderValue(nextCell->style()->borderBefore(), includeColor ? nextCell->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceCell)); if (!result.exists()) return result; } // (3) Our row's after border. (FIXME: Deal with rowspan!) - result = chooseBorder(result, CollapsedBorderValue(parent()->style()->borderAfter(), includeColor ? parent()->resolveColor(afterColorProperty) : Color(), BROW)); + result = chooseBorder(result, CollapsedBorderValue(parent()->style()->borderAfter(), includeColor ? parent()->resolveColor(afterColorProperty) : Color(), BorderPrecedenceRow)); if (!result.exists()) return result; // (4) The next row's before border. if (nextCell) { - result = chooseBorder(result, CollapsedBorderValue(nextCell->parent()->style()->borderBefore(), includeColor ? nextCell->parent()->resolveColor(beforeColorProperty) : Color(), BROW)); + result = chooseBorder(result, CollapsedBorderValue(nextCell->parent()->style()->borderBefore(), includeColor ? nextCell->parent()->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceRow)); if (!result.exists()) return result; } @@ -761,14 +761,14 @@ LayoutTableSection* currSection = section(); if (rowIndex() + rowSpan() >= currSection->numRows()) { // (5) Our row group's after border. - result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderAfter(), includeColor ? currSection->resolveColor(afterColorProperty) : Color(), BROWGROUP)); + result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderAfter(), includeColor ? currSection->resolveColor(afterColorProperty) : Color(), BorderPrecedenceRowGroup)); if (!result.exists()) return result; // (6) Following row group's before border. currSection = table->sectionBelow(currSection, SkipEmptySections); if (currSection) { - result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderBefore(), includeColor ? currSection->resolveColor(beforeColorProperty) : Color(), BROWGROUP)); + result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderBefore(), includeColor ? currSection->resolveColor(beforeColorProperty) : Color(), BorderPrecedenceRowGroup)); if (!result.exists()) return result; } @@ -778,18 +778,18 @@ // (8) Our column and column group's after borders. LayoutTableCol* colElt = table->colElementAtAbsoluteColumn(absoluteColumnIndex()).innermostColOrColGroup(); if (colElt) { - result = chooseBorder(result, CollapsedBorderValue(colElt->style()->borderAfter(), includeColor ? colElt->resolveColor(afterColorProperty) : Color(), BCOL)); + result = chooseBorder(result, CollapsedBorderValue(colElt->style()->borderAfter(), includeColor ? colElt->resolveColor(afterColorProperty) : Color(), BorderPrecedenceColumn)); if (!result.exists()) return result; if (LayoutTableCol* enclosingColumnGroup = colElt->enclosingColumnGroup()) { - result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->style()->borderAfter(), includeColor ? enclosingColumnGroup->resolveColor(afterColorProperty) : Color(), BCOLGROUP)); + result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->style()->borderAfter(), includeColor ? enclosingColumnGroup->resolveColor(afterColorProperty) : Color(), BorderPrecedenceColumnGroup)); if (!result.exists()) return result; } } // (9) The table's after border. - result = chooseBorder(result, CollapsedBorderValue(table->style()->borderAfter(), includeColor ? table->resolveColor(afterColorProperty) : Color(), BTABLE)); + result = chooseBorder(result, CollapsedBorderValue(table->style()->borderAfter(), includeColor ? table->resolveColor(afterColorProperty) : Color(), BorderPrecedenceTable)); if (!result.exists()) return result; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.h b/third_party/WebKit/Source/core/layout/LayoutTableCell.h index 0e08f35..c47d0f80 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCell.h +++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.h
@@ -149,7 +149,7 @@ // In strict mode, box-sizing: content-box do the right thing and actually add in the border and padding. // Call computedCSSPadding* directly to avoid including implicitPadding. - if (!document().inQuirksMode() && style()->boxSizing() != BORDER_BOX) + if (!document().inQuirksMode() && style()->boxSizing() != BoxSizingBorderBox) styleLogicalHeight += (computedCSSPaddingBefore() + computedCSSPaddingAfter()).floor() + borderBefore() + borderAfter(); return styleLogicalHeight; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp index fbe4d93..89b925a 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp
@@ -1147,15 +1147,15 @@ int borderWidth = 0; const BorderValue& sb = side == BorderBefore ? style()->borderBefore() : style()->borderAfter(); - if (sb.style() == BHIDDEN) + if (sb.style() == BorderStyleHidden) return -1; - if (sb.style() > BHIDDEN) + if (sb.style() > BorderStyleHidden) borderWidth = sb.width(); const BorderValue& rb = side == BorderBefore ? firstRow()->style()->borderBefore() : lastRow()->style()->borderAfter(); - if (rb.style() == BHIDDEN) + if (rb.style() == BorderStyleHidden) return -1; - if (rb.style() > BHIDDEN && rb.width() > borderWidth) + if (rb.style() > BorderStyleHidden && rb.width() > borderWidth) borderWidth = rb.width(); bool allHidden = true; @@ -1169,18 +1169,18 @@ LayoutTableCol* col = table()->colElementAtAbsoluteColumn(c).innermostColOrColGroup(); if (col) { const BorderValue& gb = side == BorderBefore ? col->style()->borderBefore() : col->style()->borderAfter(); - if (gb.style() == BHIDDEN || cb.style() == BHIDDEN) + if (gb.style() == BorderStyleHidden || cb.style() == BorderStyleHidden) continue; allHidden = false; - if (gb.style() > BHIDDEN && gb.width() > borderWidth) + if (gb.style() > BorderStyleHidden && gb.width() > borderWidth) borderWidth = gb.width(); - if (cb.style() > BHIDDEN && cb.width() > borderWidth) + if (cb.style() > BorderStyleHidden && cb.width() > borderWidth) borderWidth = cb.width(); } else { - if (cb.style() == BHIDDEN) + if (cb.style() == BorderStyleHidden) continue; allHidden = false; - if (cb.style() > BHIDDEN && cb.width() > borderWidth) + if (cb.style() > BorderStyleHidden && cb.width() > borderWidth) borderWidth = cb.width(); } } @@ -1202,16 +1202,16 @@ int borderWidth = 0; const BorderValue& sb = side == BorderStart ? style()->borderStart() : style()->borderEnd(); - if (sb.style() == BHIDDEN) + if (sb.style() == BorderStyleHidden) return -1; - if (sb.style() > BHIDDEN) + if (sb.style() > BorderStyleHidden) borderWidth = sb.width(); if (LayoutTableCol* col = table()->colElementAtAbsoluteColumn(colIndex).innermostColOrColGroup()) { const BorderValue& gb = side == BorderStart ? col->style()->borderStart() : col->style()->borderEnd(); - if (gb.style() == BHIDDEN) + if (gb.style() == BorderStyleHidden) return -1; - if (gb.style() > BHIDDEN && gb.width() > borderWidth) + if (gb.style() > BorderStyleHidden && gb.width() > borderWidth) borderWidth = gb.width(); } @@ -1225,12 +1225,12 @@ const ComputedStyle& primaryCellParentStyle = current.primaryCell()->parent()->styleRef(); const BorderValue& cb = side == BorderStart ? primaryCellStyle.borderStart() : primaryCellStyle.borderEnd(); // FIXME: Make this work with perpendicular and flipped cells. const BorderValue& rb = side == BorderStart ? primaryCellParentStyle.borderStart() : primaryCellParentStyle.borderEnd(); - if (cb.style() == BHIDDEN || rb.style() == BHIDDEN) + if (cb.style() == BorderStyleHidden || rb.style() == BorderStyleHidden) continue; allHidden = false; - if (cb.style() > BHIDDEN && cb.width() > borderWidth) + if (cb.style() > BorderStyleHidden && cb.width() > borderWidth) borderWidth = cb.width(); - if (rb.style() > BHIDDEN && rb.width() > borderWidth) + if (rb.style() > BorderStyleHidden && rb.width() > borderWidth) borderWidth = rb.width(); } if (allHidden)
diff --git a/third_party/WebKit/Source/core/layout/LayoutThemeMac.mm b/third_party/WebKit/Source/core/layout/LayoutThemeMac.mm index 18dd4a89..27649cc 100644 --- a/third_party/WebKit/Source/core/layout/LayoutThemeMac.mm +++ b/third_party/WebKit/Source/core/layout/LayoutThemeMac.mm
@@ -848,13 +848,13 @@ style.resetBorder(); const short borderWidth = searchFieldBorderWidth * style.effectiveZoom(); style.setBorderLeftWidth(borderWidth); - style.setBorderLeftStyle(INSET); + style.setBorderLeftStyle(BorderStyleInset); style.setBorderRightWidth(borderWidth); - style.setBorderRightStyle(INSET); + style.setBorderRightStyle(BorderStyleInset); style.setBorderBottomWidth(borderWidth); - style.setBorderBottomStyle(INSET); + style.setBorderBottomStyle(BorderStyleInset); style.setBorderTopWidth(borderWidth); - style.setBorderTopStyle(INSET); + style.setBorderTopStyle(BorderStyleInset); // Override height. style.setHeight(Length(Auto));
diff --git a/third_party/WebKit/Source/core/layout/LayoutThemeTest.cpp b/third_party/WebKit/Source/core/layout/LayoutThemeTest.cpp index a3016fb..f75a85a 100644 --- a/third_party/WebKit/Source/core/layout/LayoutThemeTest.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutThemeTest.cpp
@@ -62,7 +62,7 @@ Color customColor = makeRGB(123, 145, 167); // Checking unfocused style. - EXPECT_EQ(BNONE, outlineStyle(span)); + EXPECT_EQ(BorderStyleNone, outlineStyle(span)); EXPECT_NE(customColor, outlineColor(span)); // Do focus. @@ -72,7 +72,7 @@ document().view()->updateAllLifecyclePhases(); // Checking focused style. - EXPECT_NE(BNONE, outlineStyle(span)); + EXPECT_NE(BorderStyleNone, outlineStyle(span)); EXPECT_NE(customColor, outlineColor(span)); // Change focus ring color. @@ -81,7 +81,7 @@ document().view()->updateAllLifecyclePhases(); // Check that the focus ring color is updated. - EXPECT_NE(BNONE, outlineStyle(span)); + EXPECT_NE(BorderStyleNone, outlineStyle(span)); EXPECT_EQ(customColor, outlineColor(span)); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp b/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp index 44f873d..00282c7 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTreeAsText.cpp
@@ -67,34 +67,34 @@ static void printBorderStyle(TextStream& ts, const EBorderStyle borderStyle) { switch (borderStyle) { - case BNONE: + case BorderStyleNone: ts << "none"; break; - case BHIDDEN: + case BorderStyleHidden: ts << "hidden"; break; - case INSET: + case BorderStyleInset: ts << "inset"; break; - case GROOVE: + case BorderStyleGroove: ts << "groove"; break; - case RIDGE: + case BorderStyleRidge: ts << "ridge"; break; - case OUTSET: + case BorderStyleOutset: ts << "outset"; break; - case DOTTED: + case BorderStyleDotted: ts << "dotted"; break; - case DASHED: + case BorderStyleDashed: ts << "dashed"; break; - case SOLID: + case BorderStyleSolid: ts << "solid"; break; - case DOUBLE: + case BorderStyleDouble: ts << "double"; break; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutView.cpp b/third_party/WebKit/Source/core/layout/LayoutView.cpp index 632261ac..b03b5ea 100644 --- a/third_party/WebKit/Source/core/layout/LayoutView.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutView.cpp
@@ -406,7 +406,7 @@ if (mode & TraverseDocumentBoundaries) { if (LayoutPart* parentDocLayoutObject = frame()->ownerLayoutObject()) { // A LayoutView is a containing block for fixed-position elements, so don't carry this state across frames. - mode &= !IsFixed; + mode &= ~IsFixed; parentDocLayoutObject->mapAncestorToLocal(ancestor, transformState, mode); transformState.move(parentDocLayoutObject->contentBoxOffset());
diff --git a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp index bb14a2d0..c6ad72e 100644 --- a/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp +++ b/third_party/WebKit/Source/core/layout/line/InlineFlowBox.cpp
@@ -317,7 +317,7 @@ // we know the inline began on this line (unless we are a continuation). LineBoxList* lineBoxList = lineBoxes(); if (!lineBoxList->firstLineBox()->isConstructed() && !getLineLayoutItem().isInlineElementContinuation()) { - if (getLineLayoutItem().style()->boxDecorationBreak() == DCLONE) + if (getLineLayoutItem().style()->boxDecorationBreak() == BoxDecorationBreakClone) includeLeftEdge = includeRightEdge = true; else if (ltr && lineBoxList->firstLineBox() == this) includeLeftEdge = true; @@ -335,7 +335,7 @@ // (2) The logicallyLastRun is not a descendant of this layout object. // (3) The logicallyLastRun is a descendant of this layout object, but it is the last child of this layout object and it does not wrap to the next line. // (4) The decoration break is set to clone therefore there will be borders on every sides. - if (getLineLayoutItem().style()->boxDecorationBreak() == DCLONE) { + if (getLineLayoutItem().style()->boxDecorationBreak() == BoxDecorationBreakClone) { includeLeftEdge = includeRightEdge = true; } else if (ltr) { if (!nextLineBox()
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp index 90dacf4..ec8cd68 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.cpp +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -240,7 +240,7 @@ void DocumentLoader::mainReceivedError(const ResourceError& error) { ASSERT(!error.isNull()); - ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame)); + ASSERT(!m_frame || !m_frame->page()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame)); if (m_applicationCacheHost) m_applicationCacheHost->failedLoadingMainResource(); if (!frameLoader()) @@ -297,7 +297,7 @@ void DocumentLoader::finishedLoading(double finishTime) { - ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame)); + ASSERT(!m_frame->page()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame)); RefPtrWillBeRawPtr<DocumentLoader> protect(this); @@ -347,7 +347,7 @@ cancelMainResourceLoad(ResourceError::cancelledError(requestURL)); return; } - if (!frameLoader()->shouldContinueForNavigationPolicy(m_request, SubstituteData(), this, CheckContentSecurityPolicy, m_navigationType, NavigationPolicyCurrentTab, replacesCurrentHistoryItem(), isClientRedirect(), nullptr)) { + if (!frameLoader()->shouldContinueForNavigationPolicy(m_request, SubstituteData(), this, CheckContentSecurityPolicy, m_navigationType, NavigationPolicyCurrentTab, replacesCurrentHistoryItem(), isClientRedirect())) { cancelMainResourceLoad(ResourceError::cancelledError(requestURL)); return; } @@ -446,7 +446,7 @@ if (it != response.httpHeaderFields().end()) m_suboriginName = SuboriginPolicy::parseSuboriginName(*frame()->document(), it->value); - ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading()); + ASSERT(!m_frame->page()->defersLoading()); m_response = response; @@ -530,7 +530,7 @@ ASSERT(length); ASSERT_UNUSED(resource, resource == m_mainResource); ASSERT(!m_response.isNull()); - ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading()); + ASSERT(!m_frame->page()->defersLoading()); if (m_inDataReceived) { // If this function is reentered, defer processing of the additional @@ -661,17 +661,6 @@ return m_substituteData.failingURL(); } -void DocumentLoader::setDefersLoading(bool defers) -{ - // Multiple frames may be loading the same main resource simultaneously. If deferral state changes, - // each frame's DocumentLoader will try to send a setDefersLoading() to the same underlying ResourceLoader. Ensure only - // the "owning" DocumentLoader does so, as setDefersLoading() is not resilient to setting the same value repeatedly. - if (mainResourceLoader() && mainResourceLoader()->isLoadedBy(m_fetcher.get())) - mainResourceLoader()->setDefersLoading(defers); - - m_fetcher->setDefersLoading(defers); -} - bool DocumentLoader::maybeLoadEmpty() { bool shouldLoadEmpty = !m_substituteData.isValid() && (m_request.url().isEmpty() || SchemeRegistry::shouldLoadURLSchemeAsEmptyDocument(m_request.url().protocol()));
diff --git a/third_party/WebKit/Source/core/loader/DocumentLoader.h b/third_party/WebKit/Source/core/loader/DocumentLoader.h index 2dec5ea6..16d968c 100644 --- a/third_party/WebKit/Source/core/loader/DocumentLoader.h +++ b/third_party/WebKit/Source/core/loader/DocumentLoader.h
@@ -109,8 +109,6 @@ NavigationType getNavigationType() const { return m_navigationType; } void setNavigationType(NavigationType navigationType) { m_navigationType = navigationType; } - void setDefersLoading(bool); - void startLoadingMainResource(); void cancelMainResourceLoad(const ResourceError&);
diff --git a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp index c0224cf9..b1da3cd 100644 --- a/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp +++ b/third_party/WebKit/Source/core/loader/FrameFetchContextTest.cpp
@@ -629,7 +629,7 @@ TEST_F(FrameFetchContextTest, SetIsExternalRequestForPrivateDocument) { - document->setHostedInReservedIPRange(true); + document->setAddressSpace(WebURLRequest::AddressSpacePrivate); EXPECT_EQ(WebURLRequest::AddressSpacePrivate, document->addressSpace()); struct TestCase { @@ -677,8 +677,7 @@ TEST_F(FrameFetchContextTest, SetIsExternalRequestForLocalDocument) { - document->setSecurityOrigin(SecurityOrigin::create(KURL(KURL(), "http://localhost/"))); - document->setHostedInReservedIPRange(true); + document->setAddressSpace(WebURLRequest::AddressSpaceLocal); EXPECT_EQ(WebURLRequest::AddressSpaceLocal, document->addressSpace()); struct TestCase {
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/third_party/WebKit/Source/core/loader/FrameLoader.cpp index cbc206b..89cbfe37 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.cpp +++ b/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -210,12 +210,11 @@ void FrameLoader::setDefersLoading(bool defers) { - if (m_documentLoader) - m_documentLoader->setDefersLoading(defers); if (m_provisionalDocumentLoader) - m_provisionalDocumentLoader->setDefersLoading(defers); + m_provisionalDocumentLoader->fetcher()->setDefersLoading(defers); if (Document* document = m_frame->document()) { + document->fetcher()->setDefersLoading(defers); if (defers) document->suspendScheduledTasks(); else @@ -1336,7 +1335,7 @@ bool FrameLoader::shouldContinueForNavigationPolicy(const ResourceRequest& request, const SubstituteData& substituteData, DocumentLoader* loader, ContentSecurityPolicyDisposition shouldCheckMainWorldContentSecurityPolicy, - NavigationType type, NavigationPolicy policy, bool replacesCurrentHistoryItem, bool isClientRedirect, HTMLFormElement* form) + NavigationType type, NavigationPolicy policy, bool replacesCurrentHistoryItem, bool isClientRedirect) { // Don't ask if we are loading an empty URL. if (request.url().isEmpty() || substituteData.isValid()) @@ -1366,12 +1365,6 @@ if (policy == NavigationPolicyHandledByClient) { // Mark the frame as loading since the embedder is handling the navigation. m_progressTracker->progressStarted(); - - // If this is a form submit, dispatch that a form is being submitted - // since the embedder is handling the navigation. - if (form) - client()->dispatchWillSubmitForm(form); - return false; } if (!LocalDOMWindow::allowPopUp(*m_frame) && !UserGestureIndicator::processingUserGesture()) @@ -1392,13 +1385,8 @@ frameLoadRequest.resourceRequest().setRequestContext(determineRequestContextFromNavigationType(navigationType)); frameLoadRequest.resourceRequest().setFrameType(m_frame->isMainFrame() ? WebURLRequest::FrameTypeTopLevel : WebURLRequest::FrameTypeNested); ResourceRequest& request = frameLoadRequest.resourceRequest(); - if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, - frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, - navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, - frameLoadRequest.clientRedirect() == ClientRedirect, frameLoadRequest.form())) { + if (!shouldContinueForNavigationPolicy(request, frameLoadRequest.substituteData(), nullptr, frameLoadRequest.shouldCheckMainWorldContentSecurityPolicy(), navigationType, navigationPolicy, type == FrameLoadTypeReplaceCurrentItem, frameLoadRequest.clientRedirect() == ClientRedirect)) return; - } - if (!shouldClose(navigationType == NavigationTypeReload)) return;
diff --git a/third_party/WebKit/Source/core/loader/FrameLoader.h b/third_party/WebKit/Source/core/loader/FrameLoader.h index 2c6fe36c..b948aac8 100644 --- a/third_party/WebKit/Source/core/loader/FrameLoader.h +++ b/third_party/WebKit/Source/core/loader/FrameLoader.h
@@ -51,7 +51,6 @@ namespace blink { class DocumentLoader; -class HTMLFormElement; class Frame; class FrameLoaderClient; class ProgressTracker; @@ -186,7 +185,7 @@ void restoreScrollPositionAndViewState(); bool shouldContinueForNavigationPolicy(const ResourceRequest&, const SubstituteData&, DocumentLoader*, ContentSecurityPolicyDisposition, - NavigationType, NavigationPolicy, bool shouldReplaceCurrentEntry, bool isClientRedirect, HTMLFormElement*); + NavigationType, NavigationPolicy, bool shouldReplaceCurrentEntry, bool isClientRedirect); DECLARE_TRACE();
diff --git a/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp b/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp index e3a84db..636d43a 100644 --- a/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp +++ b/third_party/WebKit/Source/core/origin_trials/OriginTrialContext.cpp
@@ -17,7 +17,7 @@ namespace { -const char kTrialMetaTagName[] = "origin-trials"; +const char kTrialHeaderName[] = "origin-trial"; String getCurrentOrigin(ExecutionContext* executionContext) { @@ -39,7 +39,7 @@ if (executionContext->isDocument()) { HTMLHeadElement* head = toDocument(executionContext)->head(); for (HTMLMetaElement* metaElement = head ? Traversal<HTMLMetaElement>::firstChild(*head) : 0; metaElement; metaElement = Traversal<HTMLMetaElement>::nextSibling(*metaElement)) { - if (equalIgnoringCase(metaElement->name(), kTrialMetaTagName)) { + if (equalIgnoringCase(metaElement->httpEquiv(), kTrialHeaderName)) { foundAnyToken = true; String tokenString = metaElement->content(); // Check with the validator service to verify the signature.
diff --git a/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp b/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp index 25c8865..64643512 100644 --- a/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp +++ b/third_party/WebKit/Source/core/origin_trials/OriginTrialContextTest.cpp
@@ -124,7 +124,7 @@ ASSERT_TRUE(head); RefPtrWillBeRawPtr<HTMLMetaElement> meta = HTMLMetaElement::create(document()); - meta->setAttribute(HTMLNames::nameAttr, "origin-trials"); + meta->setAttribute(HTMLNames::http_equivAttr, "origin-trial"); AtomicString value(token); meta->setAttribute(HTMLNames::contentAttr, value); head->appendChild(meta.release());
diff --git a/third_party/WebKit/Source/core/page/FocusController.cpp b/third_party/WebKit/Source/core/page/FocusController.cpp index bfc62ce3..279dc514 100644 --- a/third_party/WebKit/Source/core/page/FocusController.cpp +++ b/third_party/WebKit/Source/core/page/FocusController.cpp
@@ -28,13 +28,14 @@ #include "core/HTMLNames.h" #include "core/dom/AXObjectCache.h" +#include "core/dom/ContainerNode.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/ElementTraversal.h" -#include "core/dom/NodeTraversal.h" #include "core/dom/Range.h" #include "core/dom/shadow/ElementShadow.h" #include "core/dom/shadow/ShadowRoot.h" +#include "core/dom/shadow/SlotScopedTraversal.h" #include "core/editing/EditingUtilities.h" // For firstPositionInOrBeforeNode #include "core/editing/Editor.h" #include "core/editing/FrameSelection.h" @@ -49,6 +50,7 @@ #include "core/html/HTMLImageElement.h" #include "core/html/HTMLPlugInElement.h" #include "core/html/HTMLShadowElement.h" +#include "core/html/HTMLSlotElement.h" #include "core/html/HTMLTextFormControlElement.h" #include "core/input/EventHandler.h" #include "core/page/ChromeClient.h" @@ -69,89 +71,181 @@ return isActiveShadowInsertionPoint(element) && toHTMLShadowElement(element).olderShadowRoot(); } -class FocusNavigationScope { +class ScopedFocusNavigation { STACK_ALLOCATED(); public: - Element* firstElement() const; - Element* lastElement() const; + Element* currentElement() const; + void setCurrentElement(Element*); + void moveToNext(); + void moveToPrevious(); + void moveToFirst(); + void moveToLast(); Element* owner() const; - static FocusNavigationScope focusNavigationScopeOf(const Element&); - static FocusNavigationScope ownedByNonFocusableFocusScopeOwner(Element&); - static FocusNavigationScope ownedByShadowHost(const Element&); - static FocusNavigationScope ownedByShadowInsertionPoint(HTMLShadowElement&); - static FocusNavigationScope ownedByIFrame(const HTMLFrameOwnerElement&); + static ScopedFocusNavigation createScopedFocusNavigation(const Element& root, const Element* current); + static ScopedFocusNavigation ownedByNonFocusableFocusScopeOwner(Element&); + static ScopedFocusNavigation ownedByShadowHost(const Element&); + static ScopedFocusNavigation ownedByShadowInsertionPoint(HTMLShadowElement&); + static ScopedFocusNavigation ownedByHTMLSlotElement(const HTMLSlotElement&); + static ScopedFocusNavigation ownedByIFrame(const HTMLFrameOwnerElement&); private: - explicit FocusNavigationScope(TreeScope*); - ContainerNode& rootNode() const; - RawPtrWillBeMember<TreeScope> m_rootTreeScope; + ScopedFocusNavigation(TreeScope&, const Element*); + ScopedFocusNavigation(HTMLSlotElement&, const Element*); + RawPtrWillBeMember<ContainerNode> m_rootNode; + RawPtrWillBeMember<HTMLSlotElement> m_rootSlot; + RawPtrWillBeMember<Element> m_current; }; -FocusNavigationScope::FocusNavigationScope(TreeScope* treeScope) - : m_rootTreeScope(treeScope) +ScopedFocusNavigation::ScopedFocusNavigation(TreeScope& treeScope, const Element* current) + : m_rootNode(treeScope.rootNode()) + , m_rootSlot(nullptr) + , m_current(const_cast<Element*>(current)) { - ASSERT(treeScope); } -ContainerNode& FocusNavigationScope::rootNode() const +ScopedFocusNavigation::ScopedFocusNavigation(HTMLSlotElement& slot, const Element* current) + : m_rootNode(nullptr) + , m_rootSlot(&slot) + , m_current(const_cast<Element*>(current)) { - return m_rootTreeScope->rootNode(); } -Element* FocusNavigationScope::firstElement() const +Element* ScopedFocusNavigation::currentElement() const { - ContainerNode& root = rootNode(); - return root.isElementNode() ? &toElement(root) : ElementTraversal::next(root); + return m_current; } -Element* FocusNavigationScope::lastElement() const +void ScopedFocusNavigation::setCurrentElement(Element* element) { - return ElementTraversal::lastWithin(rootNode()); + m_current = element; } -Element* FocusNavigationScope::owner() const +void ScopedFocusNavigation::moveToNext() { - ContainerNode& root = rootNode(); - if (root.isShadowRoot()) { - ShadowRoot& shadowRoot = toShadowRoot(root); + ASSERT(m_current); + if (m_rootSlot) { + m_current = SlotScopedTraversal::next(*m_current); + } else { + m_current = ElementTraversal::next(*m_current); + while (m_current && SlotScopedTraversal::isSlotScoped(*m_current)) + m_current = ElementTraversal::next(*m_current); + } +} + +void ScopedFocusNavigation::moveToPrevious() +{ + ASSERT(m_current); + if (m_rootSlot) { + m_current = SlotScopedTraversal::previous(*m_current); + } else { + m_current = ElementTraversal::previous(*m_current); + while (m_current && SlotScopedTraversal::isSlotScoped(*m_current)) + m_current = ElementTraversal::previous(*m_current); + } +} + +void ScopedFocusNavigation::moveToFirst() +{ + if (m_rootSlot) { + if (!m_rootSlot->getAssignedNodes().isEmpty()) { + WillBeHeapVector<RefPtrWillBeMember<Node>> assignedNodes = m_rootSlot->getAssignedNodes(); + for (auto assignedNode : assignedNodes) { + if (assignedNode->isElementNode()) { + m_current = toElement(assignedNode); + break; + } + } + } else { + m_current = nullptr; + } + } else { + Element* first = m_rootNode->isElementNode() ? &toElement(*m_rootNode) : ElementTraversal::next(*m_rootNode); + while (first && SlotScopedTraversal::isSlotScoped(*first)) + first = ElementTraversal::next(*first, m_rootNode); + m_current = first; + } +} + +void ScopedFocusNavigation::moveToLast() +{ + if (m_rootSlot) { + if (!m_rootSlot->getAssignedNodes().isEmpty()) { + WillBeHeapVector<RefPtrWillBeMember<Node>> assignedNodes = m_rootSlot->getAssignedNodes(); + for (auto assignedNode = assignedNodes.rbegin(); assignedNode != assignedNodes.rend(); ++assignedNode) { + if ((*assignedNode)->isElementNode()) { + Element* lastWithin = ElementTraversal::lastWithin(*toElement(*assignedNode)); + if (lastWithin) + m_current = lastWithin; + else + m_current = toElement(*assignedNode); + break; + } + } + } else { + m_current = nullptr; + } + } else { + Element* last = ElementTraversal::lastWithin(*m_rootNode); + while (last && SlotScopedTraversal::isSlotScoped(*last)) + last = ElementTraversal::previous(*last, m_rootNode); + m_current = last; + } +} + +Element* ScopedFocusNavigation::owner() const +{ + if (m_rootSlot) + return m_rootSlot; + if (m_rootNode->isShadowRoot()) { + ShadowRoot& shadowRoot = toShadowRoot(*m_rootNode); return shadowRoot.isYoungest() ? shadowRoot.host() : shadowRoot.shadowInsertionPointOfYoungerShadowRoot(); } // FIXME: Figure out the right thing for OOPI here. - if (Frame* frame = root.document().frame()) + if (Frame* frame = m_rootNode->document().frame()) return frame->deprecatedLocalOwner(); return nullptr; } -FocusNavigationScope FocusNavigationScope::focusNavigationScopeOf(const Element& element) +ScopedFocusNavigation ScopedFocusNavigation::createScopedFocusNavigation(const Element& root, const Element* current) { - return FocusNavigationScope(&element.treeScope()); + if (SlotScopedTraversal::isSlotScoped(root)) + return ScopedFocusNavigation(*SlotScopedTraversal::findScopeOwnerSlot(root), current); + return ScopedFocusNavigation(*&root.treeScope(), current); } -FocusNavigationScope FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(Element& element) +ScopedFocusNavigation ScopedFocusNavigation::ownedByNonFocusableFocusScopeOwner(Element& element) { if (isShadowHost(element)) - return FocusNavigationScope::ownedByShadowHost(element); - ASSERT(isShadowInsertionPointFocusScopeOwner(element)); - return FocusNavigationScope::ownedByShadowInsertionPoint(toHTMLShadowElement(element)); + return ScopedFocusNavigation::ownedByShadowHost(element); + if (isShadowInsertionPointFocusScopeOwner(element)) + return ScopedFocusNavigation::ownedByShadowInsertionPoint(toHTMLShadowElement(element)); + ASSERT(isHTMLSlotElement(element)); + return ScopedFocusNavigation::ownedByHTMLSlotElement(toHTMLSlotElement(element)); } -FocusNavigationScope FocusNavigationScope::ownedByShadowHost(const Element& element) +ScopedFocusNavigation ScopedFocusNavigation::ownedByShadowHost(const Element& element) { ASSERT(isShadowHost(element)); - return FocusNavigationScope(&element.shadow()->youngestShadowRoot()); + return ScopedFocusNavigation(*&element.shadow()->youngestShadowRoot(), nullptr); } -FocusNavigationScope FocusNavigationScope::ownedByIFrame(const HTMLFrameOwnerElement& frame) +ScopedFocusNavigation ScopedFocusNavigation::ownedByIFrame(const HTMLFrameOwnerElement& frame) { ASSERT(frame.contentFrame()); ASSERT(frame.contentFrame()->isLocalFrame()); - return FocusNavigationScope(toLocalFrame(frame.contentFrame())->document()); + toLocalFrame(frame.contentFrame())->document()->updateDistribution(); + return ScopedFocusNavigation(*toLocalFrame(frame.contentFrame())->document(), nullptr); } -FocusNavigationScope FocusNavigationScope::ownedByShadowInsertionPoint(HTMLShadowElement& shadowInsertionPoint) +ScopedFocusNavigation ScopedFocusNavigation::ownedByShadowInsertionPoint(HTMLShadowElement& shadowInsertionPoint) { ASSERT(isShadowInsertionPointFocusScopeOwner(shadowInsertionPoint)); - return FocusNavigationScope(shadowInsertionPoint.olderShadowRoot()); + return ScopedFocusNavigation(*shadowInsertionPoint.olderShadowRoot(), nullptr); +} + +ScopedFocusNavigation ScopedFocusNavigation::ownedByHTMLSlotElement(const HTMLSlotElement& element) +{ + return ScopedFocusNavigation(const_cast<HTMLSlotElement&>(element), nullptr); } inline void dispatchBlurEvent(const Document& document, Element& focusedElement) @@ -234,7 +328,7 @@ inline bool isNonFocusableFocusScopeOwner(Element& element) { - return isNonKeyboardFocusableShadowHost(element) || isShadowInsertionPointFocusScopeOwner(element); + return isNonKeyboardFocusableShadowHost(element) || isShadowInsertionPointFocusScopeOwner(element) || isHTMLSlotElement(element); } inline bool isShadowHostDelegatesFocus(const Element& element) @@ -252,59 +346,65 @@ return element.isKeyboardFocusable() || isNonFocusableFocusScopeOwner(element); } -Element* findElementWithExactTabIndex(Element* start, int tabIndex, WebFocusType type) +Element* findElementWithExactTabIndex(ScopedFocusNavigation& scope, int tabIndex, WebFocusType type) { // Search is inclusive of start - for (Element* element = start; element; element = type == WebFocusTypeForward ? ElementTraversal::next(*element) : ElementTraversal::previous(*element)) { - if (shouldVisit(*element) && adjustedTabIndex(*element) == tabIndex) - return element; + for (; scope.currentElement(); type == WebFocusTypeForward ? scope.moveToNext() : scope.moveToPrevious()) { + Element* current = scope.currentElement(); + if (shouldVisit(*current) && adjustedTabIndex(*current) == tabIndex) + return current; } return nullptr; } -Element* nextElementWithGreaterTabIndex(Element* start, int tabIndex) +Element* nextElementWithGreaterTabIndex(ScopedFocusNavigation& scope, int tabIndex) { // Search is inclusive of start int winningTabIndex = std::numeric_limits<short>::max() + 1; Element* winner = nullptr; - for (Element& element : ElementTraversal::startsAt(start)) { - int currentTabIndex = adjustedTabIndex(element); - if (shouldVisit(element) && currentTabIndex > tabIndex && currentTabIndex < winningTabIndex) { - winner = &element; + for (; scope.currentElement(); scope.moveToNext()) { + Element* current = scope.currentElement(); + int currentTabIndex = adjustedTabIndex(*current); + if (shouldVisit(*current) && currentTabIndex > tabIndex && currentTabIndex < winningTabIndex) { + winner = current; winningTabIndex = currentTabIndex; } } return winner; } -Element* previousElementWithLowerTabIndex(Element* start, int tabIndex) +Element* previousElementWithLowerTabIndex(ScopedFocusNavigation& scope, int tabIndex) { // Search is inclusive of start int winningTabIndex = 0; Element* winner = nullptr; - for (Element* element = start; element; element = ElementTraversal::previous(*element)) { - int currentTabIndex = adjustedTabIndex(*element); - if (shouldVisit(*element) && currentTabIndex < tabIndex && currentTabIndex > winningTabIndex) { - winner = element; + for (; scope.currentElement(); scope.moveToPrevious()) { + Element* current = scope.currentElement(); + int currentTabIndex = adjustedTabIndex(*current); + if (shouldVisit(*current) && currentTabIndex < tabIndex && currentTabIndex > winningTabIndex) { + winner = current; winningTabIndex = currentTabIndex; } } return winner; } -Element* nextFocusableElement(const FocusNavigationScope& scope, Element* start) +Element* nextFocusableElement(ScopedFocusNavigation& scope) { - if (start) { - int tabIndex = adjustedTabIndex(*start); + Element* current = scope.currentElement(); + if (current) { + int tabIndex = adjustedTabIndex(*current); // If an element is excluded from the normal tabbing cycle, the next focusable element is determined by tree order if (tabIndex < 0) { - for (Element& element : ElementTraversal::startsAfter(*start)) { - if (shouldVisit(element) && adjustedTabIndex(element) >= 0) - return &element; + for (scope.moveToNext(); scope.currentElement(); scope.moveToNext()) { + current = scope.currentElement(); + if (shouldVisit(*current) && adjustedTabIndex(*current) >= 0) + return current; } } else { // First try to find an element with the same tabindex as start that comes after start in the scope. - if (Element* winner = findElementWithExactTabIndex(ElementTraversal::next(*start), tabIndex, WebFocusTypeForward)) + scope.moveToNext(); + if (Element* winner = findElementWithExactTabIndex(scope, tabIndex, WebFocusTypeForward)) return winner; } if (!tabIndex) { @@ -316,46 +416,49 @@ // Look for the first element in the scope that: // 1) has the lowest tabindex that is higher than start's tabindex (or 0, if start is null), and // 2) comes first in the scope, if there's a tie. - if (Element* winner = nextElementWithGreaterTabIndex(scope.firstElement(), start ? adjustedTabIndex(*start) : 0)) + scope.moveToFirst(); + if (Element* winner = nextElementWithGreaterTabIndex(scope, current ? adjustedTabIndex(*current) : 0)) { return winner; + } // There are no elements with a tabindex greater than start's tabindex, // so find the first element with a tabindex of 0. - return findElementWithExactTabIndex(scope.firstElement(), 0, WebFocusTypeForward); + scope.moveToFirst(); + return findElementWithExactTabIndex(scope, 0, WebFocusTypeForward); } -Element* previousFocusableElement(const FocusNavigationScope& scope, Element* start) +Element* previousFocusableElement(ScopedFocusNavigation& scope) { - Element* lastElement = scope.lastElement(); - // First try to find the last element in the scope that comes before start and has the same tabindex as start. // If start is null, find the last element in the scope with a tabindex of 0. - Element* startElement; - int startTabIndex; - if (start) { - startElement = ElementTraversal::previous(*start); - startTabIndex = adjustedTabIndex(*start); + int tabIndex; + Element* current = scope.currentElement(); + if (current) { + scope.moveToPrevious(); + tabIndex = adjustedTabIndex(*current); } else { - startElement = lastElement; - startTabIndex = 0; + scope.moveToLast(); + tabIndex = 0; } // However, if an element is excluded from the normal tabbing cycle, the previous focusable element is determined by tree order - if (startTabIndex < 0) { - for (Element* element = startElement; element; element = ElementTraversal::previous(*element)) { - if (shouldVisit(*element) && adjustedTabIndex(*element) >= 0) - return element; + if (tabIndex < 0) { + for (; scope.currentElement(); scope.moveToPrevious()) { + current = scope.currentElement(); + if (shouldVisit(*current) && adjustedTabIndex(*current) >= 0) + return current; } } else { - if (Element* winner = findElementWithExactTabIndex(startElement, startTabIndex, WebFocusTypeBackward)) + if (Element* winner = findElementWithExactTabIndex(scope, tabIndex, WebFocusTypeBackward)) return winner; } // There are no elements before start with the same tabindex as start, so look for an element that: // 1) has the highest non-zero tabindex (that is less than start's tabindex), and // 2) comes last in the scope, if there's a tie. - startTabIndex = (start && startTabIndex) ? startTabIndex : std::numeric_limits<short>::max(); - return previousElementWithLowerTabIndex(lastElement, startTabIndex); + tabIndex = (current && tabIndex) ? tabIndex : std::numeric_limits<short>::max(); + scope.moveToLast(); + return previousElementWithLowerTabIndex(scope, tabIndex); } // Searches through the given tree scope, starting from start element, for the next/previous @@ -371,58 +474,60 @@ // // [1] https://html.spec.whatwg.org/multipage/interaction.html#sequential-focus-navigation // [2] https://w3c.github.io/webcomponents/spec/shadow/#focus-navigation -inline Element* findFocusableElementInternal(WebFocusType type, const FocusNavigationScope& scope, Element* element) +inline Element* findFocusableElementInternal(WebFocusType type, ScopedFocusNavigation& scope) { - Element* found = (type == WebFocusTypeForward) ? nextFocusableElement(scope, element) : previousFocusableElement(scope, element); + Element* found = (type == WebFocusTypeForward) ? nextFocusableElement(scope) : previousFocusableElement(scope); return found; } -Element* findFocusableElementRecursivelyForward(const FocusNavigationScope& scope, Element* start) +Element* findFocusableElementRecursivelyForward(ScopedFocusNavigation& scope) { // Starting element is exclusive. - Element* found = findFocusableElementInternal(WebFocusTypeForward, scope, start); + Element* found = findFocusableElementInternal(WebFocusTypeForward, scope); while (found) { if (isShadowHostDelegatesFocus(*found)) { // If tabindex is positive, find focusable element inside its shadow tree. if (found->tabIndex() >= 0 && isShadowHostWithoutCustomFocusLogic(*found)) { - FocusNavigationScope innerScope = FocusNavigationScope::ownedByShadowHost(*found); - if (Element* foundInInnerFocusScope = findFocusableElementRecursivelyForward(innerScope, nullptr)) + ScopedFocusNavigation innerScope = ScopedFocusNavigation::ownedByShadowHost(*found); + if (Element* foundInInnerFocusScope = findFocusableElementRecursivelyForward(innerScope)) return foundInInnerFocusScope; } // Skip to the next element in the same scope. - found = findFocusableElementInternal(WebFocusTypeForward, scope, found); + found = findFocusableElementInternal(WebFocusTypeForward, scope); continue; } if (!isNonFocusableFocusScopeOwner(*found)) return found; - // Now |found| is on a non focusable scope owner (either shadow host or <shadow>) + // Now |found| is on a non focusable scope owner (either shadow host or <shadow> or slot) // Find inside the inward scope and return it if found. Otherwise continue searching in the same // scope. - FocusNavigationScope innerScope = FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(*found); - if (Element* foundInInnerFocusScope = findFocusableElementRecursivelyForward(innerScope, nullptr)) + ScopedFocusNavigation innerScope = ScopedFocusNavigation::ownedByNonFocusableFocusScopeOwner(*found); + if (Element* foundInInnerFocusScope = findFocusableElementRecursivelyForward(innerScope)) return foundInInnerFocusScope; - found = findFocusableElementInternal(WebFocusTypeForward, scope, found); + scope.setCurrentElement(found); + found = findFocusableElementInternal(WebFocusTypeForward, scope); } return nullptr; } -Element* findFocusableElementRecursivelyBackward(const FocusNavigationScope& scope, Element* start) +Element* findFocusableElementRecursivelyBackward(ScopedFocusNavigation& scope) { // Starting element is exclusive. - Element* found = findFocusableElementInternal(WebFocusTypeBackward, scope, start); + Element* found = findFocusableElementInternal(WebFocusTypeBackward, scope); + while (found) { // Now |found| is on a focusable shadow host. // Find inside shadow backwards. If any focusable element is found, return it, otherwise return // the host itself. if (isKeyboardFocusableShadowHost(*found)) { - FocusNavigationScope innerScope = FocusNavigationScope::ownedByShadowHost(*found); - Element* foundInInnerFocusScope = findFocusableElementRecursivelyBackward(innerScope, nullptr); + ScopedFocusNavigation innerScope = ScopedFocusNavigation::ownedByShadowHost(*found); + Element* foundInInnerFocusScope = findFocusableElementRecursivelyBackward(innerScope); if (foundInInnerFocusScope) return foundInInnerFocusScope; if (isShadowHostDelegatesFocus(*found)) { - found = findFocusableElementInternal(WebFocusTypeBackward, scope, found); + found = findFocusableElementInternal(WebFocusTypeBackward, scope); continue; } return found; @@ -431,33 +536,36 @@ // If delegatesFocus is true and tabindex is negative, skip the whole shadow tree under the // shadow host. if (isShadowHostDelegatesFocus(*found) && found->tabIndex() < 0) { - found = findFocusableElementInternal(WebFocusTypeBackward, scope, found); + found = findFocusableElementInternal(WebFocusTypeBackward, scope); continue; } - // Now |found| is on a non focusable scope owner (either shadow host or <shadow>). + // Now |found| is on a non focusable scope owner (either shadow host or <shadow> or slot). // Find focusable element in descendant scope. If not found, find next focusable element within the // current scope. if (isNonFocusableFocusScopeOwner(*found)) { - FocusNavigationScope innerScope = FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(*found); - Element* foundInInnerFocusScope = findFocusableElementRecursivelyBackward(innerScope, nullptr); + ScopedFocusNavigation innerScope = ScopedFocusNavigation::ownedByNonFocusableFocusScopeOwner(*found); + Element* foundInInnerFocusScope = findFocusableElementRecursivelyBackward(innerScope); + if (foundInInnerFocusScope) return foundInInnerFocusScope; - found = findFocusableElementInternal(WebFocusTypeBackward, scope, found); + found = findFocusableElementInternal(WebFocusTypeBackward, scope); continue; } if (!isShadowHostDelegatesFocus(*found)) return found; - found = findFocusableElementInternal(WebFocusTypeBackward, scope, found); + + scope.setCurrentElement(found); + found = findFocusableElementInternal(WebFocusTypeBackward, scope); } return nullptr; } -Element* findFocusableElementRecursively(WebFocusType type, const FocusNavigationScope& scope, Element* start) +Element* findFocusableElementRecursively(WebFocusType type, ScopedFocusNavigation& scope) { return (type == WebFocusTypeForward) ? - findFocusableElementRecursivelyForward(scope, start) : - findFocusableElementRecursivelyBackward(scope, start); + findFocusableElementRecursivelyForward(scope) : + findFocusableElementRecursivelyBackward(scope); } Element* findFocusableElementDescendingDownIntoFrameDocument(WebFocusType type, Element* element) @@ -470,7 +578,8 @@ if (!owner.contentFrame() || !owner.contentFrame()->isLocalFrame()) break; toLocalFrame(owner.contentFrame())->document()->updateLayoutIgnorePendingStylesheets(); - Element* foundElement = findFocusableElementRecursively(type, FocusNavigationScope::ownedByIFrame(owner), nullptr); + ScopedFocusNavigation scope = ScopedFocusNavigation::ownedByIFrame(owner); + Element* foundElement = findFocusableElementRecursively(type, scope); if (!foundElement) break; ASSERT(element != foundElement); @@ -479,56 +588,57 @@ return element; } -Element* findFocusableElementAcrossFocusScopesForward(const FocusNavigationScope& scope, Element* current) +Element* findFocusableElementAcrossFocusScopesForward(ScopedFocusNavigation& scope) { + Element* current = scope.currentElement(); ASSERT(!current || !isNonFocusableShadowHost(*current)); Element* found; if (current && isShadowHostWithoutCustomFocusLogic(*current)) { - FocusNavigationScope innerScope = FocusNavigationScope::ownedByShadowHost(*current); - Element* foundInInnerFocusScope = findFocusableElementRecursivelyForward(innerScope, nullptr); - found = foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableElementRecursivelyForward(scope, current); + ScopedFocusNavigation innerScope = ScopedFocusNavigation::ownedByShadowHost(*current); + Element* foundInInnerFocusScope = findFocusableElementRecursivelyForward(innerScope); + found = foundInInnerFocusScope ? foundInInnerFocusScope : findFocusableElementRecursivelyForward(scope); } else { - found = findFocusableElementRecursivelyForward(scope, current); + found = findFocusableElementRecursivelyForward(scope); } // If there's no focusable element to advance to, move up the focus scopes until we find one. - FocusNavigationScope currentScope = scope; + ScopedFocusNavigation currentScope = scope; while (!found) { Element* owner = currentScope.owner(); if (!owner) break; - currentScope = FocusNavigationScope::focusNavigationScopeOf(*owner); - found = findFocusableElementRecursivelyForward(currentScope, owner); + currentScope = ScopedFocusNavigation::createScopedFocusNavigation(*owner, owner); + found = findFocusableElementRecursivelyForward(currentScope); } return findFocusableElementDescendingDownIntoFrameDocument(WebFocusTypeForward, found); } -Element* findFocusableElementAcrossFocusScopesBackward(const FocusNavigationScope& scope, Element* current) +Element* findFocusableElementAcrossFocusScopesBackward(ScopedFocusNavigation& scope) { - ASSERT(!current || !isNonFocusableShadowHost(*current)); - Element* found = findFocusableElementRecursivelyBackward(scope, current); + ASSERT(!scope.currentElement() || !isNonFocusableShadowHost(*scope.currentElement())); + Element* found = findFocusableElementRecursivelyBackward(scope); // If there's no focusable element to advance to, move up the focus scopes until we find one. - FocusNavigationScope currentScope = scope; + ScopedFocusNavigation currentScope = scope; while (!found) { Element* owner = currentScope.owner(); if (!owner) break; - currentScope = FocusNavigationScope::focusNavigationScopeOf(*owner); + currentScope = ScopedFocusNavigation::createScopedFocusNavigation(*owner, owner); if (isKeyboardFocusableShadowHost(*owner) && !isShadowHostDelegatesFocus(*owner)) { found = owner; break; } - found = findFocusableElementRecursivelyBackward(currentScope, owner); + found = findFocusableElementRecursivelyBackward(currentScope); } return findFocusableElementDescendingDownIntoFrameDocument(WebFocusTypeBackward, found); } -Element* findFocusableElementAcrossFocusScopes(WebFocusType type, const FocusNavigationScope& scope, Element* current) +Element* findFocusableElementAcrossFocusScopes(WebFocusType type, ScopedFocusNavigation& scope) { return (type == WebFocusTypeForward) ? - findFocusableElementAcrossFocusScopesForward(scope, current) : - findFocusableElementAcrossFocusScopesBackward(scope, current); + findFocusableElementAcrossFocusScopesForward(scope) : + findFocusableElementAcrossFocusScopesBackward(scope); } inline Element* adjustToElement(Node* node, WebFocusType type) @@ -541,6 +651,8 @@ // The returned element is used as an *exclusive* start element. Thus, we should return the result of ElementTraversal::previous(*node), // instead of ElementTraversal::next(*node), if type == WebFocusTypeForward, and vice-versa. // The caller will call ElementTraversal::{next/previous} for the returned value and get the {next|previous} element of the |node|. + + // TODO(yuzus) Use ScopedFocusNavigation traversal here. return (type == WebFocusTypeForward) ? ElementTraversal::previous(*node) : ElementTraversal::next(*node); } @@ -743,6 +855,7 @@ ASSERT(frame); Document* document = frame->document(); ASSERT(document->documentElement()); + document->updateDistribution(); Element* current = start; if (!current && !initialFocus) @@ -755,8 +868,8 @@ current = adjustToElement(frame->selection().start().anchorNode(), type); document->updateLayoutIgnorePendingStylesheets(); - - RefPtrWillBeRawPtr<Element> element = findFocusableElementAcrossFocusScopes(type, FocusNavigationScope::focusNavigationScopeOf(current ? *current : *document->documentElement()), current); + ScopedFocusNavigation scope = ScopedFocusNavigation::createScopedFocusNavigation(current ? *current : *document->documentElement(), current); + RefPtrWillBeRawPtr<Element> element = findFocusableElementAcrossFocusScopes(type, scope); if (!element) { // If there's a RemoteFrame on the ancestor chain, we need to continue @@ -778,7 +891,8 @@ } // Chrome doesn't want focus, so we should wrap focus. - element = findFocusableElementRecursively(type, FocusNavigationScope::focusNavigationScopeOf(*toLocalFrame(m_page->mainFrame())->document()->documentElement()), nullptr); + ScopedFocusNavigation scope = ScopedFocusNavigation::createScopedFocusNavigation(*toLocalFrame(m_page->mainFrame())->document()->documentElement(), nullptr); + element = findFocusableElementRecursively(type, scope); element = findFocusableElementDescendingDownIntoFrameDocument(type, element.get()); if (!element) @@ -838,13 +952,15 @@ { // FIXME: No spacial navigation code yet. ASSERT(type == WebFocusTypeForward || type == WebFocusTypeBackward); - return findFocusableElementAcrossFocusScopes(type, FocusNavigationScope::focusNavigationScopeOf(element), &element); + ScopedFocusNavigation scope = ScopedFocusNavigation::createScopedFocusNavigation(element, &element); + return findFocusableElementAcrossFocusScopes(type, scope); } Element* FocusController::findFocusableElementInShadowHost(const Element& shadowHost) { ASSERT(shadowHost.authorShadowRoot()); - return findFocusableElementAcrossFocusScopes(WebFocusTypeForward, FocusNavigationScope::ownedByShadowHost(shadowHost), nullptr); + ScopedFocusNavigation scope = ScopedFocusNavigation::ownedByShadowHost(shadowHost); + return findFocusableElementAcrossFocusScopes(WebFocusTypeForward, scope); } static bool relinquishesEditingFocus(const Element& element)
diff --git a/third_party/WebKit/Source/core/page/PrintContextTest.cpp b/third_party/WebKit/Source/core/page/PrintContextTest.cpp index d6b6eea1..ba33880 100644 --- a/third_party/WebKit/Source/core/page/PrintContextTest.cpp +++ b/third_party/WebKit/Source/core/page/PrintContextTest.cpp
@@ -49,23 +49,18 @@ MockCanvas() : SkCanvas(kPageWidth, kPageHeight) { } - void onDrawRect(const SkRect& rect, const SkPaint& paint) override + void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) override { - if (!paint.getAnnotation()) - return; - Operation operation = { DrawRect, rect }; - getTotalMatrix().mapRect(&operation.rect); - m_recordedOperations.append(operation); - } - - void onDrawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) override - { - if (!paint.getAnnotation()) - return; - ASSERT_EQ(1u, count); // Only called from drawPoint(). - SkPoint point = getTotalMatrix().mapXY(pts[0].x(), pts[0].y()); - Operation operation = { DrawPoint, SkRect::MakeXYWH(point.x(), point.y(), 0, 0) }; - m_recordedOperations.append(operation); + if (rect.width() == 0 && rect.height() == 0) { + SkPoint point = getTotalMatrix().mapXY(rect.x(), rect.y()); + Operation operation = { + DrawPoint, SkRect::MakeXYWH(point.x(), point.y(), 0, 0) }; + m_recordedOperations.append(operation); + } else { + Operation operation = { DrawRect, rect }; + getTotalMatrix().mapRect(&operation.rect); + m_recordedOperations.append(operation); + } } const Vector<Operation>& recordedOperations() const { return m_recordedOperations; }
diff --git a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp index 64b5930..ec2136e8 100644 --- a/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp +++ b/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -331,26 +331,11 @@ void ScrollingCoordinator::scrollableAreaScrollbarLayerDidChange(ScrollableArea* scrollableArea, ScrollbarOrientation orientation) { -// FIXME: Instead of hardcode here, we should make a setting flag. -#if OS(MACOSX) - static const bool platformSupportsCoordinatedScrollbar = ScrollAnimatorMac::canUseCoordinatedScrollbar(); -#else - static const bool platformSupportsCoordinatedScrollbar = true; -#endif - bool isMainFrame = isForMainFrame(scrollableArea); GraphicsLayer* scrollbarGraphicsLayer = orientation == HorizontalScrollbar ? scrollableArea->layerForHorizontalScrollbar() : scrollableArea->layerForVerticalScrollbar(); - if (!platformSupportsCoordinatedScrollbar) { - if (scrollbarGraphicsLayer) { - WebLayer* scrollbarLayer = toWebLayer(scrollbarGraphicsLayer); - scrollbarLayer->addMainThreadScrollingReasons(MainThreadScrollingReason::kScrollbarScrolling); - } - return; - } - if (scrollbarGraphicsLayer) { Scrollbar& scrollbar = orientation == HorizontalScrollbar ? *scrollableArea->horizontalScrollbar() : *scrollableArea->verticalScrollbar(); if (scrollbar.isCustomScrollbar()) { @@ -379,8 +364,9 @@ // blending. bool isOpaqueScrollbar = !scrollbar.isOverlayScrollbar(); scrollbarGraphicsLayer->setContentsOpaque(isMainFrame && isOpaqueScrollbar); - } else + } else { removeWebScrollbarLayer(scrollableArea, orientation); + } } bool ScrollingCoordinator::scrollableAreaScrollLayerDidChange(ScrollableArea* scrollableArea)
diff --git a/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp b/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp index 15e67cd1..853ab4f 100644 --- a/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp +++ b/third_party/WebKit/Source/core/paint/BoxBorderPainter.cpp
@@ -45,30 +45,30 @@ inline bool styleRequiresClipPolygon(EBorderStyle style) { // These are drawn with a stroke, so we have to clip to get corner miters. - return style == DOTTED || style == DASHED; + return style == BorderStyleDotted || style == BorderStyleDashed; } inline bool borderStyleFillsBorderArea(EBorderStyle style) { - return !(style == DOTTED || style == DASHED || style == DOUBLE); + return !(style == BorderStyleDotted || style == BorderStyleDashed || style == BorderStyleDouble); } inline bool borderStyleHasInnerDetail(EBorderStyle style) { - return style == GROOVE || style == RIDGE || style == DOUBLE; + return style == BorderStyleGroove || style == BorderStyleRidge || style == BorderStyleDouble; } inline bool borderStyleIsDottedOrDashed(EBorderStyle style) { - return style == DOTTED || style == DASHED; + return style == BorderStyleDotted || style == BorderStyleDashed; } -// OUTSET darkens the bottom and right (and maybe lightens the top and left) -// INSET darkens the top and left (and maybe lightens the bottom and right) +// BorderStyleOutset darkens the bottom and right (and maybe lightens the top and left) +// BorderStyleInset darkens the top and left (and maybe lightens the bottom and right) inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide) { // These styles match at the top/left and bottom/right. - if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) { + if (style == BorderStyleInset || style == BorderStyleGroove || style == BorderStyleRidge || style == BorderStyleOutset) { const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight); const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft); @@ -106,7 +106,7 @@ inline bool borderStylesRequireMiter(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle) { - if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE) + if (style == BorderStyleDouble || adjacentStyle == BorderStyleDouble || adjacentStyle == BorderStyleGroove || adjacentStyle == BorderStyleRidge) return true; if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle)) @@ -311,16 +311,16 @@ } // The LUTs below assume specific enum values. -static_assert(BNONE == 0, "unexpected EBorderStyle value"); -static_assert(BHIDDEN == 1, "unexpected EBorderStyle value"); -static_assert(INSET == 2, "unexpected EBorderStyle value"); -static_assert(GROOVE == 3, "unexpected EBorderStyle value"); -static_assert(OUTSET == 4, "unexpected EBorderStyle value"); -static_assert(RIDGE == 5, "unexpected EBorderStyle value"); -static_assert(DOTTED == 6, "unexpected EBorderStyle value"); -static_assert(DASHED == 7, "unexpected EBorderStyle value"); -static_assert(SOLID == 8, "unexpected EBorderStyle value"); -static_assert(DOUBLE == 9, "unexpected EBorderStyle value"); +static_assert(BorderStyleNone == 0, "unexpected EBorderStyle value"); +static_assert(BorderStyleHidden == 1, "unexpected EBorderStyle value"); +static_assert(BorderStyleInset == 2, "unexpected EBorderStyle value"); +static_assert(BorderStyleGroove == 3, "unexpected EBorderStyle value"); +static_assert(BorderStyleOutset == 4, "unexpected EBorderStyle value"); +static_assert(BorderStyleRidge == 5, "unexpected EBorderStyle value"); +static_assert(BorderStyleDotted == 6, "unexpected EBorderStyle value"); +static_assert(BorderStyleDashed == 7, "unexpected EBorderStyle value"); +static_assert(BorderStyleSolid == 8, "unexpected EBorderStyle value"); +static_assert(BorderStyleDouble == 9, "unexpected EBorderStyle value"); static_assert(BSTop == 0, "unexpected BoxSide value"); static_assert(BSRight == 1, "unexpected BoxSide value"); @@ -330,16 +330,16 @@ // Style-based paint order: non-solid edges (dashed/dotted/double) are painted before // solid edges (inset/outset/groove/ridge/solid) to maximize overdraw opportunities. const unsigned kStylePriority[] = { - 0 /* BNONE */, - 0 /* BHIDDEN */, - 2 /* INSET */, - 2 /* GROOVE */, - 2 /* OUTSET */, - 2 /* RIDGE */, - 1 /* DOTTED */, - 1 /* DASHED */, - 3 /* SOLID */, - 1 /* DOUBLE */ + 0 /* BorderStyleNone */, + 0 /* BorderStyleHidden */, + 2 /* BorderStyleInset */, + 2 /* BorderStyleGroove */, + 2 /* BorderStyleOutset */, + 2 /* BorderStyleRidge */, + 1 /* BorderStyleDotted */, + 1 /* BorderStyleDashed */, + 3 /* BorderStyleSolid */, + 1 /* BorderStyleDouble */ }; // Given the same style, prefer drawing in non-adjacent order to minimize the number of sides @@ -442,7 +442,7 @@ { ASSERT(m_isUniformColor); ASSERT(m_isUniformStyle); - ASSERT(firstEdge().borderStyle() == DOUBLE); + ASSERT(firstEdge().borderStyle() == BorderStyleDouble); ASSERT(m_visibleEdgeSet == AllBorderEdges); const Color color = firstEdge().color; @@ -467,11 +467,11 @@ if (!m_isUniformColor || !m_isUniformStyle || !m_inner.isRenderable()) return false; - if (firstEdge().borderStyle() != SOLID && firstEdge().borderStyle() != DOUBLE) + if (firstEdge().borderStyle() != BorderStyleSolid && firstEdge().borderStyle() != BorderStyleDouble) return false; if (m_visibleEdgeSet == AllBorderEdges) { - if (firstEdge().borderStyle() == SOLID) { + if (firstEdge().borderStyle() == BorderStyleSolid) { if (m_isUniformWidth && !m_outer.isRounded()) { // 4-side, solid, uniform-width, rectangular border => one drawRect() drawSolidBorderRect(context, m_outer.rect(), firstEdge().width, firstEdge().color); @@ -481,7 +481,7 @@ } } else { // 4-side, double border => 2x drawDRRect() - ASSERT(firstEdge().borderStyle() == DOUBLE); + ASSERT(firstEdge().borderStyle() == BorderStyleDouble); drawDoubleBorder(context, borderRect); } @@ -490,7 +490,7 @@ // This is faster than the normal complex border path only if it avoids creating transparency // layers (when the border is translucent). - if (firstEdge().borderStyle() == SOLID && !m_outer.isRounded() && m_hasAlpha) { + if (firstEdge().borderStyle() == BorderStyleSolid && !m_outer.isRounded() && m_hasAlpha) { ASSERT(m_visibleEdgeSet != AllBorderEdges); // solid, rectangular border => one drawPath() Path path; @@ -869,15 +869,15 @@ if (thickness <= 0) return; - if (borderStyle == DOUBLE && thickness < 3) - borderStyle = SOLID; + if (borderStyle == BorderStyleDouble && thickness < 3) + borderStyle = BorderStyleSolid; switch (borderStyle) { - case BNONE: - case BHIDDEN: + case BorderStyleNone: + case BorderStyleHidden: return; - case DOTTED: - case DASHED: { + case BorderStyleDotted: + case BorderStyleDashed: { graphicsContext.setStrokeColor(color); // The stroke is doubled here because the provided path is the @@ -885,14 +885,14 @@ // The extra multiplier is so that the clipping mask can antialias // the edges to prevent jaggies. graphicsContext.setStrokeThickness(drawThickness * 2 * 1.1f); - graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke); + graphicsContext.setStrokeStyle(borderStyle == BorderStyleDashed ? DashedStroke : DottedStroke); // If the number of dashes that fit in the path is odd and non-integral then we // will have an awkwardly-sized dash at the end of the path. To try to avoid that // here, we simply make the whitespace dashes ever so slightly bigger. // FIXME: This could be even better if we tried to manipulate the dash offset // and possibly the gapLength to get the corners dash-symmetrical. - float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f); + float dashLength = thickness * ((borderStyle == BorderStyleDashed) ? 3.0f : 1.0f); float gapLength = dashLength; float numberOfDashes = borderPath.length() / dashLength; // Don't try to show dashes if we have less than 2 dashes + 2 gaps. @@ -917,7 +917,7 @@ graphicsContext.strokePath(borderPath); return; } - case DOUBLE: { + case BorderStyleDouble: { // Draw inner border line { GraphicsContextStateSaver stateSaver(graphicsContext); @@ -927,7 +927,7 @@ graphicsContext.clipRoundedRect(innerClip); drawBoxSideFromPath(graphicsContext, borderRect, borderPath, thickness, drawThickness, - side, color, SOLID); + side, color, BorderStyleSolid); } // Draw outer border line @@ -948,21 +948,21 @@ m_includeLogicalLeftEdge, m_includeLogicalRightEdge); graphicsContext.clipOutRoundedRect(outerClip); drawBoxSideFromPath(graphicsContext, borderRect, borderPath, thickness, drawThickness, - side, color, SOLID); + side, color, BorderStyleSolid); } return; } - case RIDGE: - case GROOVE: + case BorderStyleRidge: + case BorderStyleGroove: { EBorderStyle s1; EBorderStyle s2; - if (borderStyle == GROOVE) { - s1 = INSET; - s2 = OUTSET; + if (borderStyle == BorderStyleGroove) { + s1 = BorderStyleInset; + s2 = BorderStyleOutset; } else { - s1 = OUTSET; - s2 = INSET; + s1 = BorderStyleOutset; + s2 = BorderStyleInset; } // Paint full border @@ -985,11 +985,11 @@ side, color, s2); return; } - case INSET: + case BorderStyleInset: if (side == BSTop || side == BSLeft) color = color.dark(); break; - case OUTSET: + case BorderStyleOutset: if (side == BSBottom || side == BSRight) color = color.dark(); break;
diff --git a/third_party/WebKit/Source/core/paint/BoxPainter.cpp b/third_party/WebKit/Source/core/paint/BoxPainter.cpp index 8e6785e89..94500cd3 100644 --- a/third_party/WebKit/Source/core/paint/BoxPainter.cpp +++ b/third_party/WebKit/Source/core/paint/BoxPainter.cpp
@@ -249,7 +249,7 @@ // Use the most conservative inset to avoid mixed-style corner issues. float fractionalInset = 1.0f / 2; for (auto& edge : edges) { - if (edge.borderStyle() == DOUBLE) { + if (edge.borderStyle() == BorderStyleDouble) { fractionalInset = 1.0f / 6; break; }
diff --git a/third_party/WebKit/Source/core/paint/InlineFlowBoxPainter.cpp b/third_party/WebKit/Source/core/paint/InlineFlowBoxPainter.cpp index 8df3f65..232ed1c5 100644 --- a/third_party/WebKit/Source/core/paint/InlineFlowBoxPainter.cpp +++ b/third_party/WebKit/Source/core/paint/InlineFlowBoxPainter.cpp
@@ -67,7 +67,7 @@ bool hasFillImage = img && img->canRender(); if ((!hasFillImage && !m_inlineFlowBox.getLineLayoutItem().style()->hasBorderRadius()) || (!m_inlineFlowBox.prevLineBox() && !m_inlineFlowBox.nextLineBox()) || !m_inlineFlowBox.parent()) { BoxPainter::paintFillLayer(*boxModel, paintInfo, c, fillLayer, rect, BackgroundBleedNone, &m_inlineFlowBox, rect.size(), op); - } else if (m_inlineFlowBox.getLineLayoutItem().style()->boxDecorationBreak() == DCLONE) { + } else if (m_inlineFlowBox.getLineLayoutItem().style()->boxDecorationBreak() == BoxDecorationBreakClone) { GraphicsContextStateSaver stateSaver(paintInfo.context); paintInfo.context.clip(pixelSnappedIntRect(rect)); BoxPainter::paintFillLayer(*boxModel, paintInfo, c, fillLayer, rect, BackgroundBleedNone, &m_inlineFlowBox, rect.size(), op);
diff --git a/third_party/WebKit/Source/core/paint/MultiColumnSetPainter.cpp b/third_party/WebKit/Source/core/paint/MultiColumnSetPainter.cpp index d2d89a1..f45dc17 100644 --- a/third_party/WebKit/Source/core/paint/MultiColumnSetPainter.cpp +++ b/third_party/WebKit/Source/core/paint/MultiColumnSetPainter.cpp
@@ -42,7 +42,7 @@ EBorderStyle ruleStyle = blockStyle.columnRuleStyle(); LayoutUnit ruleThickness(blockStyle.columnRuleWidth()); LayoutUnit colGap = m_layoutMultiColumnSet.columnGap(); - bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent; + bool renderRule = ruleStyle > BorderStyleHidden && !ruleTransparent; if (!renderRule) return;
diff --git a/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp b/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp index 9eed86d..6518917 100644 --- a/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp +++ b/third_party/WebKit/Source/core/paint/NinePieceImagePainter.cpp
@@ -37,10 +37,10 @@ // Find out if the hasImage() check in ComputedStyle::border*Width had any affect, i.e. if a border is non-zero while border-style is // none or hidden. - if ((style.borderLeftWidth() && (style.borderLeft().style() == BNONE || style.borderLeft().style() == BHIDDEN)) - || (style.borderRightWidth() && (style.borderRight().style() == BNONE || style.borderRight().style() == BHIDDEN)) - || (style.borderTopWidth() && (style.borderTop().style() == BNONE || style.borderTop().style() == BHIDDEN)) - || (style.borderBottomWidth() && (style.borderBottom().style() == BNONE || style.borderBottom().style() == BHIDDEN))) + if ((style.borderLeftWidth() && (style.borderLeft().style() == BorderStyleNone || style.borderLeft().style() == BorderStyleHidden)) + || (style.borderRightWidth() && (style.borderRight().style() == BorderStyleNone || style.borderRight().style() == BorderStyleHidden)) + || (style.borderTopWidth() && (style.borderTop().style() == BorderStyleNone || style.borderTop().style() == BorderStyleHidden)) + || (style.borderBottomWidth() && (style.borderBottom().style() == BorderStyleNone || style.borderBottom().style() == BorderStyleHidden))) Deprecation::countDeprecation(m_layoutObject.document(), UseCounter::BorderImageWithBorderStyleNone); // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
diff --git a/third_party/WebKit/Source/core/paint/ObjectPainter.cpp b/third_party/WebKit/Source/core/paint/ObjectPainter.cpp index 0f0e700..32fcade 100644 --- a/third_party/WebKit/Source/core/paint/ObjectPainter.cpp +++ b/third_party/WebKit/Source/core/paint/ObjectPainter.cpp
@@ -299,38 +299,38 @@ if (length <= 0 || thickness <= 0) return; - if (style == DOUBLE && thickness < 3) - style = SOLID; + if (style == BorderStyleDouble && thickness < 3) + style = BorderStyleSolid; switch (style) { - case BNONE: - case BHIDDEN: + case BorderStyleNone: + case BorderStyleHidden: return; - case DOTTED: - case DASHED: + case BorderStyleDotted: + case BorderStyleDashed: drawDashedOrDottedBoxSide(graphicsContext, x1, y1, x2, y2, side, color, thickness, style, antialias); break; - case DOUBLE: + case BorderStyleDouble: drawDoubleBoxSide(graphicsContext, x1, y1, x2, y2, length, side, color, thickness, adjacentWidth1, adjacentWidth2, antialias); break; - case RIDGE: - case GROOVE: + case BorderStyleRidge: + case BorderStyleGroove: drawRidgeOrGrooveBoxSide(graphicsContext, x1, y1, x2, y2, side, color, style, adjacentWidth1, adjacentWidth2, antialias); break; - case INSET: + case BorderStyleInset: // FIXME: Maybe we should lighten the colors on one side like Firefox. // https://bugs.webkit.org/show_bug.cgi?id=58608 if (side == BSTop || side == BSLeft) color = color.dark(); // fall through - case OUTSET: - if (style == OUTSET && (side == BSBottom || side == BSRight)) + case BorderStyleOutset: + if (style == BorderStyleOutset && (side == BSBottom || side == BSRight)) color = color.dark(); // fall through - case SOLID: + case BorderStyleSolid: drawSolidBoxSide(graphicsContext, x1, y1, x2, y2, side, color, adjacentWidth1, adjacentWidth2, antialias); break; } @@ -346,7 +346,7 @@ graphicsContext.setShouldAntialias(antialias); graphicsContext.setStrokeColor(color); graphicsContext.setStrokeThickness(thickness); - graphicsContext.setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke); + graphicsContext.setStrokeStyle(style == BorderStyleDashed ? DashedStroke : DottedStroke); switch (side) { case BSBottom: @@ -405,34 +405,34 @@ case BSTop: drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0), y1, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness, - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0), y2 - thirdOfThickness, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y2, - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); break; case BSLeft: drawLineForBoxSide(graphicsContext, x1, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0), x1 + thirdOfThickness, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0), x2, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); break; case BSBottom: drawLineForBoxSide(graphicsContext, x1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0), y1, x2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness, - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); drawLineForBoxSide(graphicsContext, x1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0), y2 - thirdOfThickness, x2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), y2, - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); break; case BSRight: drawLineForBoxSide(graphicsContext, x1, y1 + std::max((adjacentWidth1 * 2 + 1) / 3, 0), x1 + thirdOfThickness, y2 - std::max((adjacentWidth2 * 2 + 1) / 3, 0), - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + std::max((-adjacentWidth1 * 2 + 1) / 3, 0), x2, y2 - std::max((-adjacentWidth2 * 2 + 1) / 3, 0), - side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias); + side, color, BorderStyleSolid, adjacent1BigThird, adjacent2BigThird, antialias); break; default: break; @@ -444,12 +444,12 @@ { EBorderStyle s1; EBorderStyle s2; - if (style == GROOVE) { - s1 = INSET; - s2 = OUTSET; + if (style == BorderStyleGroove) { + s1 = BorderStyleInset; + s2 = BorderStyleOutset; } else { - s1 = OUTSET; - s2 = INSET; + s1 = BorderStyleOutset; + s2 = BorderStyleInset; } int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
diff --git a/third_party/WebKit/Source/core/paint/PaintLayer.cpp b/third_party/WebKit/Source/core/paint/PaintLayer.cpp index 252dea3..de95f672 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayer.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayer.cpp
@@ -2646,7 +2646,7 @@ if (layoutObject()->style()->filter().hasReferenceFilter()) ensureFilterInfo()->updateReferenceFilterClients(layoutObject()->style()->filter()); else if (hasFilterInfo()) - filterInfo()->removeReferenceFilterClients(); + filterInfo()->clearFilterReferences(); } FilterEffectBuilder* PaintLayer::updateFilterEffectBuilder() const
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.cpp b/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.cpp index 55dacd1..653369b 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.cpp
@@ -89,7 +89,7 @@ PaintLayerFilterInfo::~PaintLayerFilterInfo() { - removeReferenceFilterClients(); + clearFilterReferences(); } void PaintLayerFilterInfo::setBuilder(PassRefPtrWillBeRawPtr<FilterEffectBuilder> builder) @@ -97,43 +97,10 @@ m_builder = builder; } -void PaintLayerFilterInfo::notifyFinished(Resource*) -{ - m_layer->filterNeedsPaintInvalidation(); -} - void PaintLayerFilterInfo::updateReferenceFilterClients(const FilterOperations& operations) { - removeReferenceFilterClients(); - for (size_t i = 0; i < operations.size(); ++i) { - RefPtrWillBeRawPtr<FilterOperation> filterOperation = operations.operations().at(i); - if (filterOperation->type() != FilterOperation::REFERENCE) - continue; - ReferenceFilterOperation* referenceFilterOperation = toReferenceFilterOperation(filterOperation.get()); - DocumentResourceReference* documentReference = ReferenceFilterBuilder::documentResourceReference(referenceFilterOperation); - DocumentResource* cachedSVGDocument = documentReference ? documentReference->document() : 0; - - if (cachedSVGDocument) { - // Reference is external; wait for notifyFinished(). - cachedSVGDocument->addClient(this); - m_externalSVGReferences.append(cachedSVGDocument); - } else { - // Reference is internal; add layer as a client so we can trigger - // filter paint invalidation on SVG attribute change. - Element* filter = m_layer->layoutObject()->document().getElementById(referenceFilterOperation->fragment()); - if (!isSVGFilterElement(filter)) - continue; - addFilterReference(toSVGFilterElement(filter)); - } - } -} - -void PaintLayerFilterInfo::removeReferenceFilterClients() -{ - for (size_t i = 0; i < m_externalSVGReferences.size(); ++i) - m_externalSVGReferences.at(i)->removeClient(this); - m_externalSVGReferences.clear(); clearFilterReferences(); + addFilterReferences(operations, m_layer->layoutObject()->document()); } void PaintLayerFilterInfo::filterNeedsInvalidation()
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.h b/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.h index 00dc3d5..c9a6cc2d 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.h +++ b/third_party/WebKit/Source/core/paint/PaintLayerFilterInfo.h
@@ -31,7 +31,6 @@ #define PaintLayerFilterInfo_h #include "core/dom/Element.h" -#include "core/fetch/DocumentResource.h" #include "core/svg/SVGResourceClient.h" #include "platform/geometry/LayoutRect.h" #include "platform/graphics/filters/FilterOperation.h" @@ -61,7 +60,7 @@ // PaintLayerFilterInfo is allocated when filters are present and stored in an // internal map (s_filterMap) to save memory as 'filter' should be a rare // property. -class PaintLayerFilterInfo final : public DocumentResourceClient, public SVGResourceClient { +class PaintLayerFilterInfo final : public SVGResourceClient { USING_FAST_MALLOC(PaintLayerFilterInfo); WTF_MAKE_NONCOPYABLE(PaintLayerFilterInfo); public: @@ -84,9 +83,6 @@ void setBuilder(PassRefPtrWillBeRawPtr<FilterEffectBuilder>); void updateReferenceFilterClients(const FilterOperations&); - void notifyFinished(Resource*) override; - String debugName() const override { return "PaintLayerFilterInfo"; } - void removeReferenceFilterClients(); void filterNeedsInvalidation() override; @@ -99,10 +95,6 @@ RefPtrWillBePersistent<FilterEffectBuilder> m_builder; static PaintLayerFilterInfoMap* s_filterMap; - - // This stores SVG reference filters (filter: url(#someElement)) where the - // reference belongs to a different document. - WillBePersistentHeapVector<RefPtrWillBeMember<DocumentResource>> m_externalSVGReferences; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp index 13d47ed..ef6eca3 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp
@@ -1293,7 +1293,7 @@ LayoutSize difference((currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize); - bool isBoxSizingBorder = box().style()->boxSizing() == BORDER_BOX; + bool isBoxSizingBorder = box().style()->boxSizing() == BoxSizingBorderBox; EResize resize = box().style()->resize(); if (resize != RESIZE_VERTICAL && difference.width()) {
diff --git a/third_party/WebKit/Source/core/paint/TableCellPainter.cpp b/third_party/WebKit/Source/core/paint/TableCellPainter.cpp index 4c467b7..92225d9 100644 --- a/third_party/WebKit/Source/core/paint/TableCellPainter.cpp +++ b/third_party/WebKit/Source/core/paint/TableCellPainter.cpp
@@ -57,10 +57,10 @@ static EBorderStyle collapsedBorderStyle(EBorderStyle style) { - if (style == OUTSET) - return GROOVE; - if (style == INSET) - return RIDGE; + if (style == BorderStyleOutset) + return BorderStyleGroove; + if (style == BorderStyleInset) + return BorderStyleRidge; return style; }
diff --git a/third_party/WebKit/Source/core/style/BorderData.h b/third_party/WebKit/Source/core/style/BorderData.h index 2e1dc4a..4a12c22 100644 --- a/third_party/WebKit/Source/core/style/BorderData.h +++ b/third_party/WebKit/Source/core/style/BorderData.h
@@ -70,28 +70,28 @@ int borderLeftWidth() const { - if (!m_image.hasImage() && (m_left.style() == BNONE || m_left.style() == BHIDDEN)) + if (!m_image.hasImage() && (m_left.style() == BorderStyleNone || m_left.style() == BorderStyleHidden)) return 0; return m_left.width(); } int borderRightWidth() const { - if (!m_image.hasImage() && (m_right.style() == BNONE || m_right.style() == BHIDDEN)) + if (!m_image.hasImage() && (m_right.style() == BorderStyleNone || m_right.style() == BorderStyleHidden)) return 0; return m_right.width(); } int borderTopWidth() const { - if (!m_image.hasImage() && (m_top.style() == BNONE || m_top.style() == BHIDDEN)) + if (!m_image.hasImage() && (m_top.style() == BorderStyleNone || m_top.style() == BorderStyleHidden)) return 0; return m_top.width(); } int borderBottomWidth() const { - if (!m_image.hasImage() && (m_bottom.style() == BNONE || m_bottom.style() == BHIDDEN)) + if (!m_image.hasImage() && (m_bottom.style() == BorderStyleNone || m_bottom.style() == BorderStyleHidden)) return 0; return m_bottom.width(); }
diff --git a/third_party/WebKit/Source/core/style/BorderEdge.cpp b/third_party/WebKit/Source/core/style/BorderEdge.cpp index 0f4bd67..4736a2b 100644 --- a/third_party/WebKit/Source/core/style/BorderEdge.cpp +++ b/third_party/WebKit/Source/core/style/BorderEdge.cpp
@@ -12,20 +12,20 @@ , isPresent(edgeIsPresent) , style(edgeStyle) { - if (style == DOUBLE && edgeWidth < 3) - style = SOLID; + if (style == BorderStyleDouble && edgeWidth < 3) + style = BorderStyleSolid; } BorderEdge::BorderEdge() : width(0) , isPresent(false) - , style(BHIDDEN) + , style(BorderStyleHidden) { } bool BorderEdge::hasVisibleColorAndStyle() const { - return style > BHIDDEN && color.alpha() > 0; + return style > BorderStyleHidden && color.alpha() > 0; } bool BorderEdge::shouldRender() const @@ -40,10 +40,10 @@ bool BorderEdge::obscuresBackgroundEdge() const { - if (!isPresent || color.hasAlpha() || style == BHIDDEN) + if (!isPresent || color.hasAlpha() || style == BorderStyleHidden) return false; - if (style == DOTTED || style == DASHED) + if (style == BorderStyleDotted || style == BorderStyleDashed) return false; return true; @@ -51,10 +51,10 @@ bool BorderEdge::obscuresBackground() const { - if (!isPresent || color.hasAlpha() || style == BHIDDEN) + if (!isPresent || color.hasAlpha() || style == BorderStyleHidden) return false; - if (style == DOTTED || style == DASHED || style == DOUBLE) + if (style == BorderStyleDotted || style == BorderStyleDashed || style == BorderStyleDouble) return false; return true;
diff --git a/third_party/WebKit/Source/core/style/BorderValue.h b/third_party/WebKit/Source/core/style/BorderValue.h index 1713110..7914be9 100644 --- a/third_party/WebKit/Source/core/style/BorderValue.h +++ b/third_party/WebKit/Source/core/style/BorderValue.h
@@ -40,14 +40,14 @@ : m_color(0) , m_colorIsCurrentColor(true) , m_width(3) - , m_style(BNONE) - , m_isAuto(AUTO_OFF) + , m_style(BorderStyleNone) + , m_isAuto(OutlineIsAutoOff) { } bool nonZero(bool checkStyle = true) const { - return width() && (!checkStyle || m_style != BNONE); + return width() && (!checkStyle || m_style != BorderStyleNone); } bool isTransparent() const @@ -57,7 +57,7 @@ bool isVisible(bool checkStyle = true) const { - return nonZero(checkStyle) && !isTransparent() && (!checkStyle || m_style != BHIDDEN); + return nonZero(checkStyle) && !isTransparent() && (!checkStyle || m_style != BorderStyleHidden); } bool operator==(const BorderValue& o) const @@ -68,9 +68,9 @@ // The default width is 3px, but if the style is none we compute a value of 0 (in ComputedStyle itself) bool visuallyEqual(const BorderValue& o) const { - if (m_style == BNONE && o.m_style == BNONE) + if (m_style == BorderStyleNone && o.m_style == BorderStyleNone) return true; - if (m_style == BHIDDEN && o.m_style == BHIDDEN) + if (m_style == BorderStyleHidden && o.m_style == BorderStyleHidden) return true; return *this == o; }
diff --git a/third_party/WebKit/Source/core/style/CollapsedBorderValue.h b/third_party/WebKit/Source/core/style/CollapsedBorderValue.h index 022590d..b184ce2a 100644 --- a/third_party/WebKit/Source/core/style/CollapsedBorderValue.h +++ b/third_party/WebKit/Source/core/style/CollapsedBorderValue.h
@@ -37,8 +37,8 @@ : m_color(0) , m_colorIsCurrentColor(true) , m_width(0) - , m_style(BNONE) - , m_precedence(BOFF) + , m_style(BorderStyleNone) + , m_precedence(BorderPrecedenceOff) , m_transparent(false) { } @@ -53,9 +53,9 @@ { } - unsigned width() const { return m_style > BHIDDEN ? m_width : 0; } + unsigned width() const { return m_style > BorderStyleHidden ? m_width : 0; } EBorderStyle style() const { return static_cast<EBorderStyle>(m_style); } - bool exists() const { return m_precedence != BOFF; } + bool exists() const { return m_precedence != BorderPrecedenceOff; } StyleColor color() const { return m_colorIsCurrentColor ? StyleColor::currentColor() : StyleColor(m_color); } bool isTransparent() const { return m_transparent; } EBorderPrecedence precedence() const { return static_cast<EBorderPrecedence>(m_precedence); } @@ -72,7 +72,7 @@ bool isVisible() const { - return style() > BHIDDEN && !isTransparent() && exists(); + return style() > BorderStyleHidden && !isTransparent() && exists(); } bool shouldPaint(const CollapsedBorderValue& tableCurrentBorderValue) const
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.cpp b/third_party/WebKit/Source/core/style/ComputedStyle.cpp index 0033542..415902e 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.cpp +++ b/third_party/WebKit/Source/core/style/ComputedStyle.cpp
@@ -641,14 +641,14 @@ // In the collapsing border model, 'hidden' suppresses other borders, while 'none' // does not, so these style differences can be width differences. if (inherited_flags._border_collapse - && ((borderTopStyle() == BHIDDEN && other.borderTopStyle() == BNONE) - || (borderTopStyle() == BNONE && other.borderTopStyle() == BHIDDEN) - || (borderBottomStyle() == BHIDDEN && other.borderBottomStyle() == BNONE) - || (borderBottomStyle() == BNONE && other.borderBottomStyle() == BHIDDEN) - || (borderLeftStyle() == BHIDDEN && other.borderLeftStyle() == BNONE) - || (borderLeftStyle() == BNONE && other.borderLeftStyle() == BHIDDEN) - || (borderRightStyle() == BHIDDEN && other.borderRightStyle() == BNONE) - || (borderRightStyle() == BNONE && other.borderRightStyle() == BHIDDEN))) + && ((borderTopStyle() == BorderStyleHidden && other.borderTopStyle() == BorderStyleNone) + || (borderTopStyle() == BorderStyleNone && other.borderTopStyle() == BorderStyleHidden) + || (borderBottomStyle() == BorderStyleHidden && other.borderBottomStyle() == BorderStyleNone) + || (borderBottomStyle() == BorderStyleNone && other.borderBottomStyle() == BorderStyleHidden) + || (borderLeftStyle() == BorderStyleHidden && other.borderLeftStyle() == BorderStyleNone) + || (borderLeftStyle() == BorderStyleNone && other.borderLeftStyle() == BorderStyleHidden) + || (borderRightStyle() == BorderStyleHidden && other.borderRightStyle() == BorderStyleNone) + || (borderRightStyle() == BorderStyleNone && other.borderRightStyle() == BorderStyleHidden))) return true; } else if (noninherited_flags.effectiveDisplay == LIST_ITEM) { if (inherited_flags._list_style_type != other.inherited_flags._list_style_type @@ -1514,7 +1514,7 @@ Color ComputedStyle::colorIncludingFallback(int colorProperty, bool visitedLink) const { StyleColor result(StyleColor::currentColor()); - EBorderStyle borderStyle = BNONE; + EBorderStyle borderStyle = BorderStyleNone; switch (colorProperty) { case CSSPropertyBackgroundColor: result = visitedLink ? visitedLinkBackgroundColor() : backgroundColor(); @@ -1578,7 +1578,7 @@ // FIXME: Treating styled borders with initial color differently causes problems // See crbug.com/316559, crbug.com/276231 - if (!visitedLink && (borderStyle == INSET || borderStyle == OUTSET || borderStyle == RIDGE || borderStyle == GROOVE)) + if (!visitedLink && (borderStyle == BorderStyleInset || borderStyle == BorderStyleOutset || borderStyle == BorderStyleRidge || borderStyle == BorderStyleGroove)) return Color(238, 238, 238); return visitedLink ? visitedLinkColor() : color(); }
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.h b/third_party/WebKit/Source/core/style/ComputedStyle.h index dc34e43..d426901 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.h +++ b/third_party/WebKit/Source/core/style/ComputedStyle.h
@@ -561,11 +561,11 @@ int outlineWidth() const { - if (m_background->outline().style() == BNONE) + if (m_background->outline().style() == BorderStyleNone) return 0; return m_background->outline().width(); } - bool hasOutline() const { return outlineWidth() > 0 && outlineStyle() > BHIDDEN; } + bool hasOutline() const { return outlineWidth() > 0 && outlineStyle() > BorderStyleHidden; } EBorderStyle outlineStyle() const { return m_background->outline().style(); } OutlineIsAuto outlineStyleIsAuto() const { return static_cast<OutlineIsAuto>(m_background->outline().isAuto()); } int outlineOutsetExtent() const; @@ -763,7 +763,7 @@ int outlineOffset() const { - if (m_background->outline().style() == BNONE) + if (m_background->outline().style() == BorderStyleNone) return 0; return m_background->outline().offset(); } @@ -1647,9 +1647,9 @@ bool hasAuthorBorder() const { return rareNonInheritedData->m_hasAuthorBorder; }; // Initial values for all the properties - static EBorderCollapse initialBorderCollapse() { return BSEPARATE; } - static EBorderStyle initialBorderStyle() { return BNONE; } - static OutlineIsAuto initialOutlineStyleIsAuto() { return AUTO_OFF; } + static EBorderCollapse initialBorderCollapse() { return BorderCollapseSeparate; } + static EBorderStyle initialBorderStyle() { return BorderStyleNone; } + static OutlineIsAuto initialOutlineStyleIsAuto() { return OutlineIsAutoOff; } static NinePieceImage initialNinePieceImage() { return NinePieceImage(); } static LengthSize initialBorderRadius() { return LengthSize(Length(0, Fixed), Length(0, Fixed)); } static ECaptionSide initialCaptionSide() { return CAPTOP; } @@ -1710,7 +1710,7 @@ static int initialOutlineOffset() { return 0; } static float initialOpacity() { return 1.0f; } static EBoxAlignment initialBoxAlign() { return BSTRETCH; } - static EBoxDecorationBreak initialBoxDecorationBreak() { return DSLICE; } + static EBoxDecorationBreak initialBoxDecorationBreak() { return BoxDecorationBreakSlice; } static EBoxDirection initialBoxDirection() { return BNORMAL; } static EBoxLines initialBoxLines() { return SINGLE; } static EBoxOrient initialBoxOrient() { return HORIZONTAL; } @@ -1718,7 +1718,7 @@ static float initialBoxFlex() { return 0.0f; } static unsigned initialBoxFlexGroup() { return 1; } static unsigned initialBoxOrdinalGroup() { return 1; } - static EBoxSizing initialBoxSizing() { return CONTENT_BOX; } + static EBoxSizing initialBoxSizing() { return BoxSizingContentBox; } static StyleReflection* initialBoxReflect() { return 0; } static float initialFlexGrow() { return 0; } static float initialFlexShrink() { return 1; } @@ -1732,8 +1732,8 @@ static EUserDrag initialUserDrag() { return DRAG_AUTO; } static EUserSelect initialUserSelect() { return SELECT_TEXT; } static TextOverflow initialTextOverflow() { return TextOverflowClip; } - static EMarginCollapse initialMarginBeforeCollapse() { return MCOLLAPSE; } - static EMarginCollapse initialMarginAfterCollapse() { return MCOLLAPSE; } + static EMarginCollapse initialMarginBeforeCollapse() { return MarginCollapseCollapse; } + static EMarginCollapse initialMarginAfterCollapse() { return MarginCollapseCollapse; } static EWordBreak initialWordBreak() { return NormalWordBreak; } static EOverflowWrap initialOverflowWrap() { return NormalOverflowWrap; } static LineBreak initialLineBreak() { return LineBreakAuto; }
diff --git a/third_party/WebKit/Source/core/style/ComputedStyleConstants.h b/third_party/WebKit/Source/core/style/ComputedStyleConstants.h index 8c110c0..df5c62b 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyleConstants.h +++ b/third_party/WebKit/Source/core/style/ComputedStyleConstants.h
@@ -73,15 +73,26 @@ enum ColumnSpan { ColumnSpanNone = 0, ColumnSpanAll }; -enum EBorderCollapse { BSEPARATE = 0, BCOLLAPSE = 1 }; +enum EBorderCollapse { BorderCollapseSeparate = 0, BorderCollapseCollapse = 1 }; // These have been defined in the order of their precedence for border-collapsing. Do // not change this order! This order also must match the order in CSSValueKeywords.in. -enum EBorderStyle { BNONE, BHIDDEN, INSET, GROOVE, OUTSET, RIDGE, DOTTED, DASHED, SOLID, DOUBLE }; +enum EBorderStyle { + BorderStyleNone, + BorderStyleHidden, + BorderStyleInset, + BorderStyleGroove, + BorderStyleOutset, + BorderStyleRidge, + BorderStyleDotted, + BorderStyleDashed, + BorderStyleSolid, + BorderStyleDouble +}; -enum EBorderPrecedence { BOFF, BTABLE, BCOLGROUP, BCOL, BROWGROUP, BROW, BCELL }; +enum EBorderPrecedence { BorderPrecedenceOff, BorderPrecedenceTable, BorderPrecedenceColumnGroup, BorderPrecedenceColumn, BorderPrecedenceRowGroup, BorderPrecedenceRow, BorderPrecedenceCell }; -enum OutlineIsAuto { AUTO_OFF = 0, AUTO_ON }; +enum OutlineIsAuto { OutlineIsAutoOff = 0, OutlineIsAutoOn }; enum EPosition { StaticPosition = 0, @@ -96,15 +107,15 @@ NoFloat, LeftFloat, RightFloat }; -enum EMarginCollapse { MCOLLAPSE, MSEPARATE, MDISCARD }; +enum EMarginCollapse { MarginCollapseCollapse, MarginCollapseSeparate, MarginCollapseDiscard }; // Box decoration attributes. Not inherited. -enum EBoxDecorationBreak { DSLICE, DCLONE }; +enum EBoxDecorationBreak { BoxDecorationBreakSlice, BoxDecorationBreakClone }; // Box attributes. Not inherited. -enum EBoxSizing { CONTENT_BOX, BORDER_BOX }; +enum EBoxSizing { BoxSizingContentBox, BoxSizingBorderBox }; // Random visual rendering model attributes. Not inherited.
diff --git a/third_party/WebKit/Source/core/style/OutlineValue.h b/third_party/WebKit/Source/core/style/OutlineValue.h index 6018048..eddf7d183 100644 --- a/third_party/WebKit/Source/core/style/OutlineValue.h +++ b/third_party/WebKit/Source/core/style/OutlineValue.h
@@ -51,7 +51,7 @@ bool visuallyEqual(const OutlineValue& o) const { - if (m_style == BNONE && o.m_style == BNONE) + if (m_style == BorderStyleNone && o.m_style == BorderStyleNone) return true; return *this == o; }
diff --git a/third_party/WebKit/Source/core/style/OutlineValueTest.cpp b/third_party/WebKit/Source/core/style/OutlineValueTest.cpp index de809a8a..e91760e 100644 --- a/third_party/WebKit/Source/core/style/OutlineValueTest.cpp +++ b/third_party/WebKit/Source/core/style/OutlineValueTest.cpp
@@ -18,7 +18,7 @@ outline2.setOffset(10); EXPECT_TRUE(outline1.visuallyEqual(outline2)); - outline2.setStyle(DOTTED); + outline2.setStyle(BorderStyleDotted); outline1.setOffset(10); EXPECT_FALSE(outline1.visuallyEqual(outline2)); } @@ -28,8 +28,8 @@ OutlineValue outline1; OutlineValue outline2; - outline1.setStyle(DOTTED); - outline2.setStyle(DOTTED); + outline1.setStyle(BorderStyleDotted); + outline2.setStyle(BorderStyleDotted); EXPECT_TRUE(outline1.visuallyEqual(outline2)); outline1.setOffset(10); @@ -44,14 +44,14 @@ OutlineValue outline1; OutlineValue outline2; - outline1.setStyle(DOTTED); - outline2.setStyle(DOTTED); + outline1.setStyle(BorderStyleDotted); + outline2.setStyle(BorderStyleDotted); EXPECT_TRUE(outline1.visuallyEqual(outline2)); - outline1.setIsAuto(AUTO_ON); + outline1.setIsAuto(OutlineIsAutoOn); EXPECT_FALSE(outline1.visuallyEqual(outline2)); - outline2.setIsAuto(AUTO_ON); + outline2.setIsAuto(OutlineIsAutoOn); EXPECT_TRUE(outline1.visuallyEqual(outline2)); }
diff --git a/third_party/WebKit/Source/core/style/StyleBoxData.cpp b/third_party/WebKit/Source/core/style/StyleBoxData.cpp index ddb4272..e24e2c1 100644 --- a/third_party/WebKit/Source/core/style/StyleBoxData.cpp +++ b/third_party/WebKit/Source/core/style/StyleBoxData.cpp
@@ -40,8 +40,8 @@ , m_maxHeight(ComputedStyle::initialMaxSize()) , m_zIndex(0) , m_hasAutoZIndex(true) - , m_boxSizing(CONTENT_BOX) - , m_boxDecorationBreak(DSLICE) + , m_boxSizing(BoxSizingContentBox) + , m_boxDecorationBreak(BoxDecorationBreakSlice) { }
diff --git a/third_party/WebKit/Source/core/style/StyleMultiColData.h b/third_party/WebKit/Source/core/style/StyleMultiColData.h index 3e8d13b..a81b03f 100644 --- a/third_party/WebKit/Source/core/style/StyleMultiColData.h +++ b/third_party/WebKit/Source/core/style/StyleMultiColData.h
@@ -48,7 +48,7 @@ unsigned short ruleWidth() const { - if (m_rule.style() == BNONE || m_rule.style() == BHIDDEN) + if (m_rule.style() == BorderStyleNone || m_rule.style() == BorderStyleHidden) return 0; return m_rule.width(); }
diff --git a/third_party/WebKit/Source/core/style/StyleRareNonInheritedData.cpp b/third_party/WebKit/Source/core/style/StyleRareNonInheritedData.cpp index 2890f35..f371ec5 100644 --- a/third_party/WebKit/Source/core/style/StyleRareNonInheritedData.cpp +++ b/third_party/WebKit/Source/core/style/StyleRareNonInheritedData.cpp
@@ -99,8 +99,8 @@ , m_backfaceVisibility(ComputedStyle::initialBackfaceVisibility()) , userDrag(ComputedStyle::initialUserDrag()) , textOverflow(ComputedStyle::initialTextOverflow()) - , marginBeforeCollapse(MCOLLAPSE) - , marginAfterCollapse(MCOLLAPSE) + , marginBeforeCollapse(MarginCollapseCollapse) + , marginAfterCollapse(MarginCollapseCollapse) , m_appearance(ComputedStyle::initialAppearance()) , m_textDecorationStyle(ComputedStyle::initialTextDecorationStyle()) , m_wrapFlow(ComputedStyle::initialWrapFlow())
diff --git a/third_party/WebKit/Source/core/svg/SVGResourceClient.cpp b/third_party/WebKit/Source/core/svg/SVGResourceClient.cpp index a5da8ab..626c77b8 100644 --- a/third_party/WebKit/Source/core/svg/SVGResourceClient.cpp +++ b/third_party/WebKit/Source/core/svg/SVGResourceClient.cpp
@@ -4,7 +4,9 @@ #include "core/svg/SVGResourceClient.h" +#include "core/fetch/DocumentResourceReference.h" #include "core/layout/svg/LayoutSVGResourceContainer.h" +#include "core/layout/svg/ReferenceFilterBuilder.h" namespace blink { @@ -12,29 +14,56 @@ { } -void SVGResourceClient::addFilterReference(SVGFilterElement* filter) +void SVGResourceClient::addFilterReferences(const FilterOperations& operations, const Document& document) { - if (filter->layoutObject()) - toLayoutSVGResourceContainer(filter->layoutObject())->addResourceClient(this); - else - filter->addClient(this); - m_filterReferences.add(filter); + for (size_t i = 0; i < operations.size(); ++i) { + RefPtrWillBeRawPtr<FilterOperation> filterOperation = operations.operations().at(i); + if (filterOperation->type() != FilterOperation::REFERENCE) + continue; + ReferenceFilterOperation* referenceFilterOperation = toReferenceFilterOperation(filterOperation.get()); + DocumentResourceReference* documentReference = ReferenceFilterBuilder::documentResourceReference(referenceFilterOperation); + DocumentResource* cachedSVGDocument = documentReference ? documentReference->document() : 0; + + if (cachedSVGDocument) { + cachedSVGDocument->addClient(this); + m_externalFilterReferences.append(cachedSVGDocument); + } else { + Element* element = document.getElementById(referenceFilterOperation->fragment()); + if (!isSVGFilterElement(element)) + continue; + SVGFilterElement* filter = toSVGFilterElement(element); + if (filter->layoutObject()) + toLayoutSVGResourceContainer(filter->layoutObject())->addResourceClient(this); + else + filter->addClient(this); + m_internalFilterReferences.add(filter); + } + } } void SVGResourceClient::clearFilterReferences() { - for (SVGFilterElement* filter : m_filterReferences) { + for (SVGFilterElement* filter : m_internalFilterReferences) { if (filter->layoutObject()) toLayoutSVGResourceContainer(filter->layoutObject())->removeResourceClient(this); else filter->removeClient(this); } - m_filterReferences.clear(); + m_internalFilterReferences.clear(); + + for (RefPtrWillBeRawPtr<DocumentResource> documentResource : m_externalFilterReferences) + documentResource->removeClient(this); + m_externalFilterReferences.clear(); } void SVGResourceClient::filterWillBeDestroyed(SVGFilterElement* filter) { - m_filterReferences.remove(filter); + m_internalFilterReferences.remove(filter); + filterNeedsInvalidation(); +} + +void SVGResourceClient::notifyFinished(Resource*) +{ filterNeedsInvalidation(); }
diff --git a/third_party/WebKit/Source/core/svg/SVGResourceClient.h b/third_party/WebKit/Source/core/svg/SVGResourceClient.h index acee5f8c..f1f6f70 100644 --- a/third_party/WebKit/Source/core/svg/SVGResourceClient.h +++ b/third_party/WebKit/Source/core/svg/SVGResourceClient.h
@@ -6,25 +6,32 @@ #define SVGResourceClient_h #include "core/CoreExport.h" +#include "core/fetch/DocumentResource.h" #include "core/svg/SVGFilterElement.h" #include "platform/heap/Handle.h" namespace blink { +class Document; +class FilterOperations; class SVGFilterElement; -class CORE_EXPORT SVGResourceClient { +class CORE_EXPORT SVGResourceClient : DocumentResourceClient { public: virtual ~SVGResourceClient(); - void addFilterReference(SVGFilterElement*); + void addFilterReferences(const FilterOperations&, const Document&); void clearFilterReferences(); virtual void filterNeedsInvalidation() = 0; void filterWillBeDestroyed(SVGFilterElement*); + void notifyFinished(Resource*) override; + String debugName() const override { return "SVGResourceClient"; } + private: - WillBePersistentHeapHashSet<RawPtrWillBeWeakMember<SVGFilterElement>> m_filterReferences; + WillBePersistentHeapHashSet<RawPtrWillBeWeakMember<SVGFilterElement>> m_internalFilterReferences; + WillBePersistentHeapVector<RefPtrWillBeMember<DocumentResource>> m_externalFilterReferences; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp b/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp index 062cdb53..ebe19d2 100644 --- a/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
@@ -21,12 +21,15 @@ #include "core/svg/SVGTitleElement.h" #include "core/SVGNames.h" +#include "core/dom/ChildListMutationScope.h" #include "core/dom/Document.h" +#include "core/dom/Text.h" namespace blink { inline SVGTitleElement::SVGTitleElement(Document& document) : SVGElement(SVGNames::titleTag, document) + , m_ignoreTitleUpdatesWhenChildrenChange(false) { } @@ -52,8 +55,23 @@ void SVGTitleElement::childrenChanged(const ChildrenChange& change) { SVGElement::childrenChanged(change); - if (inDocument() && document().isSVGDocument()) + if (inDocument() && document().isSVGDocument() && !m_ignoreTitleUpdatesWhenChildrenChange) document().setTitleElement(this); } +void SVGTitleElement::setText(const String& value) +{ + RefPtrWillBeRawPtr<Node> protectFromMutationEvents(this); + ChildListMutationScope mutation(*this); + + { + // Avoid calling Document::setTitleElement() during intermediate steps. + TemporaryChange<bool> inhibitTitleUpdateScope(m_ignoreTitleUpdatesWhenChildrenChange, !value.isEmpty()); + removeChildren(OmitSubtreeModifiedEvent); + } + + if (!value.isEmpty()) + appendChild(document().createTextNode(value.impl()), IGNORE_EXCEPTION); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/svg/SVGTitleElement.h b/third_party/WebKit/Source/core/svg/SVGTitleElement.h index 31e9753..1adc590 100644 --- a/third_party/WebKit/Source/core/svg/SVGTitleElement.h +++ b/third_party/WebKit/Source/core/svg/SVGTitleElement.h
@@ -30,6 +30,8 @@ public: DECLARE_NODE_FACTORY(SVGTitleElement); + void setText(const String&); + private: explicit SVGTitleElement(Document&); @@ -38,6 +40,8 @@ void childrenChanged(const ChildrenChange&) override; bool layoutObjectIsNeeded(const ComputedStyle&) override { return false; } + + bool m_ignoreTitleUpdatesWhenChildrenChange; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/svg/SVGUseElement.cpp b/third_party/WebKit/Source/core/svg/SVGUseElement.cpp index a7996516..3f2d1ec 100644 --- a/third_party/WebKit/Source/core/svg/SVGUseElement.cpp +++ b/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
@@ -151,24 +151,27 @@ static void transferUseWidthAndHeightIfNeeded(const SVGUseElement& use, SVGElement& shadowElement, const SVGElement& originalElement) { DEFINE_STATIC_LOCAL(const AtomicString, hundredPercentString, ("100%", AtomicString::ConstructFromLiteral)); - if (isSVGSymbolElement(shadowElement)) { - // Spec (<use> on <symbol>): This generated 'svg' will always have explicit values for attributes width and height. - // If attributes width and/or height are provided on the 'use' element, then these attributes - // will be transferred to the generated 'svg'. If attributes width and/or height are not specified, - // the generated 'svg' element will use values of 100% for these attributes. - shadowElement.setAttribute(SVGNames::widthAttr, use.width()->isSpecified() ? AtomicString(use.width()->currentValue()->valueAsString()) : hundredPercentString); - shadowElement.setAttribute(SVGNames::heightAttr, use.height()->isSpecified() ? AtomicString(use.height()->currentValue()->valueAsString()) : hundredPercentString); - } else if (isSVGSVGElement(shadowElement)) { - // Spec (<use> on <svg>): If attributes width and/or height are provided on the 'use' element, then these - // values will override the corresponding attributes on the 'svg' in the generated tree. - if (use.width()->isSpecified()) - shadowElement.setAttribute(SVGNames::widthAttr, AtomicString(use.width()->currentValue()->valueAsString())); - else - shadowElement.setAttribute(SVGNames::widthAttr, originalElement.getAttribute(SVGNames::widthAttr)); - if (use.height()->isSpecified()) - shadowElement.setAttribute(SVGNames::heightAttr, AtomicString(use.height()->currentValue()->valueAsString())); - else - shadowElement.setAttribute(SVGNames::heightAttr, originalElement.getAttribute(SVGNames::heightAttr)); + // Use |originalElement| for checking the element type, because we will + // have replaced a <symbol> with an <svg> in the instance tree. + if (isSVGSymbolElement(originalElement)) { + // Spec (<use> on <symbol>): This generated 'svg' will always have + // explicit values for attributes width and height. If attributes + // width and/or height are provided on the 'use' element, then these + // attributes will be transferred to the generated 'svg'. If attributes + // width and/or height are not specified, the generated 'svg' element + // will use values of 100% for these attributes. + shadowElement.setAttribute(SVGNames::widthAttr, + use.width()->isSpecified() ? AtomicString(use.width()->currentValue()->valueAsString()) : hundredPercentString); + shadowElement.setAttribute(SVGNames::heightAttr, + use.height()->isSpecified() ? AtomicString(use.height()->currentValue()->valueAsString()) : hundredPercentString); + } else if (isSVGSVGElement(originalElement)) { + // Spec (<use> on <svg>): If attributes width and/or height are + // provided on the 'use' element, then these values will override the + // corresponding attributes on the 'svg' in the generated tree. + shadowElement.setAttribute(SVGNames::widthAttr, + use.width()->isSpecified() ? AtomicString(use.width()->currentValue()->valueAsString()) : originalElement.getAttribute(SVGNames::widthAttr)); + shadowElement.setAttribute(SVGNames::heightAttr, + use.height()->isSpecified() ? AtomicString(use.height()->currentValue()->valueAsString()) : originalElement.getAttribute(SVGNames::heightAttr)); } } @@ -245,21 +248,15 @@ SVGGraphicsElement::svgAttributeChanged(attrName); } -static bool isDisallowedElement(const Node& node) +static bool isDisallowedElement(const Element& element) { // Spec: "Any 'svg', 'symbol', 'g', graphics element or other 'use' is potentially a template object that can be re-used // (i.e., "instanced") in the SVG document via a 'use' element." // "Graphics Element" is defined as 'circle', 'ellipse', 'image', 'line', 'path', 'polygon', 'polyline', 'rect', 'text' // Excluded are anything that is used by reference or that only make sense to appear once in a document. - // We must also allow the shadow roots of other use elements. - if (node.isShadowRoot() || node.isTextNode()) - return false; - - if (!node.isSVGElement()) + if (!element.isSVGElement()) return true; - const Element& element = toElement(node); - DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowedElementTags, ()); if (allowedElementTags.isEmpty()) { allowedElementTags.add(SVGNames::aTag); @@ -364,6 +361,64 @@ ASSERT(!(targetIterator != targetRange.end())); } +// We don't walk the target tree element-by-element, and clone each element, +// but instead use cloneNode(deep=true). This is an optimization for the common +// case where <use> doesn't contain disallowed elements (ie. <foreignObject>). +// Though if there are disallowed elements in the subtree, we have to remove +// them. For instance: <use> on <g> containing <foreignObject> (indirect +// case). +static inline void removeDisallowedElementsFromSubtree(SVGElement& subtree) +{ + ASSERT(!subtree.inDocument()); + Element* element = ElementTraversal::firstWithin(subtree); + while (element) { + if (isDisallowedElement(*element)) { + Element* next = ElementTraversal::nextSkippingChildren(*element, &subtree); + // The subtree is not in document so this won't generate events that could mutate the tree. + element->parentNode()->removeChild(element); + element = next; + } else { + element = ElementTraversal::next(*element, &subtree); + } + } +} + +static void moveChildrenToReplacementElement(ContainerNode& sourceRoot, ContainerNode& destinationRoot) +{ + for (RefPtrWillBeRawPtr<Node> child = sourceRoot.firstChild(); child; ) { + RefPtrWillBeRawPtr<Node> nextChild = child->nextSibling(); + destinationRoot.appendChild(child); + child = nextChild.release(); + } +} + +PassRefPtrWillBeRawPtr<Element> SVGUseElement::createInstanceTree(SVGElement& targetRoot) const +{ + RefPtrWillBeRawPtr<Element> instanceRoot = targetRoot.cloneElementWithChildren(); + ASSERT(instanceRoot->isSVGElement()); + if (isSVGSymbolElement(targetRoot)) { + // Spec: The referenced 'symbol' and its contents are deep-cloned into + // the generated tree, with the exception that the 'symbol' is replaced + // by an 'svg'. This generated 'svg' will always have explicit values + // for attributes width and height. If attributes width and/or height + // are provided on the 'use' element, then these attributes will be + // transferred to the generated 'svg'. If attributes width and/or + // height are not specified, the generated 'svg' element will use + // values of 100% for these attributes. + RefPtrWillBeRawPtr<SVGSVGElement> svgElement = SVGSVGElement::create(targetRoot.document()); + // Transfer all data (attributes, etc.) from the <symbol> to the new + // <svg> element. + svgElement->cloneDataFromElement(*instanceRoot); + // Move already cloned elements to the new <svg> element. + moveChildrenToReplacementElement(*instanceRoot, *svgElement); + instanceRoot = svgElement.release(); + } + transferUseWidthAndHeightIfNeeded(*this, toSVGElement(*instanceRoot), targetRoot); + associateCorrespondingElements(targetRoot, toSVGElement(*instanceRoot)); + removeDisallowedElementsFromSubtree(toSVGElement(*instanceRoot)); + return instanceRoot.release(); +} + void SVGUseElement::buildShadowAndInstanceTree(SVGElement& target) { ASSERT(!m_targetElementInstance); @@ -380,18 +435,15 @@ return; // Set up root SVG element in shadow tree. - RefPtrWillBeRawPtr<Element> newChild = target.cloneElementWithoutChildren(); - m_targetElementInstance = toSVGElement(newChild.get()); - ShadowRoot* shadowTreeRootElement = userAgentShadowRoot(); - shadowTreeRootElement->appendChild(newChild.release()); - // Clone the target subtree into the shadow tree, not handling <use> and <symbol> yet. + RefPtrWillBeRawPtr<Element> instanceRoot = createInstanceTree(target); + m_targetElementInstance = toSVGElement(instanceRoot.get()); + ShadowRoot* shadowTreeRootElement = userAgentShadowRoot(); + shadowTreeRootElement->appendChild(instanceRoot.release()); - // SVG specification does not say a word about <use> & cycles. My view on this is: just ignore it! - // Non-appearing <use> content is easier to debug, then half-appearing content. - buildShadowTree(target, *m_targetElementInstance, false); + addReferencesToFirstDegreeNestedUseElements(target); - if (instanceTreeIsLoading(m_targetElementInstance.get())) { + if (instanceTreeIsLoading()) { cloneNonMarkupEventListeners(); return; } @@ -408,16 +460,13 @@ return; } - // Expand all <symbol> elements in the shadow tree. - // Expand means: replace the actual <symbol> element by the <svg> element. - expandSymbolElementsInShadowTree(); - + // If the instance root was a <use>, it could have been replaced now, so + // reset |m_targetElementInstance|. m_targetElementInstance = toSVGElement(shadowTreeRootElement->firstChild()); - transferUseWidthAndHeightIfNeeded(*this, *m_targetElementInstance, *m_targetElementInstance->correspondingElement()); - cloneNonMarkupEventListeners(); - ASSERT(m_targetElementInstance->parentNode() == shadowTreeRootElement); + cloneNonMarkupEventListeners(); + // Update relative length information. updateRelativeLengthsInformation(); } @@ -480,35 +529,18 @@ return &toSVGGraphicsElement(element); } -void SVGUseElement::buildShadowTree(SVGElement& target, SVGElement& targetInstance, bool foundUse) +void SVGUseElement::addReferencesToFirstDegreeNestedUseElements(SVGElement& target) { - ASSERT(!isDisallowedElement(target)); - - // Spec: If the referenced object is itself a 'use', or if there are 'use' subelements within the referenced - // object, the instance tree will contain recursive expansion of the indirect references to form a complete tree. - if (isSVGUseElement(target)) { - // We only need to track first degree <use> dependencies. Indirect references are handled - // as the invalidation bubbles up the dependency chain. - if (!foundUse && !isStructurallyExternal()) { - addReferenceTo(&target); - foundUse = true; - } - } - - targetInstance.setCorrespondingElement(&target); - - for (RefPtrWillBeRawPtr<Node> child = target.firstChild(); child; child = child->nextSibling()) { - // Skip any disallowed element. - if (isDisallowedElement(*child)) - continue; - - RefPtrWillBeRawPtr<Node> newChild = child->cloneNode(false); - targetInstance.appendChild(newChild.get()); - if (newChild->isSVGElement()) { - // Enter recursion, appending new instance tree nodes to the "instance" object. - buildShadowTree(toSVGElement(*child), toSVGElement(*newChild), foundUse); - } - } + // Don't track references to external documents. + if (isStructurallyExternal()) + return; + // We only need to track first degree <use> dependencies. Indirect + // references are handled as the invalidation bubbles up the dependency + // chain. + SVGUseElement* useElement = + isSVGUseElement(target) ? toSVGUseElement(&target) : Traversal<SVGUseElement>::firstWithin(target); + for (; useElement; useElement = Traversal<SVGUseElement>::nextSkippingChildren(*useElement, &target)) + addReferenceTo(useElement); } void SVGUseElement::cloneNonMarkupEventListeners() @@ -545,37 +577,6 @@ return false; } -// We don't walk the target tree element-by-element, and clone each element, -// but instead use cloneNode(deep=true). This is an optimization for the common -// case where <use> doesn't contain disallowed elements (ie. <foreignObject>). -// Though if there are disallowed elements in the subtree, we have to remove -// them. For instance: <use> on <g> containing <foreignObject> (indirect -// case). -static inline void removeDisallowedElementsFromSubtree(SVGElement& subtree) -{ - ASSERT(!subtree.inDocument()); - Element* element = ElementTraversal::firstWithin(subtree); - while (element) { - if (isDisallowedElement(*element)) { - Element* next = ElementTraversal::nextSkippingChildren(*element, &subtree); - // The subtree is not in document so this won't generate events that could mutate the tree. - element->parentNode()->removeChild(element); - element = next; - } else { - element = ElementTraversal::next(*element, &subtree); - } - } -} - -static void moveChildrenToReplacementElement(ContainerNode& sourceRoot, ContainerNode& destinationRoot) -{ - for (RefPtrWillBeRawPtr<Node> child = sourceRoot.firstChild(); child; ) { - RefPtrWillBeRawPtr<Node> nextChild = child->nextSibling(); - destinationRoot.appendChild(child); - child = nextChild.release(); - } -} - // Spec: In the generated content, the 'use' will be replaced by 'g', where all // attributes from the 'use' element except for x, y, width, height and // xlink:href are transferred to the generated 'g' element. @@ -621,14 +622,8 @@ // Move already cloned elements to the new <g> element. moveChildrenToReplacementElement(*use, *cloneParent); - if (target) { - RefPtrWillBeRawPtr<Element> instanceRoot = target->cloneElementWithChildren(); - ASSERT(instanceRoot->isSVGElement()); - associateCorrespondingElements(*target, toSVGElement(*instanceRoot)); - transferUseWidthAndHeightIfNeeded(*use, toSVGElement(*instanceRoot), *target); - removeDisallowedElementsFromSubtree(toSVGElement(*instanceRoot)); - cloneParent->appendChild(instanceRoot.release()); - } + if (target) + cloneParent->appendChild(use->createInstanceTree(*target)); RefPtrWillBeRawPtr<SVGElement> replacingElement(cloneParent.get()); @@ -640,36 +635,6 @@ return true; } -void SVGUseElement::expandSymbolElementsInShadowTree() -{ - ShadowRoot* shadowRoot = userAgentShadowRoot(); - for (RefPtrWillBeRawPtr<SVGSymbolElement> symbol = Traversal<SVGSymbolElement>::firstWithin(*shadowRoot); symbol; ) { - // Spec: The referenced 'symbol' and its contents are deep-cloned into the generated tree, - // with the exception that the 'symbol' is replaced by an 'svg'. This generated 'svg' will - // always have explicit values for attributes width and height. If attributes width and/or - // height are provided on the 'use' element, then these attributes will be transferred to - // the generated 'svg'. If attributes width and/or height are not specified, the generated - // 'svg' element will use values of 100% for these attributes. - SVGElement& originalSymbol = *symbol->correspondingElement(); - RefPtrWillBeRawPtr<SVGSVGElement> svgElement = SVGSVGElement::create(originalSymbol.document()); - // Transfer all data (attributes, etc.) from <symbol> to the new <svg> element. - svgElement->cloneDataFromElement(*symbol); - svgElement->setCorrespondingElement(&originalSymbol); - - // Move already cloned elements to the new <svg> element. - moveChildrenToReplacementElement(*symbol, *svgElement); - - removeDisallowedElementsFromSubtree(*svgElement); - - RefPtrWillBeRawPtr<SVGElement> replacingElement(svgElement.get()); - - // Replace <symbol> with <svg>. - symbol->parentNode()->replaceChild(svgElement.release(), symbol); - - symbol = Traversal<SVGSymbolElement>::next(*replacingElement, shadowRoot); - } -} - void SVGUseElement::invalidateShadowTree() { if (!inActiveDocument() || m_needsShadowTreeRecreation) @@ -770,10 +735,10 @@ && m_resource->document(); } -bool SVGUseElement::instanceTreeIsLoading(const SVGElement* targetInstance) +bool SVGUseElement::instanceTreeIsLoading() const { - for (const SVGElement* element = targetInstance; element; element = Traversal<SVGElement>::next(*element, targetInstance)) { - if (isSVGUseElement(*element) && toSVGUseElement(*element).resourceIsStillLoading()) + for (const SVGUseElement& useElement : Traversal<SVGUseElement>::descendantsOf(*userAgentShadowRoot())) { + if (useElement.resourceIsStillLoading()) return true; } return false;
diff --git a/third_party/WebKit/Source/core/svg/SVGUseElement.h b/third_party/WebKit/Source/core/svg/SVGUseElement.h index 6cc065d..e5ea5486 100644 --- a/third_party/WebKit/Source/core/svg/SVGUseElement.h +++ b/third_party/WebKit/Source/core/svg/SVGUseElement.h
@@ -91,19 +91,19 @@ // Instance tree handling void buildShadowAndInstanceTree(SVGElement& target); void clearInstanceRoot(); - void buildShadowTree(SVGElement& target, SVGElement& targetInstance, bool foundUse); + PassRefPtrWillBeRawPtr<Element> createInstanceTree(SVGElement& targetRoot) const; void clearShadowTree(); bool hasCycleUseReferencing(const SVGUseElement&, const ContainerNode& targetInstance, SVGElement*& newTarget) const; bool expandUseElementsInShadowTree(); - void expandSymbolElementsInShadowTree(); void cloneNonMarkupEventListeners(); + void addReferencesToFirstDegreeNestedUseElements(SVGElement& target); void invalidateDependentShadowTrees(); bool resourceIsStillLoading() const; bool resourceIsValid() const; Document* externalDocument() const; - bool instanceTreeIsLoading(const SVGElement*); + bool instanceTreeIsLoading() const; void notifyFinished(Resource*) override; String debugName() const override { return "SVGUseElement"; } void setDocumentResource(PassRefPtrWillBeRawPtr<DocumentResource>);
diff --git a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp index 88567612d..ced72d1 100644 --- a/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
@@ -48,6 +48,7 @@ // passed along to the created 'context'. RefPtrWillBeRawPtr<DedicatedWorkerGlobalScope> context = adoptRefWillBeNoop(new DedicatedWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, timeOrigin, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release())); context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders); + context->setAddressSpace(startupData->m_addressSpace); return context.release(); }
diff --git a/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp b/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp index 7fc49696..349029c 100644 --- a/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp +++ b/third_party/WebKit/Source/core/workers/InProcessWorkerBase.cpp
@@ -98,10 +98,7 @@ dispatchEvent(Event::createCancelable(EventTypeNames::error)); } else { ASSERT(m_contextProxy); - WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart; - if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(executionContext())) - startMode = PauseWorkerGlobalScopeOnStart; - m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(), m_scriptLoader->script(), startMode); + m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(), m_scriptLoader->script()); InspectorInstrumentation::scriptImported(executionContext(), m_scriptLoader->identifier(), m_scriptLoader->script()); } m_contentSecurityPolicy = m_scriptLoader->releaseContentSecurityPolicy();
diff --git a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp index 68557994..1002f172 100644 --- a/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
@@ -54,6 +54,7 @@ // passed along to the created 'context'. RefPtrWillBeRawPtr<SharedWorkerGlobalScope> context = adoptRefWillBeNoop(new SharedWorkerGlobalScope(name, startupData->m_scriptURL, startupData->m_userAgent, thread, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release())); context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders); + context->setAddressSpace(startupData->m_addressSpace); return context.release(); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl index 1d3f4d5..856c451 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl
@@ -47,6 +47,10 @@ // https://developer.chrome.com/devtools/docs/console-api [Replaceable] readonly attribute WorkerConsole console; + // CORS and RFC1918 + // https://mikewest.github.io/cors-rfc1918/#feature-detect + [RuntimeEnabled=CorsRFC1918, ImplementedAs=addressSpaceForBindings] readonly attribute AddressSpace addressSpace; + // Unhandled Promise Rejection Events // https://github.com/domenic/unhandled-rejections-browser-spec [RuntimeEnabled=PromiseRejectionEvent] attribute EventHandler onrejectionhandled;
diff --git a/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h b/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h index 04689e2..078a95b 100644 --- a/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h +++ b/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h
@@ -47,7 +47,7 @@ public: virtual ~WorkerGlobalScopeProxy() { } - virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) = 0; + virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode) = 0; virtual void terminateWorkerGlobalScope() = 0;
diff --git a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp index 4226408..6abe3aef 100644 --- a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.cpp
@@ -33,11 +33,20 @@ { } +WorkerThreadStartMode WorkerInspectorProxy::workerStartMode(ExecutionContext* context) +{ + if (InspectorInstrumentation::shouldWaitForDebuggerOnWorkerStart(context)) + return PauseWorkerGlobalScopeOnStart; + return DontPauseWorkerGlobalScopeOnStart; +} + void WorkerInspectorProxy::workerThreadCreated(ExecutionContext* context, WorkerThread* workerThread, const KURL& url) { m_workerThread = workerThread; m_executionContext = context; - InspectorInstrumentation::didStartWorker(context, this, url); + // We expect everyone starting worker thread to synchronously ask for workerStartMode right before. + bool waitingForDebugger = InspectorInstrumentation::shouldWaitForDebuggerOnWorkerStart(context); + InspectorInstrumentation::didStartWorker(context, this, url, waitingForDebugger); } void WorkerInspectorProxy::workerThreadTerminated()
diff --git a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h index 48326235..44bd045 100644 --- a/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h +++ b/third_party/WebKit/Source/core/workers/WorkerInspectorProxy.h
@@ -6,6 +6,7 @@ #define WorkerInspectorProxy_h #include "core/CoreExport.h" +#include "core/workers/WorkerThread.h" #include "platform/heap/Handle.h" #include "wtf/Forward.h" @@ -15,7 +16,6 @@ class KURL; class WebTraceLocation; class WorkerGlobalScopeProxy; -class WorkerThread; // A proxy for talking to the worker inspector on the worker thread. // All of these methods should be called on the main thread. @@ -35,6 +35,7 @@ DEFINE_INLINE_VIRTUAL_TRACE() { } }; + WorkerThreadStartMode workerStartMode(ExecutionContext*); void workerThreadCreated(ExecutionContext*, WorkerThread*, const KURL&); void workerThreadTerminated();
diff --git a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp index 0a5d87b0..21d5c66 100644 --- a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
@@ -31,6 +31,7 @@ #include "bindings/core/v8/V8GCController.h" #include "core/dom/CrossThreadTask.h" #include "core/dom/Document.h" +#include "core/dom/SecurityContext.h" #include "core/events/ErrorEvent.h" #include "core/events/MessageEvent.h" #include "core/frame/Console.h" @@ -98,7 +99,7 @@ m_workerInspectorProxy->setWorkerGlobalScopeProxy(nullptr); } -void WorkerMessagingProxy::startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode) +void WorkerMessagingProxy::startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode) { // FIXME: This need to be revisited when we support nested worker one day ASSERT(m_executionContext->isDocument()); @@ -112,7 +113,8 @@ ContentSecurityPolicy* csp = m_workerObject->contentSecurityPolicy() ? m_workerObject->contentSecurityPolicy() : document->contentSecurityPolicy(); ASSERT(csp); - OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(scriptURL, userAgent, sourceCode, nullptr, startMode, csp->headers(), starterOrigin, m_workerClients.release()); + WorkerThreadStartMode startMode = m_workerInspectorProxy->workerStartMode(document); + OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(scriptURL, userAgent, sourceCode, nullptr, startMode, csp->headers(), starterOrigin, m_workerClients.release(), document->addressSpace()); double originTime = document->loader() ? document->loader()->timing().referenceMonotonicTime() : monotonicallyIncreasingTime(); m_loaderProxy = WorkerLoaderProxy::create(this);
diff --git a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h index f7a0b9f..aac6138 100644 --- a/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h +++ b/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
@@ -54,7 +54,7 @@ public: // Implementations of WorkerGlobalScopeProxy. // (Only use these methods in the worker object thread.) - void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) override; + void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode) override; void terminateWorkerGlobalScope() override; void postMessageToWorkerGlobalScope(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) override; bool hasPendingActivity() const override;
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp index 0e01670..7b81cd8 100644 --- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
@@ -34,8 +34,9 @@ #include "platform/HTTPNames.h" #include "platform/network/ContentSecurityPolicyResponseHeaders.h" #include "platform/network/ResourceResponse.h" +#include "platform/weborigin/SecurityOrigin.h" +#include "public/platform/Platform.h" #include "public/platform/WebURLRequest.h" - #include "wtf/OwnPtr.h" #include "wtf/RefPtr.h" @@ -49,6 +50,7 @@ , m_identifier(0) , m_appCacheID(0) , m_requestContext(WebURLRequest::RequestContextWorker) + , m_responseAddressSpace(WebURLRequest::AddressSpacePublic) { } @@ -133,6 +135,13 @@ m_responseEncoding = response.textEncodingName(); m_appCacheID = response.appCacheID(); processContentSecurityPolicy(response); + + if (Platform::current()->isReservedIPAddress(response.remoteIPAddress())) { + m_responseAddressSpace = SecurityOrigin::create(m_responseURL)->isLocalhost() + ? WebURLRequest::AddressSpaceLocal + : WebURLRequest::AddressSpacePrivate; + } + if (m_responseCallback) (*m_responseCallback)(); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h index cae0426..ae1b922 100644 --- a/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h +++ b/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
@@ -80,6 +80,8 @@ ContentSecurityPolicy* contentSecurityPolicy() { return m_contentSecurityPolicy.get(); } PassRefPtrWillBeRawPtr<ContentSecurityPolicy> releaseContentSecurityPolicy() { return m_contentSecurityPolicy.release(); } + WebURLRequest::AddressSpace responseAddressSpace() const { return m_responseAddressSpace; } + // ThreadableLoaderClient void didReceiveResponse(unsigned long /*identifier*/, const ResourceResponse&, PassOwnPtr<WebDataConsumerHandle>) override; void didReceiveData(const char* data, unsigned dataLength) override; @@ -119,6 +121,7 @@ OwnPtr<Vector<char>> m_cachedMetadata; WebURLRequest::RequestContext m_requestContext; RefPtrWillBePersistent<ContentSecurityPolicy> m_contentSecurityPolicy; + WebURLRequest::AddressSpace m_responseAddressSpace; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/third_party/WebKit/Source/core/workers/WorkerThread.cpp index 136f1d8..c96a79b 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThread.cpp
@@ -134,84 +134,6 @@ return threadSafeBind(&WorkerThread::performTask, AllowCrossThreadAccess(this), task, isInstrumented); } -class WorkerThread::DebuggerTaskQueue { - WTF_MAKE_NONCOPYABLE(DebuggerTaskQueue); -public: - using Task = WTF::Closure; - using Result = WorkerThread::TaskQueueResult; - - DebuggerTaskQueue() { } - - // Returns true if the queue is still alive, false if the queue has been - // killed. - bool append(PassOwnPtr<Task> task) - { - MutexLocker lock(m_mutex); - m_queue.append(task); - m_condition.signal(); - return !m_killed; - } - - PassOwnPtr<Task> waitWithTimeout(Result& result, double absoluteTime) - { - MutexLocker lock(m_mutex); - bool timedOut = false; - - while (!m_killed && !timedOut && m_queue.isEmpty()) - timedOut = !m_condition.timedWait(m_mutex, absoluteTime); - - ASSERT(!timedOut || absoluteTime != infiniteTime()); - - if (m_killed) { - result = Terminated; - return nullptr; - } - - if (timedOut) { - result = Timeout; - return nullptr; - } - - ASSERT_WITH_SECURITY_IMPLICATION(!m_queue.isEmpty()); - result = TaskReceived; - - return m_queue.takeFirst().release(); - } - - void kill() - { - MutexLocker lock(m_mutex); - m_killed = true; - m_condition.broadcast(); - } - - static double infiniteTime() { return std::numeric_limits<double>::max(); } - -private: - Mutex m_mutex; - ThreadCondition m_condition; - Deque<OwnPtr<Task>> m_queue; - bool m_killed = false; -}; - -class WorkerThread::RunInspectorCommandsTask : public InspectorTaskRunner::Task { - WTF_MAKE_NONCOPYABLE(RunInspectorCommandsTask); -public: - explicit RunInspectorCommandsTask(WorkerThread* thread) : m_thread(thread) { } - ~RunInspectorCommandsTask() override { } - void run() override - { - // Process all queued debugger commands. WorkerThread is certainly - // alive if this task is being executed. - InspectorInstrumentation::willEnterNestedRunLoop(m_thread->workerGlobalScope()); - while (WorkerThread::TaskReceived == m_thread->runDebuggerTask(WorkerThread::DontWaitForTask)) { } - InspectorInstrumentation::didLeaveNestedRunLoop(m_thread->workerGlobalScope()); - } - -private: - WorkerThread* m_thread; -}; - WorkerThread::WorkerThread(PassRefPtr<WorkerLoaderProxy> workerLoaderProxy, WorkerReportingProxy& workerReportingProxy) : m_started(false) , m_terminated(false) @@ -219,7 +141,7 @@ , m_pausedInDebugger(false) , m_runningDebuggerTask(false) , m_shouldTerminateV8Execution(false) - , m_debuggerTaskQueue(adoptPtr(new DebuggerTaskQueue)) + , m_inspectorTaskRunner(adoptPtr(new InspectorTaskRunner())) , m_workerLoaderProxy(workerLoaderProxy) , m_workerReportingProxy(workerReportingProxy) , m_webScheduler(nullptr) @@ -289,7 +211,6 @@ m_isolate = initializeIsolate(); // Optimize for memory usage instead of latency for the worker isolate. m_isolate->IsolateInBackgroundNotification(); - m_inspectorTaskRunner = adoptPtr(new InspectorTaskRunner(m_isolate)); m_workerGlobalScope = createWorkerGlobalScope(startupData); m_workerGlobalScope->scriptLoaded(sourceCode.length(), cachedMetaData.get() ? cachedMetaData->size() : 0); @@ -385,11 +306,6 @@ return m_workerGlobalScope.get(); } -InspectorTaskRunner* WorkerThread::inspectorTaskRunner() -{ - return m_inspectorTaskRunner.get(); -} - bool WorkerThread::terminated() { MutexLocker lock(m_threadStateMutex); @@ -434,7 +350,7 @@ terminateV8Execution(); InspectorInstrumentation::didKillAllExecutionContextTasks(m_workerGlobalScope.get()); - m_debuggerTaskQueue->kill(); + m_inspectorTaskRunner->kill(); backingThread().postTask(BLINK_FROM_HERE, threadSafeBind(&WorkerThread::shutdown, AllowCrossThreadAccess(this))); } @@ -524,7 +440,9 @@ void WorkerThread::runDebuggerTaskDontWait() { - runDebuggerTask(WorkerThread::DontWaitForTask); + OwnPtr<Closure> task = m_inspectorTaskRunner->takeNextTask(InspectorTaskRunner::DontWaitForTask); + if (task) + (*task)(); } void WorkerThread::appendDebuggerTask(PassOwnPtr<Closure> task) @@ -534,55 +452,50 @@ if (m_shutdown) return; } - m_debuggerTaskQueue->append(task); + m_inspectorTaskRunner->appendTask(threadSafeBind(&WorkerThread::runDebuggerTask, AllowCrossThreadAccess(this), task)); + { + MutexLocker lock(m_threadStateMutex); + if (m_isolate) + m_inspectorTaskRunner->interruptAndRunAllTasksDontWait(m_isolate); + } backingThread().postTask(BLINK_FROM_HERE, threadSafeBind(&WorkerThread::runDebuggerTaskDontWait, AllowCrossThreadAccess(this))); - if (m_inspectorTaskRunner) - m_inspectorTaskRunner->interruptAndRun(adoptPtr(new RunInspectorCommandsTask(this))); } -WorkerThread::TaskQueueResult WorkerThread::runDebuggerTask(WaitMode waitMode) +void WorkerThread::runDebuggerTask(PassOwnPtr<Closure> task) { ASSERT(isCurrentThread()); - TaskQueueResult result; - double absoluteTime = DebuggerTaskQueue::infiniteTime(); - OwnPtr<Closure> task; + InspectorTaskRunner::IgnoreInterruptsScope scope(m_inspectorTaskRunner.get()); { - if (waitMode == DontWaitForTask) - absoluteTime = 0.0; - SafePointScope safePointScope(BlinkGC::HeapPointersOnStack); - task = m_debuggerTaskQueue->waitWithTimeout(result, absoluteTime); + MutexLocker lock(m_threadStateMutex); + m_runningDebuggerTask = true; } - - if (result == TaskReceived) { - { - MutexLocker lock(m_threadStateMutex); - m_runningDebuggerTask = true; - } - InspectorInstrumentation::willProcessTask(workerGlobalScope()); - (*task)(); - InspectorInstrumentation::didProcessTask(workerGlobalScope()); - { - MutexLocker lock(m_threadStateMutex); - m_runningDebuggerTask = false; - if (m_shouldTerminateV8Execution) { - m_shouldTerminateV8Execution = false; - terminateV8Execution(); - } + InspectorInstrumentation::willProcessTask(workerGlobalScope()); + (*task)(); + InspectorInstrumentation::didProcessTask(workerGlobalScope()); + { + MutexLocker lock(m_threadStateMutex); + m_runningDebuggerTask = false; + if (m_shouldTerminateV8Execution) { + m_shouldTerminateV8Execution = false; + terminateV8Execution(); } } - - return result; } void WorkerThread::startRunningDebuggerTasksOnPause() { m_pausedInDebugger = true; - WorkerThread::TaskQueueResult result; InspectorInstrumentation::willEnterNestedRunLoop(m_workerGlobalScope.get()); + OwnPtr<Closure> task; do { - result = runDebuggerTask(WorkerThread::WaitForTask); + { + SafePointScope safePointScope(BlinkGC::HeapPointersOnStack); + task = m_inspectorTaskRunner->takeNextTask(InspectorTaskRunner::WaitForTask); + } + if (task) + (*task)(); // Keep waiting until execution is resumed. - } while (result == WorkerThread::TaskReceived && m_pausedInDebugger); + } while (task && m_pausedInDebugger); InspectorInstrumentation::didLeaveNestedRunLoop(m_workerGlobalScope.get()); }
diff --git a/third_party/WebKit/Source/core/workers/WorkerThread.h b/third_party/WebKit/Source/core/workers/WorkerThread.h index 3edd3b7..340922c 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThread.h +++ b/third_party/WebKit/Source/core/workers/WorkerThread.h
@@ -106,9 +106,6 @@ // Can be called only on the worker thread, WorkerGlobalScope is not thread safe. WorkerGlobalScope* workerGlobalScope(); - // Can be called on any thread. - InspectorTaskRunner* inspectorTaskRunner(); - // Returns true once one of the terminate* methods is called. bool terminated(); @@ -137,8 +134,6 @@ virtual void terminateV8Execution(); private: - class DebuggerTaskQueue; - class RunInspectorCommandsTask; friend class WorkerMicrotaskRunner; PassOwnPtr<Closure> createWorkerThreadTask(PassOwnPtr<ExecutionContextTask>, bool isInstrumented); @@ -152,14 +147,7 @@ void performTask(PassOwnPtr<ExecutionContextTask>, bool isInstrumented); void performShutdownTask(); void postDelayedTask(const WebTraceLocation&, PassOwnPtr<ExecutionContextTask>, long long delayMs); - - enum WaitMode { WaitForTask, DontWaitForTask }; - enum TaskQueueResult { - Terminated, // Queue was destroyed while waiting for a task. - Timeout, // Timeout was specified and it expired. - TaskReceived, // A task was successfully received and returned. - }; - TaskQueueResult runDebuggerTask(WaitMode); + void runDebuggerTask(PassOwnPtr<Closure>); void runDebuggerTaskDontWait(); bool m_started; @@ -168,7 +156,6 @@ bool m_pausedInDebugger; bool m_runningDebuggerTask; bool m_shouldTerminateV8Execution; - OwnPtr<DebuggerTaskQueue> m_debuggerTaskQueue; OwnPtr<InspectorTaskRunner> m_inspectorTaskRunner; OwnPtr<WebThread::TaskObserver> m_microtaskRunner;
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp index 809ab9d..552e90e 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
@@ -34,7 +34,7 @@ namespace blink { -WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, PassOwnPtrWillBeRawPtr<WorkerClients> workerClients, V8CacheOptions v8CacheOptions) +WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, PassOwnPtrWillBeRawPtr<WorkerClients> workerClients, WebURLRequest::AddressSpace addressSpace, V8CacheOptions v8CacheOptions) : m_scriptURL(scriptURL.copy()) , m_userAgent(userAgent.isolatedCopy()) , m_sourceCode(sourceCode.isolatedCopy()) @@ -42,6 +42,7 @@ , m_startMode(startMode) , m_starterOriginPrivilegeData(starterOrigin ? starterOrigin->createPrivilegeData() : nullptr) , m_workerClients(workerClients) + , m_addressSpace(addressSpace) , m_v8CacheOptions(v8CacheOptions) { m_contentSecurityPolicyHeaders = adoptPtr(new Vector<CSPHeaderAndType>());
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h index 728ae120..56a3ba0 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h +++ b/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
@@ -38,6 +38,7 @@ #include "core/workers/WorkerThread.h" #include "platform/network/ContentSecurityPolicyParsers.h" #include "platform/weborigin/KURL.h" +#include "public/platform/WebURLRequest.h" #include "wtf/Forward.h" #include "wtf/Noncopyable.h" @@ -49,9 +50,9 @@ WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData); USING_FAST_MALLOC(WorkerThreadStartupData); public: - static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, PassOwnPtrWillBeRawPtr<WorkerClients> workerClients, V8CacheOptions v8CacheOptions = V8CacheOptionsDefault) + static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode startMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin* starterOrigin, PassOwnPtrWillBeRawPtr<WorkerClients> workerClients, WebURLRequest::AddressSpace addressSpace, V8CacheOptions v8CacheOptions = V8CacheOptionsDefault) { - return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, cachedMetaData, startMode, contentSecurityPolicyHeaders, starterOrigin, workerClients, v8CacheOptions)); + return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, cachedMetaData, startMode, contentSecurityPolicyHeaders, starterOrigin, workerClients, addressSpace, v8CacheOptions)); } ~WorkerThreadStartupData(); @@ -63,6 +64,7 @@ WorkerThreadStartMode m_startMode; OwnPtr<Vector<CSPHeaderAndType>> m_contentSecurityPolicyHeaders; + // The SecurityOrigin of the Document creating a Worker may have // been configured with extra policy privileges when it was created // (e.g., enforce path-based file:// origins.) @@ -84,10 +86,12 @@ // supplies no extra 'clients', m_workerClients can be left as empty/null. OwnPtrWillBeCrossThreadPersistent<WorkerClients> m_workerClients; + WebURLRequest::AddressSpace m_addressSpace; + V8CacheOptions m_v8CacheOptions; private: - WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin*, PassOwnPtrWillBeRawPtr<WorkerClients>, V8CacheOptions); + WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, PassOwnPtr<Vector<char>> cachedMetaData, WorkerThreadStartMode, const PassOwnPtr<Vector<CSPHeaderAndType>> contentSecurityPolicyHeaders, const SecurityOrigin*, PassOwnPtrWillBeRawPtr<WorkerClients>, WebURLRequest::AddressSpace, V8CacheOptions); }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp b/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp index 6096f0d..df1bfdb6 100644 --- a/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp +++ b/third_party/WebKit/Source/core/workers/WorkerThreadTest.cpp
@@ -185,6 +185,7 @@ headers.release(), m_securityOrigin.get(), clients.release(), + WebURLRequest::AddressSpaceLocal, V8CacheOptionsDefault)); }
diff --git a/third_party/WebKit/Source/devtools/devtools.gypi b/third_party/WebKit/Source/devtools/devtools.gypi index 8d5cb5e..ed150bcd 100644 --- a/third_party/WebKit/Source/devtools/devtools.gypi +++ b/third_party/WebKit/Source/devtools/devtools.gypi
@@ -688,6 +688,7 @@ 'front_end/timeline/Layers3DView.js', 'front_end/timeline/MemoryCountersGraph.js', 'front_end/timeline/PaintProfilerView.js', + 'front_end/timeline/TimelineController.js', 'front_end/timeline/TimelineEventOverview.js', 'front_end/timeline/TimelineFlameChart.js', 'front_end/timeline/TimelineFrameModel.js',
diff --git a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js index ba02da29..d63af21 100644 --- a/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js +++ b/third_party/WebKit/Source/devtools/front_end/accessibility/AccessibilityNodeView.js
@@ -58,7 +58,7 @@ { ignoredReasons.appendChild(new WebInspector.AXNodeIgnoredReasonTreeElement(property, axNode, target)); } - var ignoredReasonsArray = /** @type {!Array.<!Object>} */(axNode.ignoredReasons); + var ignoredReasonsArray = /** @type {!Array<!AccessibilityAgent.AXProperty>} */(axNode.ignoredReasons); for (var reason of ignoredReasonsArray) addIgnoredReason(reason); if (!ignoredReasons.firstChild())
diff --git a/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js b/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js index ca45d51..a638205 100644 --- a/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js +++ b/third_party/WebKit/Source/devtools/front_end/animation/AnimationModel.js
@@ -883,7 +883,7 @@ this._model.addEventListener(WebInspector.AnimationModel.Events.ModelReset, this._stopScreencast, this); } -/** @typedef {{ time: number, screenshots: !Array.<string>}} */ +/** @typedef {{ endTime: number, screenshots: !Array.<string>}} */ WebInspector.AnimationModel.ScreenshotCapture.Request; WebInspector.AnimationModel.ScreenshotCapture.prototype = {
diff --git a/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js b/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js index 6824758..307b5c53 100644 --- a/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js +++ b/third_party/WebKit/Source/devtools/front_end/audits/AuditRules.js
@@ -44,7 +44,7 @@ /** * @param {!Array.<!WebInspector.NetworkRequest>} requests - * @param {?Array.<!WebInspector.resourceTypes>} types + * @param {?Array.<!WebInspector.ResourceType>} types * @param {boolean} needFullResources * @return {!Object.<string, !Array.<!WebInspector.NetworkRequest|string>>} */
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/TempFile.js b/third_party/WebKit/Source/devtools/front_end/bindings/TempFile.js index e40ccf4..6ce9762 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/TempFile.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/TempFile.js
@@ -233,7 +233,7 @@ */ WebInspector.DeferredTempFile = function(dirPath, name) { - /** @type {!Array.<!{strings: !Array.<string>, callback: function(number)}>} */ + /** @type {!Array.<!{strings: !Array.<string>, callback: ?function(number)}>} */ this._chunks = []; this._tempFile = null; this._isWriting = false; @@ -254,7 +254,7 @@ { if (this._finishCallback) throw new Error("No writes are allowed after close."); - this._chunks.push({strings: strings, callback: callback}); + this._chunks.push({strings: strings, callback: callback || null}); if (this._tempFile && !this._isWriting) this._writeNextChunk(); },
diff --git a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js index bb30b7b..e1e23a3 100644 --- a/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js +++ b/third_party/WebKit/Source/devtools/front_end/console/ConsoleViewMessage.js
@@ -478,7 +478,7 @@ { var property = propertyPath.peekLast(); if (property.type === "accessor") - return this._formatAsAccessorProperty(object, propertyPath.select("name"), false); + return this._formatAsAccessorProperty(object, propertyPath.map(property => property.name), false); return this._previewFormatter.renderPropertyPreview(property.type, /** @type {string} */ (property.subtype), property.value); }, @@ -647,7 +647,7 @@ return; } - var elements = []; + var elements = {}; for (var i = 0; i < properties.length; ++i) { var property = properties[i]; var name = property.name;
diff --git a/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js b/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js index 7f09b2cc..c7d2e35 100644 --- a/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js +++ b/third_party/WebKit/Source/devtools/front_end/devices/DevicesView.js
@@ -450,7 +450,7 @@ this._deviceSerial.textContent = "#" + device.adbSerial; this._deviceOffline.classList.toggle("hidden", device.adbConnected); - this._noBrowsers.classList.toggle("hidden", !device.adbConnected || device.browsers.length); + this._noBrowsers.classList.toggle("hidden", !device.adbConnected || !!device.browsers.length); this._browsers.classList.toggle("hidden", !device.adbConnected || !device.browsers.length); var browserIds = new Set();
diff --git a/third_party/WebKit/Source/devtools/front_end/devtools.js b/third_party/WebKit/Source/devtools/front_end/devtools.js index 9cb6bf2..9da83256 100644 --- a/third_party/WebKit/Source/devtools/front_end/devtools.js +++ b/third_party/WebKit/Source/devtools/front_end/devtools.js
@@ -400,13 +400,7 @@ */ setInspectedPageBounds: function(bounds) { - var converted = { - x: Math.round(DevToolsHost.convertLengthForEmbedder(bounds.x)), - y: Math.round(DevToolsHost.convertLengthForEmbedder(bounds.y)), - width: Math.round(DevToolsHost.convertLengthForEmbedder(bounds.width)), - height: Math.round(DevToolsHost.convertLengthForEmbedder(bounds.height)) - }; - DevToolsAPI.sendMessageToEmbedder("setInspectedPageBounds", [converted], null); + DevToolsAPI.sendMessageToEmbedder("setInspectedPageBounds", [bounds], null); }, /**
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementsBreadcrumbs.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementsBreadcrumbs.js index 0b1c4e4..18f351b2 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementsBreadcrumbs.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementsBreadcrumbs.js
@@ -206,7 +206,7 @@ // Reset crumb styles. for (var i = 0; i < crumbs.childNodes.length; ++i) { - var crumb = crumbs.childNodes[i]; + var crumb = crumbs.children[i]; // Find the selected crumb and index. if (!selectedCrumb && crumb.classList.contains("selected")) { selectedCrumb = crumb; @@ -284,7 +284,7 @@ function shrinkCrumbAtIndex(index) { - var shrinkCrumb = crumbs.childNodes[index]; + var shrinkCrumb = crumbs.children[index]; if (shrinkCrumb && shrinkCrumb !== significantCrumb) shrinkingFunction(shrinkCrumb); if (crumbsAreSmallerThanContainer())
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js index 967a836..0c1c928 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/ElementsTreeOutline.js
@@ -1321,11 +1321,13 @@ { var visibleChildren = WebInspector.ElementsTreeElement.visibleShadowRoots(node); - if (node.importedDocument()) - visibleChildren.push(node.importedDocument()); + var importedDocument = node.importedDocument(); + if (importedDocument) + visibleChildren.push(importedDocument); - if (node.templateContent()) - visibleChildren.push(node.templateContent()); + var templateContent = node.templateContent(); + if (templateContent) + visibleChildren.push(templateContent); var beforePseudoElement = node.beforePseudoElement(); if (beforePseudoElement)
diff --git a/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js b/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js index e8a6180..56535fb 100644 --- a/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js +++ b/third_party/WebKit/Source/devtools/front_end/elements/StylesSidebarPane.js
@@ -1156,7 +1156,7 @@ hasMatchingChild |= child._updateFilter(); var regex = this._parentPane.filterRegex(); - var hideRule = !hasMatchingChild && regex && !regex.test(this.element.textContent); + var hideRule = !hasMatchingChild && !!regex && !regex.test(this.element.textContent); this.element.classList.toggle("hidden", hideRule); if (!hideRule && this._style.parentRule) this._markSelectorHighlights();
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js index 8f53f3ae..79c6098 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DeviceModeToolbar.js
@@ -401,11 +401,12 @@ */ _deviceListChanged: function() { - if (!this._model.device()) + var device = this._model.device(); + if (!device) return; var devices = this._allDevices(); - if (devices.indexOf(this._model.device()) === -1) { + if (devices.indexOf(device) === -1) { if (devices.length) this._emulateDevice(devices[0]); else
diff --git a/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js b/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js index 2df06bf..500fc75e 100644 --- a/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js +++ b/third_party/WebKit/Source/devtools/front_end/emulation/DevicesSettingsTab.js
@@ -152,8 +152,8 @@ device.deviceScaleFactor = editor.control("scale").value ? parseFloat(editor.control("scale").value) : 0; device.userAgent = editor.control("user-agent").value; device.modes = []; - device.modes.push({title: "", orientation: WebInspector.EmulatedDevice.Vertical, insets: new Insets(0, 0, 0, 0), images: null}); - device.modes.push({title: "", orientation: WebInspector.EmulatedDevice.Horizontal, insets: new Insets(0, 0, 0, 0), images: null}); + device.modes.push({title: "", orientation: WebInspector.EmulatedDevice.Vertical, insets: new Insets(0, 0, 0, 0), image: null}); + device.modes.push({title: "", orientation: WebInspector.EmulatedDevice.Horizontal, insets: new Insets(0, 0, 0, 0), image: null}); device.capabilities = []; var uaType = editor.control("ua-type").value; if (uaType === WebInspector.DeviceModeModel.UA.Mobile || uaType === WebInspector.DeviceModeModel.UA.MobileNoTouch)
diff --git a/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js b/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js index 9eb5179..850fb24 100644 --- a/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js +++ b/third_party/WebKit/Source/devtools/front_end/extensions/ExtensionAPI.js
@@ -953,7 +953,7 @@ { return tabId; } - chrome = window.chrome || {}; + var chrome = window.chrome || {}; // Override chrome.devtools as a workaround for a error-throwing getter being exposed // in extension pages loaded into a non-extension process (only happens for remote client // extensions)
diff --git a/third_party/WebKit/Source/devtools/front_end/externs.js b/third_party/WebKit/Source/devtools/front_end/externs.js index 20df2fc..1cb9219 100644 --- a/third_party/WebKit/Source/devtools/front_end/externs.js +++ b/third_party/WebKit/Source/devtools/front_end/externs.js
@@ -213,12 +213,6 @@ DevToolsHost.zoomFactor = function() { } /** - * @param {number} length - * @return {number} - */ -DevToolsHost.convertLengthForEmbedder = function(length) { } - -/** * @param {string} origin * @param {string} script */ @@ -700,7 +694,7 @@ this.params; /** @type {(string|undefined)} */ this.name; - /** @type {(!Array.<!ESTree.Node>|undefined)} */ + /** @type {(?ESTree.Node|undefined)} */ this.id; }
diff --git a/third_party/WebKit/Source/devtools/front_end/main/Tests.js b/third_party/WebKit/Source/devtools/front_end/main/Tests.js index 4e3588f..d7cebcf0 100644 --- a/third_party/WebKit/Source/devtools/front_end/main/Tests.js +++ b/third_party/WebKit/Source/devtools/front_end/main/Tests.js
@@ -652,29 +652,40 @@ this.takeControl(); }; +TestSuite.prototype._overrideMethod = function(receiver, methodName, override) +{ + var original = receiver[methodName]; + if (typeof original !== "function") { + this.fail(`TestSuite._overrideMethod: $[methodName] is not a function`); + return; + } + receiver[methodName] = function() + { + try { + var value = original.apply(receiver, arguments); + } finally { + receiver[methodName] = original; + } + override.apply(original, arguments); + return value; + } +} + TestSuite.prototype.startTimeline = function(callback) { + var test = this; this.showPanel("timeline").then(function() { - WebInspector.panels.timeline._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, onRecordingStarted); - WebInspector.panels.timeline._toggleRecording(); + var timeline = WebInspector.panels.timeline; + test._overrideMethod(timeline, "recordingStarted", callback); + timeline._toggleRecording(); }); - - function onRecordingStarted() - { - WebInspector.panels.timeline._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, onRecordingStarted); - callback(); - } } TestSuite.prototype.stopTimeline = function(callback) { - WebInspector.panels.timeline._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, onRecordingStopped); - WebInspector.panels.timeline._toggleRecording(); - function onRecordingStopped() - { - WebInspector.panels.timeline._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStopped, onRecordingStopped); - callback(); - } + var timeline = WebInspector.panels.timeline; + this._overrideMethod(timeline, "loadingComplete", callback); + timeline._toggleRecording(); } TestSuite.prototype.invokePageFunctionAsync = function(functionName, opt_args, callback_is_always_last)
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js index a8b20ac..71083b8f 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/CPUProfileFlameChart.js
@@ -214,7 +214,7 @@ /** * @override * @param {number} entryIndex - * @return {?Array<!{title: string, value: (string,!Element)}>} + * @return {?Array<!{title: string, value: (string|!Element)}>} */ prepareHighlightedEntryInfo: function(entryIndex) {
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js index f52f23b..3cb88eb 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/HeapSnapshotProxy.js
@@ -38,8 +38,10 @@ this._eventHandler = eventHandler; this._nextObjectId = 1; this._nextCallId = 1; - this._callbacks = []; - this._previousCallbacks = []; + /** @type {!Map<number, function(*)>} */ + this._callbacks = new Map(); + /** @type {!Set<number>} */ + this._previousCallbacks = new Set(); this._worker = new WorkerRuntime.Worker("heap_snapshot_worker"); this._worker.onmessage = this._messageReceived.bind(this); } @@ -73,7 +75,7 @@ evaluateForTest: function(script, callback) { var callId = this._nextCallId++; - this._callbacks[callId] = callback; + this._callbacks.set(callId, callback); this._postMessage({callId: callId, disposition: "evaluateForTest", source: script}); }, @@ -100,7 +102,7 @@ } if (callback) { - this._callbacks[callId] = wrapCallback.bind(this); + this._callbacks.set(callId, wrapCallback.bind(this)); this._postMessage({callId: callId, disposition: "factory", objectId: objectId, methodName: methodName, methodArguments: methodArguments, newObjectId: newObjectId}); return null; } else { @@ -119,7 +121,7 @@ var callId = this._nextCallId++; var methodArguments = Array.prototype.slice.call(arguments, 3); if (callback) - this._callbacks[callId] = callback; + this._callbacks.set(callId, callback); this._postMessage({callId: callId, disposition: "method", objectId: objectId, methodName: methodName, methodArguments: methodArguments}); }, @@ -133,17 +135,13 @@ _checkLongRunningCalls: function() { - for (var callId in this._previousCallbacks) - if (!(callId in this._callbacks)) - delete this._previousCallbacks[callId]; - var hasLongRunningCalls = false; - for (callId in this._previousCallbacks) { - hasLongRunningCalls = true; - break; - } + for (var callId of this._previousCallbacks) + if (!this._callbacks.has(callId)) + this._previousCallbacks.delete(callId); + var hasLongRunningCalls = !!this._previousCallbacks.size; this.dispatchEventToListeners("wait", hasLongRunningCalls); - for (callId in this._callbacks) - this._previousCallbacks[callId] = true; + for (var callId of this._callbacks.keysArray()) + this._previousCallbacks.add(callId); }, /** @@ -161,13 +159,13 @@ if (data.errorMethodName) WebInspector.console.error(WebInspector.UIString("An error occurred when a call to method '%s' was requested", data.errorMethodName)); WebInspector.console.error(data["errorCallStack"]); - delete this._callbacks[data.callId]; + this._callbacks.delete(data.callId); return; } - if (!this._callbacks[data.callId]) + if (!this._callbacks.has(data.callId)) return; - var callback = this._callbacks[data.callId]; - delete this._callbacks[data.callId]; + var callback = this._callbacks.get(data.callId); + this._callbacks.delete(data.callId); callback(data.result); },
diff --git a/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js b/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js index e2d14033..e8ecd19 100644 --- a/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js +++ b/third_party/WebKit/Source/devtools/front_end/profiler/ProfilesPanel.js
@@ -163,13 +163,11 @@ }, /** - * @nosideeffects * @param {number} uid * @return {?WebInspector.ProfileHeader} */ getProfile: function(uid) { - for (var i = 0; i < this._profiles.length; ++i) { if (this._profiles[i].uid === uid) return this._profiles[i];
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseModel.js b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseModel.js index 61364cb3..89aa63b 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/DatabaseModel.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/DatabaseModel.js
@@ -165,8 +165,8 @@ databases: function() { var result = []; - for (var databaseId in this._databases) - result.push(this._databases[databaseId]); + for (var database of this._databases) + result.push(database); return result; }, @@ -219,4 +219,4 @@ target[WebInspector.DatabaseModel._symbol] = new WebInspector.DatabaseModel(target); return target[WebInspector.DatabaseModel._symbol]; -} \ No newline at end of file +}
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/PaintProfiler.js b/third_party/WebKit/Source/devtools/front_end/sdk/PaintProfiler.js index c27bd3e4..f8756bf7 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/PaintProfiler.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/PaintProfiler.js
@@ -70,53 +70,6 @@ WebInspector.PaintProfilerSnapshot.loadFromFragments(target, [fragment], callback); } -/** - * @param {!Array.<!WebInspector.RawPaintProfilerLogItem>} log - * @return {!Array.<!WebInspector.PaintProfilerLogItem>} - */ -WebInspector.PaintProfilerSnapshot._processAnnotations = function(log) -{ - var result = []; - /** @type {!Array.<!Object.<string, string>>} */ - var commentGroupStack = []; - - for (var i = 0; i < log.length; ++i) { - var method = log[i].method; - switch (method) { - case "beginCommentGroup": - commentGroupStack.push({}); - break; - case "addComment": - var group = commentGroupStack.peekLast(); - if (!group) { - console.assert(false, "Stray comment without a group"); - break; - } - var key = String(log[i].params["key"]); - var value = String(log[i].params["value"]); - if (!key || typeof value === "undefined") { - console.assert(false, "Missing key or value in addComment() params"); - break; - } - if (key in group) { - console.assert(false, "Duplicate key in comment group"); - break; - } - group[key] = value; - break; - case "endCommentGroup": - if (!commentGroupStack.length) - console.assert(false, "Unbalanced commentGroupEnd call"); - else - commentGroupStack.pop(); - break; - default: - result.push(new WebInspector.PaintProfilerLogItem(log[i], i, commentGroupStack.peekLast())); - } - } - return result; -} - WebInspector.PaintProfilerSnapshot.prototype = { dispose: function() { @@ -169,7 +122,8 @@ callback(); return; } - callback(WebInspector.PaintProfilerSnapshot._processAnnotations(log)); + var logItems = log.map((entry, index) => new WebInspector.PaintProfilerLogItem(entry, index)); + callback(logItems); } this._target.layerTreeAgent().snapshotCommandLog(this._id, callbackWrapper); @@ -177,7 +131,7 @@ }; /** - * @typedef {!{method: string, params: ?Array.<!Object.<string, *>>}} + * @typedef {!{method: string, params: ?Object<string, *>}} */ WebInspector.RawPaintProfilerLogItem; @@ -185,25 +139,10 @@ * @constructor * @param {!WebInspector.RawPaintProfilerLogItem} rawEntry * @param {number} commandIndex - * @param {!Object.<string, string>=} annotations */ -WebInspector.PaintProfilerLogItem = function(rawEntry, commandIndex, annotations) +WebInspector.PaintProfilerLogItem = function(rawEntry, commandIndex) { this.method = rawEntry.method; this.params = rawEntry.params; - this.annotations = annotations; this.commandIndex = commandIndex; } - -WebInspector.PaintProfilerLogItem.prototype = { - /** - * @return {number} - */ - nodeId: function() - { - if (!this.annotations) - return 0; - var inspectorId = this.annotations["INSPECTOR_ID"]; - return Number(inspectorId); - } -}
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js b/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js index 98ea46c3..bd9bf58 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/TracingModel.js
@@ -10,10 +10,10 @@ */ WebInspector.TracingModel = function(backingStorage) { - this.reset(); - // Set backing storage after reset so that we do not perform - // an extra reset of backing storage -- this is not free. this._backingStorage = backingStorage; + // Avoid extra reset of the storage as it's expensive. + this._firstWritePending = true; + this.reset(); } /** @@ -175,9 +175,9 @@ tracingComplete: function() { this._processPendingAsyncEvents(); - if (!this._firstWritePending) - this._backingStorage.appendString("]"); + this._backingStorage.appendString(this._firstWritePending ? "[]" : "]"); this._backingStorage.finishWriting(); + this._firstWritePending = false; for (var process of Object.values(this._processById)) { for (var thread of Object.values(process._threads)) thread.tracingComplete(); @@ -192,8 +192,9 @@ this._minimumRecordTime = 0; this._maximumRecordTime = 0; this._devToolsMetadataEvents = []; - if (this._backingStorage) + if (!this._firstWritePending) this._backingStorage.reset(); + this._firstWritePending = true; /** @type {!Array<!WebInspector.TracingModel.Event>} */ this._asyncEvents = [];
diff --git a/third_party/WebKit/Source/devtools/front_end/sdk/WorkerManager.js b/third_party/WebKit/Source/devtools/front_end/sdk/WorkerManager.js index cf198b9..9ebf307 100644 --- a/third_party/WebKit/Source/devtools/front_end/sdk/WorkerManager.js +++ b/third_party/WebKit/Source/devtools/front_end/sdk/WorkerManager.js
@@ -86,48 +86,30 @@ _onSuspendStateChanged: function() { var suspended = WebInspector.targetManager.allTargetsSuspended(); - this.target().workerAgent().setAutoconnectToWorkers(!suspended); + this.target().workerAgent().setWaitForDebuggerOnStart(!suspended); }, /** * @param {string} workerId * @param {string} url - * @param {boolean} inspectorConnected + * @param {boolean} waitingForDebugger */ - _workerCreated: function(workerId, url, inspectorConnected) + _workerCreated: function(workerId, url, waitingForDebugger) { - var connection = new WebInspector.WorkerConnection(this, workerId, inspectorConnected, onConnectionReady.bind(this)); + var connection = new WebInspector.WorkerConnection(this, workerId); this._connections.set(workerId, connection); - /** - * @param {!InspectorBackendClass.Connection} connection - * @this {WebInspector.WorkerManager} - */ - function onConnectionReady(connection) - { - var parsedURL = url.asParsedURL(); - var workerName = parsedURL ? parsedURL.lastPathComponentWithFragment() : "#" + (++this._lastAnonymousTargetId); - var target = WebInspector.targetManager.createTarget(workerName, WebInspector.Target.Type.DedicatedWorker, connection, this.target()); - this._targetsByWorkerId.set(workerId, target); + var parsedURL = url.asParsedURL(); + var workerName = parsedURL ? parsedURL.lastPathComponentWithFragment() : "#" + (++this._lastAnonymousTargetId); + var target = WebInspector.targetManager.createTarget(workerName, WebInspector.Target.Type.DedicatedWorker, connection, this.target()); + this._targetsByWorkerId.set(workerId, target); - if (inspectorConnected) - target.runtimeAgent().isRunRequired(pauseInDebuggerAndRunIfRequired.bind(null, target)); - } - - /** - * @param {!WebInspector.Target} target - * @param {?Protocol.Error} error - * @param {boolean} required - */ - function pauseInDebuggerAndRunIfRequired(target, error, required) - { - // Only pause new worker if debugging SW - we are going through the - // pause on start checkbox. - var mainIsServiceWorker = WebInspector.targetManager.mainTarget().isServiceWorker(); - if (mainIsServiceWorker && required) - target.debuggerAgent().pause(); - target.runtimeAgent().run(); - } + // Only pause new worker if debugging SW - we are going through the + // pause on start checkbox. + var mainIsServiceWorker = WebInspector.targetManager.mainTarget().isServiceWorker(); + if (mainIsServiceWorker && waitingForDebugger) + target.debuggerAgent().pause(); + target.runtimeAgent().run(); }, /** @@ -187,11 +169,11 @@ * @override * @param {string} workerId * @param {string} url - * @param {boolean} inspectorConnected + * @param {boolean} waitingForDebugger */ - workerCreated: function(workerId, url, inspectorConnected) + workerCreated: function(workerId, url, waitingForDebugger) { - this._workerManager._workerCreated(workerId, url, inspectorConnected); + this._workerManager._workerCreated(workerId, url, waitingForDebugger); }, /** @@ -219,22 +201,14 @@ * @extends {InspectorBackendClass.Connection} * @param {!WebInspector.WorkerManager} workerManager * @param {string} workerId - * @param {boolean} inspectorConnected - * @param {function(!InspectorBackendClass.Connection)} onConnectionReady */ -WebInspector.WorkerConnection = function(workerManager, workerId, inspectorConnected, onConnectionReady) +WebInspector.WorkerConnection = function(workerManager, workerId) { InspectorBackendClass.Connection.call(this); //FIXME: remove resourceTreeModel and others from worker targets this.suppressErrorsForDomains(["Worker", "Page", "CSS", "DOM", "DOMStorage", "Database", "Network", "IndexedDB"]); this._agent = workerManager.target().workerAgent(); this._workerId = workerId; - - - if (!inspectorConnected) - this._agent.connectToWorker(workerId, onConnectionReady.bind(null, this)); - else - onConnectionReady.call(null, this); } WebInspector.WorkerConnection.prototype = {
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/FilePathScoreFunction.js b/third_party/WebKit/Source/devtools/front_end/sources/FilePathScoreFunction.js index 8d026a5..0d33a56 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/FilePathScoreFunction.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/FilePathScoreFunction.js
@@ -45,7 +45,7 @@ WebInspector.FilePathScoreFunction.prototype = { /** * @param {string} data - * @param {?Array.<!Number>} matchIndexes + * @param {?Array<number>} matchIndexes * @return {number} */ score: function(data, matchIndexes) @@ -98,7 +98,7 @@ * @param {!Int32Array} sequence * @param {number} n * @param {number} m - * @param {!Array.<!Number>} out + * @param {!Array<number>} out */ _restoreMatchIndexes: function(sequence, n, m, out) {
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js b/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js index 9f79ac2..ccbe65f7 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourceMapNamesResolver.js
@@ -82,7 +82,7 @@ identifiers.pushAll(node.params); if (node.type === "VariableDeclarator") - identifiers.push(node.id); + identifiers.push(/** @type {!ESTree.Node} */(node.id)); } /** @@ -378,4 +378,4 @@ }, __proto__: WebInspector.RemoteObject.prototype -} \ No newline at end of file +}
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/LayerTreeModel.js b/third_party/WebKit/Source/devtools/front_end/timeline/LayerTreeModel.js index a22642d..76e297d 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/LayerTreeModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/LayerTreeModel.js
@@ -264,8 +264,8 @@ function populateBackendNodeMap(nodesMap) { if (nodesMap) { - for (var entry of nodesMap) - this._backendNodeIdToNode.set(entry[0], entry[1]); + for (var nodeId of nodesMap.keysArray()) + this._backendNodeIdToNode.set(nodeId, nodesMap.get(nodeId) || null); } callback(); } @@ -382,7 +382,7 @@ _extractNodeIdsToResolve: function(nodeIdsToResolve, seenNodeIds, payload) { var backendNodeId = payload.owner_node; - if (backendNodeId && !this._backendNodeIdToNode[backendNodeId]) + if (backendNodeId && !this._backendNodeIdToNode.has(backendNodeId)) nodeIdsToResolve.add(backendNodeId); for (var i = 0; payload.children && i < payload.children.length; ++i) this._extractNodeIdsToResolve(nodeIdsToResolve, seenNodeIds, payload.children[i]);
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/PaintProfilerView.js b/third_party/WebKit/Source/devtools/front_end/timeline/PaintProfilerView.js index a9a592b..991fd7d0 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/PaintProfilerView.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/PaintProfilerView.js
@@ -263,10 +263,6 @@ this._treeOutline = new TreeOutlineInShadow(); this.element.appendChild(this._treeOutline.element); - this._treeOutline.element.addEventListener("mousemove", this._onMouseMove.bind(this), false); - this._treeOutline.element.addEventListener("mouseout", this._onMouseMove.bind(this), false); - this._treeOutline.element.addEventListener("contextmenu", this._onContextMenu.bind(this), true); - this._reset(); } @@ -312,40 +308,6 @@ this._log = []; }, - /** - * @param {?Event} event - */ - _onMouseMove: function(event) - { - var node = this._treeOutline.treeElementFromEvent(event); - if (node === this._lastHoveredNode || !(node instanceof WebInspector.LogTreeElement)) - return; - if (this._lastHoveredNode) - this._lastHoveredNode.setHovered(false); - this._lastHoveredNode = node; - if (this._lastHoveredNode) - this._lastHoveredNode.setHovered(true); - }, - - /** - * @param {!Event} event - */ - _onContextMenu: function(event) - { - if (!this._target) - return; - var node = this._treeOutline.treeElementFromEvent(event); - if (!node || !(node instanceof WebInspector.LogTreeElement)) - return; - var logItem = /** @type {!WebInspector.LogTreeElement} */ (node)._logItem; - if (!logItem.nodeId()) - return; - var contextMenu = new WebInspector.ContextMenu(event); - var domNode = new WebInspector.DeferredDOMNode(this._target, logItem.nodeId()); - contextMenu.appendApplicableItems(domNode); - contextMenu.show(); - }, - __proto__: WebInspector.VBox.prototype }; @@ -376,7 +338,7 @@ }, /** - * @param {!Object<string,*>} param + * @param {*} param * @param {string} name * @return {string} */ @@ -397,7 +359,7 @@ }, /** - * @param {?Array<!Object<string, *>>} params + * @param {?Object<string, *>} params * @return {string} */ _paramsToString: function(params) @@ -418,36 +380,6 @@ this.title = title; }, - /** - * @param {boolean} hovered - */ - setHovered: function(hovered) - { - this.listItemElement.classList.toggle("hovered", hovered); - var target = this._ownerView._target; - if (!target) - return; - if (!hovered) { - WebInspector.DOMModel.hideDOMNodeHighlight(); - return; - } - var logItem = /** @type {!WebInspector.PaintProfilerLogItem} */ (this._logItem); - if (!logItem) - return; - var backendNodeId = logItem.nodeId(); - if (!backendNodeId) - return; - new WebInspector.DeferredDOMNode(target, backendNodeId).resolve(highlightNode); - /** - * @param {?WebInspector.DOMNode} node - */ - function highlightNode(node) - { - if (node) - node.highlight(); - } - }, - __proto__: TreeElement.prototype };
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js new file mode 100644 index 0000000..853765d8 --- /dev/null +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineController.js
@@ -0,0 +1,296 @@ +// 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. + +/** + * @constructor + * @param {!WebInspector.TimelineLifecycleDelegate} delegate + * @param {!WebInspector.TracingModel} tracingModel + * @implements {WebInspector.TargetManager.Observer} + * @implements {WebInspector.TracingManagerClient} + */ +WebInspector.TimelineController = function(delegate, tracingModel) +{ + this._delegate = delegate; + this._tracingModel = tracingModel; + this._targets = []; + WebInspector.targetManager.observeTargets(this); +} + +WebInspector.TimelineController.prototype = { + /** + * @param {boolean} captureCauses + * @param {boolean} enableJSSampling + * @param {boolean} captureMemory + * @param {boolean} capturePictures + * @param {boolean} captureFilmStrip + */ + startRecording: function(captureCauses, enableJSSampling, captureMemory, capturePictures, captureFilmStrip) + { + function disabledByDefault(category) + { + return "disabled-by-default-" + category; + } + var categoriesArray = [ + "-*", + "devtools.timeline", + disabledByDefault("devtools.timeline"), + disabledByDefault("devtools.timeline.frame"), + WebInspector.TracingModel.TopLevelEventCategory, + WebInspector.TimelineModel.Category.Console, + WebInspector.TimelineModel.Category.UserTiming + ]; + if (Runtime.experiments.isEnabled("timelineLatencyInfo")) + categoriesArray.push(WebInspector.TimelineModel.Category.LatencyInfo) + + if (Runtime.experiments.isEnabled("timelineFlowEvents")) { + categoriesArray.push(disabledByDefault("toplevel.flow"), + disabledByDefault("ipc.flow")); + } + if (Runtime.experiments.isEnabled("timelineTracingJSProfile") && enableJSSampling) { + categoriesArray.push(disabledByDefault("v8.cpu_profile")); + if (WebInspector.moduleSetting("highResolutionCpuProfiling").get()) + categoriesArray.push(disabledByDefault("v8.cpu_profile.hires")); + } + if (captureCauses || enableJSSampling) + categoriesArray.push(disabledByDefault("devtools.timeline.stack")); + if (captureCauses && Runtime.experiments.isEnabled("timelineInvalidationTracking")) + categoriesArray.push(disabledByDefault("devtools.timeline.invalidationTracking")); + if (capturePictures) { + categoriesArray.push(disabledByDefault("devtools.timeline.layers"), + disabledByDefault("devtools.timeline.picture"), + disabledByDefault("blink.graphics_context_annotations")); + } + if (captureFilmStrip) + categoriesArray.push(disabledByDefault("devtools.screenshot")); + + var categories = categoriesArray.join(","); + this._startRecordingWithCategories(categories, enableJSSampling); + }, + + stopRecording: function() + { + WebInspector.targetManager.resumeAllTargets(); + this._allProfilesStoppedPromise = this._stopProfilingOnAllTargets(); + if (this._targets[0]) + this._targets[0].tracingManager.stop(); + this._delegate.loadingStarted(); + }, + + /** + * @override + * @param {!WebInspector.Target} target + */ + targetAdded: function(target) + { + this._targets.push(target); + if (this._profiling) + this._startProfilingOnTarget(target); + }, + + /** + * @override + * @param {!WebInspector.Target} target + */ + targetRemoved: function(target) + { + this._targets.remove(target, true); + // FIXME: We'd like to stop profiling on the target and retrieve a profile + // but it's too late. Backend connection is closed. + }, + + /** + * @param {!WebInspector.Target} target + * @return {!Promise} + */ + _startProfilingOnTarget: function(target) + { + return target.profilerAgent().start(); + }, + + /** + * @return {!Promise} + */ + _startProfilingOnAllTargets: function() + { + var intervalUs = WebInspector.moduleSetting("highResolutionCpuProfiling").get() ? 100 : 1000; + this._targets[0].profilerAgent().setSamplingInterval(intervalUs); + this._profiling = true; + return Promise.all(this._targets.map(this._startProfilingOnTarget)); + }, + + /** + * @param {!WebInspector.Target} target + * @return {!Promise} + */ + _stopProfilingOnTarget: function(target) + { + /** + * @param {?Protocol.Error} error + * @param {?ProfilerAgent.CPUProfile} profile + * @return {?ProfilerAgent.CPUProfile} + */ + function extractProfile(error, profile) + { + return !error && profile ? profile : null; + } + return target.profilerAgent().stop(extractProfile).then(this._addCpuProfile.bind(this, target.id())); + }, + + /** + * @return {!Promise} + */ + _stopProfilingOnAllTargets: function() + { + var targets = this._profiling ? this._targets : []; + this._profiling = false; + return Promise.all(targets.map(this._stopProfilingOnTarget, this)); + }, + + /** + * @param {string} categories + * @param {boolean=} enableJSSampling + * @param {function(?string)=} callback + */ + _startRecordingWithCategories: function(categories, enableJSSampling, callback) + { + if (!this._targets.length) + return; + WebInspector.targetManager.suspendAllTargets(); + var profilingStartedPromise = enableJSSampling && !Runtime.experiments.isEnabled("timelineTracingJSProfile") ? + this._startProfilingOnAllTargets() : Promise.resolve(); + var samplingFrequencyHz = WebInspector.moduleSetting("highResolutionCpuProfiling").get() ? 10000 : 1000; + var options = "sampling-frequency=" + samplingFrequencyHz; + var mainTarget = this._targets[0]; + var tracingManager = mainTarget.tracingManager; + mainTarget.resourceTreeModel.suspendReload(); + profilingStartedPromise.then(tracingManager.start.bind(tracingManager, this, categories, options, onTraceStarted)); + /** + * @param {?string} error + */ + function onTraceStarted(error) + { + mainTarget.resourceTreeModel.resumeReload(); + if (callback) + callback(error); + } + }, + + /** + * @override + */ + tracingStarted: function() + { + this._tracingModel.reset(); + this._delegate.recordingStarted(); + }, + + /** + * @param {!Array.<!WebInspector.TracingManager.EventPayload>} events + * @override + */ + traceEventsCollected: function(events) + { + this._tracingModel.addEvents(events); + }, + + /** + * @override + */ + tracingComplete: function() + { + if (!this._allProfilesStoppedPromise) { + this._didStopRecordingTraceEvents(); + return; + } + this._allProfilesStoppedPromise.then(this._didStopRecordingTraceEvents.bind(this)); + this._allProfilesStoppedPromise = null; + }, + + _didStopRecordingTraceEvents: function() + { + this._injectCpuProfileEvents(); + this._tracingModel.tracingComplete(); + this._delegate.loadingComplete(true); + }, + + /** + * @param {number} pid + * @param {number} tid + * @param {?ProfilerAgent.CPUProfile} cpuProfile + */ + _injectCpuProfileEvent: function(pid, tid, cpuProfile) + { + if (!cpuProfile) + return; + var cpuProfileEvent = /** @type {!WebInspector.TracingManager.EventPayload} */ ({ + cat: WebInspector.TracingModel.DevToolsMetadataEventCategory, + ph: WebInspector.TracingModel.Phase.Instant, + ts: this._tracingModel.maximumRecordTime() * 1000, + pid: pid, + tid: tid, + name: WebInspector.TimelineModel.RecordType.CpuProfile, + args: { data: { cpuProfile: cpuProfile } } + }); + this._tracingModel.addEvents([cpuProfileEvent]); + }, + + _injectCpuProfileEvents: function() + { + if (!this._cpuProfiles) + return; + + var metadataEventTypes = WebInspector.TimelineModel.DevToolsMetadataEvent; + var metadataEvents = this._tracingModel.devToolsMetadataEvents(); + var mainMetaEvent = metadataEvents.filter(event => event.name === metadataEventTypes.TracingStartedInPage).peekLast(); + if (!mainMetaEvent) + return; + + var pid = mainMetaEvent.thread.process().id(); + var mainTarget = this._targets[0]; + var mainCpuProfile = this._cpuProfiles.get(mainTarget.id()); + this._injectCpuProfileEvent(pid, mainMetaEvent.thread.id(), mainCpuProfile); + + var workerMetaEvents = metadataEvents.filter(event => event.name === metadataEventTypes.TracingSessionIdForWorker); + for (var metaEvent of workerMetaEvents) { + var workerId = metaEvent.args["data"]["workerId"]; + var target = mainTarget.workerManager ? mainTarget.workerManager.targetByWorkerId(workerId) : null; + if (!target) + continue; + var cpuProfile = this._cpuProfiles.get(target.id()); + this._injectCpuProfileEvent(pid, metaEvent.args["data"]["workerThreadId"], cpuProfile); + } + this._cpuProfiles = null; + }, + + /** + * @param {number} usage + * @override + */ + tracingBufferUsage: function(usage) + { + this._delegate.recordingProgress(usage); + }, + + /** + * @param {number} progress + * @override + */ + eventsRetrievalProgress: function(progress) + { + this._delegate.loadingProgress(progress); + }, + + /** + * @param {number} targetId + * @param {?ProfilerAgent.CPUProfile} cpuProfile + */ + _addCpuProfile: function(targetId, cpuProfile) + { + if (!cpuProfile) + return; + if (!this._cpuProfiles) + this._cpuProfiles = new Map(); + this._cpuProfiles.set(targetId, cpuProfile); + } +}
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js index 05b2e7d..ef01c15 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineFlameChart.js
@@ -1267,7 +1267,6 @@ this._onMainEntrySelected = this._onEntrySelected.bind(this, this._dataProvider); this._onNetworkEntrySelected = this._onEntrySelected.bind(this, this._networkDataProvider); - this._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, this._onRecordingStarted, this); this._mainView.addEventListener(WebInspector.FlameChart.Events.EntrySelected, this._onMainEntrySelected, this); this._networkView.addEventListener(WebInspector.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); WebInspector.blackboxManager.addChangeListener(this.refreshRecords, this); @@ -1279,7 +1278,6 @@ */ dispose: function() { - this._model.removeEventListener(WebInspector.TimelineModel.Events.RecordingStarted, this._onRecordingStarted, this); this._mainView.removeEventListener(WebInspector.FlameChart.Events.EntrySelected, this._onMainEntrySelected, this); this._networkView.removeEventListener(WebInspector.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); WebInspector.blackboxManager.removeChangeListener(this.refreshRecords, this); @@ -1370,7 +1368,6 @@ */ reset: function() { - this._automaticallySizeWindow = true; this._dataProvider.reset(); this._mainView.reset(); this._mainView.setWindowTimes(0, Infinity); @@ -1379,13 +1376,6 @@ this._networkView.setWindowTimes(0, Infinity); }, - _onRecordingStarted: function() - { - this._automaticallySizeWindow = true; - this._mainView.reset(); - this._networkView.reset(); - }, - /** * @override * @param {number} startTime
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js index 051bd61..20dbd26 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineLoader.js
@@ -147,6 +147,7 @@ if (this._firstChunk) { this._firstChunk = false; + this._model.reset(); if (this._looksLikeAppVersion(items[0])) { this._reportErrorAndCancelLoading(WebInspector.UIString("Legacy Timeline format is not supported.")); return; @@ -185,7 +186,7 @@ */ close: function() { - this._model._loadedFromFile = true; + this._model.tracingComplete(); if (this._delegate) this._delegate.loadingComplete(true); },
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js index 3f27d0c..3a47aec 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelineModel.js
@@ -30,20 +30,12 @@ /** * @constructor - * @param {!WebInspector.TracingModel} tracingModel * @param {!WebInspector.TimelineModel.Filter} eventFilter - * @extends {WebInspector.Object} - * @implements {WebInspector.TargetManager.Observer} - * @implements {WebInspector.TracingManagerClient} */ -WebInspector.TimelineModel = function(tracingModel, eventFilter) +WebInspector.TimelineModel = function(eventFilter) { - WebInspector.Object.call(this); - this._tracingModel = tracingModel; this._eventFilter = eventFilter; - this._targets = []; this.reset(); - WebInspector.targetManager.observeTargets(this); } /** @@ -170,14 +162,6 @@ CpuProfile: "CpuProfile" } -WebInspector.TimelineModel.Events = { - RecordsCleared: "RecordsCleared", - RecordingStarted: "RecordingStarted", - RecordingStopped: "RecordingStopped", - BufferUsage: "BufferUsage", - RetrieveEventsProgress: "RetrieveEventsProgress" -} - WebInspector.TimelineModel.Category = { Console: "blink.console", UserTiming: "blink.user_timing", @@ -423,64 +407,6 @@ WebInspector.TimelineModel.prototype = { /** - * @param {boolean} captureCauses - * @param {boolean} enableJSSampling - * @param {boolean} captureMemory - * @param {boolean} capturePictures - * @param {boolean} captureFilmStrip - */ - startRecording: function(captureCauses, enableJSSampling, captureMemory, capturePictures, captureFilmStrip) - { - function disabledByDefault(category) - { - return "disabled-by-default-" + category; - } - var categoriesArray = [ - "-*", - "devtools.timeline", - disabledByDefault("devtools.timeline"), - disabledByDefault("devtools.timeline.frame"), - WebInspector.TracingModel.TopLevelEventCategory, - WebInspector.TimelineModel.Category.Console, - WebInspector.TimelineModel.Category.UserTiming - ]; - if (Runtime.experiments.isEnabled("timelineLatencyInfo")) - categoriesArray.push(WebInspector.TimelineModel.Category.LatencyInfo) - - if (Runtime.experiments.isEnabled("timelineFlowEvents")) { - categoriesArray.push(disabledByDefault("toplevel.flow"), - disabledByDefault("ipc.flow")); - } - if (Runtime.experiments.isEnabled("timelineTracingJSProfile") && enableJSSampling) { - categoriesArray.push(disabledByDefault("v8.cpu_profile")); - if (WebInspector.moduleSetting("highResolutionCpuProfiling").get()) - categoriesArray.push(disabledByDefault("v8.cpu_profile.hires")); - } - if (captureCauses || enableJSSampling) - categoriesArray.push(disabledByDefault("devtools.timeline.stack")); - if (captureCauses && Runtime.experiments.isEnabled("timelineInvalidationTracking")) - categoriesArray.push(disabledByDefault("devtools.timeline.invalidationTracking")); - if (capturePictures) { - categoriesArray.push(disabledByDefault("devtools.timeline.layers"), - disabledByDefault("devtools.timeline.picture"), - disabledByDefault("blink.graphics_context_annotations")); - } - if (captureFilmStrip) - categoriesArray.push(disabledByDefault("devtools.screenshot")); - - var categories = categoriesArray.join(","); - this._startRecordingWithCategories(categories, enableJSSampling); - }, - - stopRecording: function() - { - WebInspector.targetManager.resumeAllTargets(); - this._allProfilesStoppedPromise = this._stopProfilingOnAllTargets(); - if (this._targets[0]) - this._targets[0].tracingManager.stop(); - }, - - /** * @param {?function(!WebInspector.TimelineModel.Record)|?function(!WebInspector.TimelineModel.Record,number)} preOrderCallback * @param {function(!WebInspector.TimelineModel.Record)|function(!WebInspector.TimelineModel.Record,number)=} postOrderCallback */ @@ -541,197 +467,22 @@ target: function() { // FIXME: Consider returning null for loaded traces. - return this._targets[0]; + return WebInspector.targetManager.targets()[0]; }, /** - * @param {!Array.<!WebInspector.TracingManager.EventPayload>} events + * @param {!WebInspector.TracingModel} tracingModel + * @param {boolean=} produceTraceStartedInPage */ - setEventsForTest: function(events) + setEvents: function(tracingModel, produceTraceStartedInPage) { - this.startCollectingTraceEvents(false); - this._tracingModel.addEvents(events); - this.tracingComplete(); - }, - - /** - * @override - * @param {!WebInspector.Target} target - */ - targetAdded: function(target) - { - this._targets.push(target); - if (this._profiling) - this._startProfilingOnTarget(target); - }, - - /** - * @override - * @param {!WebInspector.Target} target - */ - targetRemoved: function(target) - { - this._targets.remove(target, true); - // FIXME: We'd like to stop profiling on the target and retrieve a profile - // but it's too late. Backend connection is closed. - }, - - /** - * @param {!WebInspector.Target} target - * @return {!Promise} - */ - _startProfilingOnTarget: function(target) - { - return target.profilerAgent().start(); - }, - - /** - * @return {!Promise} - */ - _startProfilingOnAllTargets: function() - { - var intervalUs = WebInspector.moduleSetting("highResolutionCpuProfiling").get() ? 100 : 1000; - this._targets[0].profilerAgent().setSamplingInterval(intervalUs); - this._profiling = true; - return Promise.all(this._targets.map(this._startProfilingOnTarget)); - }, - - /** - * @param {!WebInspector.Target} target - * @return {!Promise} - */ - _stopProfilingOnTarget: function(target) - { - /** - * @param {?Protocol.Error} error - * @param {?ProfilerAgent.CPUProfile} profile - * @return {?ProfilerAgent.CPUProfile} - */ - function extractProfile(error, profile) - { - return !error && profile ? profile : null; - } - return target.profilerAgent().stop(extractProfile).then(this._addCpuProfile.bind(this, target.id())); - }, - - /** - * @return {!Promise} - */ - _stopProfilingOnAllTargets: function() - { - var targets = this._profiling ? this._targets : []; - this._profiling = false; - return Promise.all(targets.map(this._stopProfilingOnTarget, this)); - }, - - /** - * @param {string} categories - * @param {boolean=} enableJSSampling - * @param {function(?string)=} callback - */ - _startRecordingWithCategories: function(categories, enableJSSampling, callback) - { - if (!this._targets.length) - return; - WebInspector.targetManager.suspendAllTargets(); - var profilingStartedPromise = enableJSSampling && !Runtime.experiments.isEnabled("timelineTracingJSProfile") ? - this._startProfilingOnAllTargets() : Promise.resolve(); - var samplingFrequencyHz = WebInspector.moduleSetting("highResolutionCpuProfiling").get() ? 10000 : 1000; - var options = "sampling-frequency=" + samplingFrequencyHz; - var mainTarget = this._targets[0]; - var tracingManager = mainTarget.tracingManager; - mainTarget.resourceTreeModel.suspendReload(); - profilingStartedPromise.then(tracingManager.start.bind(tracingManager, this, categories, options, onTraceStarted)); - /** - * @param {?string} error - */ - function onTraceStarted(error) - { - mainTarget.resourceTreeModel.resumeReload(); - if (callback) - callback(error); - } - }, - - /** - * @param {boolean} fromFile - */ - startCollectingTraceEvents: function(fromFile) - { - this._loadedFromFile = fromFile; - this._tracingModel.reset(); this.reset(); - this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordingStarted, { fromFile: fromFile }); - }, - - /** - * @override - */ - tracingStarted: function() - { - this.startCollectingTraceEvents(false); - }, - - /** - * @param {!Array.<!WebInspector.TracingManager.EventPayload>} events - * @override - */ - traceEventsCollected: function(events) - { - this._tracingModel.addEvents(events); - }, - - /** - * @override - */ - tracingComplete: function() - { - if (!this._allProfilesStoppedPromise) { - this._didStopRecordingTraceEvents(); - return; - } - this._allProfilesStoppedPromise.then(this._didStopRecordingTraceEvents.bind(this)); - this._allProfilesStoppedPromise = null; - }, - - /** - * @param {number} usage - * @override - */ - tracingBufferUsage: function(usage) - { - this.dispatchEventToListeners(WebInspector.TimelineModel.Events.BufferUsage, usage); - }, - - /** - * @param {number} progress - * @override - */ - eventsRetrievalProgress: function(progress) - { - this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RetrieveEventsProgress, progress); - }, - - /** - * @param {number} targetId - * @param {?ProfilerAgent.CPUProfile} cpuProfile - */ - _addCpuProfile: function(targetId, cpuProfile) - { - if (!cpuProfile) - return; - if (!this._cpuProfiles) - this._cpuProfiles = new Map(); - this._cpuProfiles.set(targetId, cpuProfile); - }, - - _didStopRecordingTraceEvents: function() - { - var metadataEvents = this._processMetadataEvents(); - this._injectCpuProfileEvents(metadataEvents); - this._tracingModel.tracingComplete(); - this._resetProcessingState(); + + this._minimumRecordTime = tracingModel.minimumRecordTime(); + this._maximumRecordTime = tracingModel.maximumRecordTime(); + + var metadataEvents = this._processMetadataEvents(tracingModel, !!produceTraceStartedInPage); var startTime = 0; for (var i = 0, length = metadataEvents.page.length; i < length; i++) { var metaEvent = metadataEvents.page[i]; @@ -748,21 +499,21 @@ this._inspectedTargetEvents.sort(WebInspector.TracingModel.Event.compareStartTime); this._cpuProfiles = null; - this._processBrowserEvents(); + this._processBrowserEvents(tracingModel); this._buildTimelineRecords(); - this._buildGPUTasks(); + this._buildGPUTasks(tracingModel); this._insertFirstPaintEvent(); this._resetProcessingState(); - - this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordingStopped); }, /** + * @param {!WebInspector.TracingModel} tracingModel + * @param {boolean} produceTraceStartedInPage * @return {!WebInspector.TimelineModel.MetadataEvents} */ - _processMetadataEvents: function() + _processMetadataEvents: function(tracingModel, produceTraceStartedInPage) { - var metadataEvents = this._tracingModel.devToolsMetadataEvents(); + var metadataEvents = tracingModel.devToolsMetadataEvents(); var pageDevToolsMetadataEvents = []; var workersDevToolsMetadataEvents = []; @@ -778,7 +529,7 @@ } if (!pageDevToolsMetadataEvents.length) { // The trace is probably coming not from DevTools. Make a mock Metadata event. - var pageMetaEvent = this._loadedFromFile ? this._makeMockPageMetadataEvent() : null; + var pageMetaEvent = produceTraceStartedInPage ? this._makeMockPageMetadataEvent(tracingModel) : null; if (!pageMetaEvent) { console.error(WebInspector.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage + " event not found."); return {page: [], workers: []}; @@ -815,13 +566,14 @@ }, /** + * @param {!WebInspector.TracingModel} tracingModel * @return {?WebInspector.TracingModel.Event} */ - _makeMockPageMetadataEvent: function() + _makeMockPageMetadataEvent: function(tracingModel) { var rendererMainThreadName = WebInspector.TimelineModel.RendererMainThreadName; // FIXME: pick up the first renderer process for now. - var process = Object.values(this._tracingModel.sortedProcesses()).filter(function(p) { return p.threadByName(rendererMainThreadName); })[0]; + var process = Object.values(tracingModel.sortedProcesses()).filter(function(p) { return p.threadByName(rendererMainThreadName); })[0]; var thread = process && process.threadByName(rendererMainThreadName); if (!thread) return null; @@ -829,57 +581,11 @@ WebInspector.TracingModel.DevToolsMetadataEventCategory, WebInspector.TimelineModel.DevToolsMetadataEvent.TracingStartedInPage, WebInspector.TracingModel.Phase.Metadata, - this._tracingModel.minimumRecordTime(), thread); + tracingModel.minimumRecordTime(), thread); pageMetaEvent.addArgs({"data": {"sessionId": "mockSessionId"}}); return pageMetaEvent; }, - /** - * @param {number} pid - * @param {number} tid - * @param {?ProfilerAgent.CPUProfile} cpuProfile - */ - _injectCpuProfileEvent: function(pid, tid, cpuProfile) - { - if (!cpuProfile) - return; - var cpuProfileEvent = /** @type {!WebInspector.TracingManager.EventPayload} */ ({ - cat: WebInspector.TracingModel.DevToolsMetadataEventCategory, - ph: WebInspector.TracingModel.Phase.Instant, - ts: this._tracingModel.maximumRecordTime() * 1000, - pid: pid, - tid: tid, - name: WebInspector.TimelineModel.RecordType.CpuProfile, - args: { data: { cpuProfile: cpuProfile } } - }); - this._tracingModel.addEvents([cpuProfileEvent]); - }, - - /** - * @param {!WebInspector.TimelineModel.MetadataEvents} metadataEvents - */ - _injectCpuProfileEvents: function(metadataEvents) - { - if (!this._cpuProfiles) - return; - var mainMetaEvent = metadataEvents.page.peekLast(); - if (!mainMetaEvent) - return; - var pid = mainMetaEvent.thread.process().id(); - var mainTarget = this._targets[0]; - var mainCpuProfile = this._cpuProfiles.get(mainTarget.id()); - this._injectCpuProfileEvent(pid, mainMetaEvent.thread.id(), mainCpuProfile); - for (var metaEvent of metadataEvents.workers) { - var workerId = metaEvent.args["data"]["workerId"]; - var target = mainTarget.workerManager ? mainTarget.workerManager.targetByWorkerId(workerId) : null; - if (!target) - continue; - var cpuProfile = this._cpuProfiles.get(target.id()); - this._injectCpuProfileEvent(pid, metaEvent.args["data"]["workerThreadId"], cpuProfile); - } - this._cpuProfiles = null; - }, - _insertFirstPaintEvent: function() { if (!this._firstCompositeLayers) @@ -898,9 +604,12 @@ this._eventDividerRecords.splice(insertionIndexForObjectInListSortedByFunction(firstPaintRecord, this._eventDividerRecords, WebInspector.TimelineModel.Record._compareStartTime), 0, firstPaintRecord); }, - _processBrowserEvents: function() + /** + * @param {!WebInspector.TracingModel} tracingModel + */ + _processBrowserEvents: function(tracingModel) { - var browserMain = this._tracingModel.threadByName("Browser", "CrBrowserMain"); + var browserMain = tracingModel.threadByName("Browser", "CrBrowserMain"); if (!browserMain) return; // Disregard regular events, we don't need them yet, but still process to get proper metadata. @@ -933,9 +642,12 @@ this._records = topLevelRecords; }, - _buildGPUTasks: function() + /** + * @param {!WebInspector.TracingModel} tracingModel + */ + _buildGPUTasks: function(tracingModel) { - var mainThread = this._tracingModel.threadByName("GPU Process", "CrGpuMain"); + var mainThread = tracingModel.threadByName("GPU Process", "CrGpuMain"); if (!mainThread) return; var events = mainThread.events(); @@ -1368,8 +1080,8 @@ this._sessionId = null; /** @type {?number} */ this._mainFrameNodeId = null; - this._loadedFromFile = false; - this.dispatchEventToListeners(WebInspector.TimelineModel.Events.RecordsCleared); + this._minimumRecordTime = 0; + this._maximumRecordTime = 0; }, /** @@ -1377,7 +1089,7 @@ */ minimumRecordTime: function() { - return this._tracingModel.minimumRecordTime(); + return this._minimumRecordTime; }, /** @@ -1385,7 +1097,7 @@ */ maximumRecordTime: function() { - return this._tracingModel.maximumRecordTime(); + return this._maximumRecordTime; }, /** @@ -1498,8 +1210,6 @@ } return zeroStartRequestsList.concat(requestsList); }, - - __proto__: WebInspector.Object.prototype } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js index e527444..d59e1f8 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js +++ b/third_party/WebKit/Source/devtools/front_end/timeline/TimelinePanel.js
@@ -53,16 +53,12 @@ // Create models. this._tracingModelBackingStorage = new WebInspector.TempFileBackingStorage("tracing"); this._tracingModel = new WebInspector.TracingModel(this._tracingModelBackingStorage); - this._model = new WebInspector.TimelineModel(this._tracingModel, WebInspector.TimelineUIUtils.visibleEventsFilter()); + this._model = new WebInspector.TimelineModel(WebInspector.TimelineUIUtils.visibleEventsFilter()); this._frameModel = new WebInspector.TracingTimelineFrameModel(); if (Runtime.experiments.isEnabled("timelineLatencyInfo")) this._irModel = new WebInspector.TimelineIRModel(); - this._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStarted, this._onRecordingStarted, this); - this._model.addEventListener(WebInspector.TimelineModel.Events.RecordingStopped, this._onRecordingStopped, this); - this._model.addEventListener(WebInspector.TimelineModel.Events.RecordsCleared, this._onRecordsCleared, this); - this._model.addEventListener(WebInspector.TimelineModel.Events.BufferUsage, this._onTracingBufferUsage, this); - this._model.addEventListener(WebInspector.TimelineModel.Events.RetrieveEventsProgress, this._onRetrieveEventsProgress, this); + this._controller = new WebInspector.TimelineController(this, this._tracingModel); if (Runtime.experiments.isEnabled("cpuThrottling")) this._cpuThrottlingManager = new WebInspector.CPUThrottlingManager(); @@ -619,12 +615,10 @@ { console.assert(!this._statusPane, "Status pane is already opened."); this._setState(WebInspector.TimelinePanel.State.StartPending); - this._statusPane = new WebInspector.TimelinePanel.StatusPane(true, this._stopRecording.bind(this)); - this._statusPane.showPane(this._statusPaneContainer); - this._statusPane.updateStatus(WebInspector.UIString("Initializing recording\u2026")); + this._showRecordingStarted(); this._autoRecordGeneration = userInitiated ? null : Symbol("Generation"); - this._model.startRecording(true, this._captureJSProfileSetting.get(), this._captureMemorySetting.get(), this._captureLayersAndPicturesSetting.get(), this._captureFilmStripSetting && this._captureFilmStripSetting.get()); + this._controller.startRecording(true, this._captureJSProfileSetting.get(), this._captureMemorySetting.get(), this._captureLayersAndPicturesSetting.get(), this._captureFilmStripSetting && this._captureFilmStripSetting.get()); for (var i = 0; i < this._overviewControls.length; ++i) this._overviewControls[i].timelineStarted(); @@ -637,12 +631,14 @@ _stopRecording: function() { - this._statusPane.finish(); - this._statusPane.updateStatus(WebInspector.UIString("Retrieving timeline\u2026")); - this._statusPane.updateProgressBar(WebInspector.UIString("Received"), 0); + if (this._statusPane) { + this._statusPane.finish(); + this._statusPane.updateStatus(WebInspector.UIString("Stopping timeline\u2026")); + this._statusPane.updateProgressBar(WebInspector.UIString("Received"), 0); + } this._setState(WebInspector.TimelinePanel.State.StopPending); this._autoRecordGeneration = null; - this._model.stopRecording(); + this._controller.stopRecording(); this._setUIControlsEnabled(true); }, @@ -684,10 +680,7 @@ this._tracingModel.reset(); this._model.reset(); this._showRecordingHelpMessage(); - }, - _onRecordsCleared: function() - { this.requestWindowTimes(0, Infinity); delete this._selection; this._frameModel.reset(); @@ -702,39 +695,26 @@ }, /** - * @param {!WebInspector.Event} event + * @override */ - _onRecordingStarted: function(event) + recordingStarted: function() { - var fromFile = event.data && event.data.fromFile; - this._setState(fromFile ? WebInspector.TimelinePanel.State.Loading : WebInspector.TimelinePanel.State.Recording); - if (this._statusPane) { - this._statusPane.updateStatus(fromFile ? WebInspector.UIString("Loading\u2026") : WebInspector.UIString("Recording\u2026")); - this._statusPane.updateProgressBar(fromFile ? WebInspector.UIString("Loaded") : WebInspector.UIString("Buffer usage"), 0) - this._statusPane.startTimer(); - } + this._clear(); + this._setState(WebInspector.TimelinePanel.State.Recording); + this._showRecordingStarted(); + this._statusPane.updateStatus(WebInspector.UIString("Recording\u2026")); + this._statusPane.updateProgressBar(WebInspector.UIString("Buffer usage"), 0) + this._statusPane.startTimer(); + this._hideRecordingHelpMessage(); }, /** - * @param {!WebInspector.Event} event + * @override + * @param {number} usage */ - _onTracingBufferUsage: function(event) + recordingProgress: function(usage) { - var usage = /** @type {number} */ (event.data); - if (this._statusPane) - this._statusPane.updateProgressBar(WebInspector.UIString("Buffer usage"), usage * 100); - }, - - /** - * @param {!WebInspector.Event} event - */ - _onRetrieveEventsProgress: function(event) - { - if (!this._statusPane) - return; - this._statusPane.updateStatus(WebInspector.UIString("Retrieving timeline\u2026")); - var usage = /** @type {number} */ (event.data); - this._statusPane.updateProgressBar(WebInspector.UIString("Received"), usage * 100); + this._statusPane.updateProgressBar(WebInspector.UIString("Buffer usage"), usage * 100); }, _showRecordingHelpMessage: function() @@ -774,42 +754,21 @@ delete this._helpMessageElement; }, - _onRecordingStopped: function() - { - this._setState(WebInspector.TimelinePanel.State.Idle); - this._frameModel.reset(); - this._frameModel.addTraceEvents(this._model.target(), this._model.inspectedTargetEvents(), this._model.sessionId() || ""); - if (this._irModel) - this._irModel.populate(this._model); - this._overviewPane.reset(); - this._overviewPane.setBounds(this._model.minimumRecordTime(), this._model.maximumRecordTime()); - this._setAutoWindowTimes(); - this._refreshViews(); - for (var i = 0; i < this._overviewControls.length; ++i) - this._overviewControls[i].timelineStopped(); - this._setMarkers(); - this._overviewPane.scheduleUpdate(); - this._updateSearchHighlight(false, true); - if (this._statusPane) { - this._statusPane.hide(); - delete this._statusPane; - } - this._detailsSplitWidget.showBoth(); - }, - /** * @override */ loadingStarted: function() { this._hideRecordingHelpMessage(); - this._model.startCollectingTraceEvents(true); if (this._statusPane) this._statusPane.hide(); this._statusPane = new WebInspector.TimelinePanel.StatusPane(false, this._cancelLoading.bind(this)); this._statusPane.showPane(this._statusPaneContainer); this._statusPane.updateStatus(WebInspector.UIString("Loading timeline\u2026")); + // FIXME: make loading from backend cancelable as well. + if (!this._loader) + this._statusPane.finish(); this.loadingProgress(0); }, @@ -829,13 +788,46 @@ */ loadingComplete: function(success) { - if (!success) { - this._onRecordingStopped(); - this._clear(); - } else { - this._model.tracingComplete(); - } + var loadedFromFile = !!this._loader; delete this._loader; + this._setState(WebInspector.TimelinePanel.State.Idle); + + if (!success) { + this._statusPane.hide(); + delete this._statusPane; + this._clear(); + return; + } + + if (this._statusPane) + this._statusPane.updateStatus(WebInspector.UIString("Processing timeline\u2026")); + this._model.setEvents(this._tracingModel, loadedFromFile); + this._frameModel.reset(); + this._frameModel.addTraceEvents(this._model.target(), this._model.inspectedTargetEvents(), this._model.sessionId() || ""); + if (this._irModel) + this._irModel.populate(this._model); + if (this._statusPane) + this._statusPane.hide(); + delete this._statusPane; + this._overviewPane.reset(); + this._overviewPane.setBounds(this._model.minimumRecordTime(), this._model.maximumRecordTime()); + this._setAutoWindowTimes(); + this._refreshViews(); + for (var i = 0; i < this._overviewControls.length; ++i) + this._overviewControls[i].timelineStopped(); + this._setMarkers(); + this._overviewPane.scheduleUpdate(); + this._updateSearchHighlight(false, true); + this._detailsSplitWidget.showBoth(); + }, + + _showRecordingStarted: function() + { + if (this._statusPane) + return; + this._statusPane = new WebInspector.TimelinePanel.StatusPane(true, this._stopRecording.bind(this)); + this._statusPane.showPane(this._statusPaneContainer); + this._statusPane.updateStatus(WebInspector.UIString("Initializing recording\u2026")); }, _cancelLoading: function() @@ -1280,6 +1272,13 @@ } WebInspector.TimelineLifecycleDelegate.prototype = { + recordingStarted: function() {}, + + /** + * @param {number} usage + */ + recordingProgress: function(usage) {}, + loadingStarted: function() {}, /**
diff --git a/third_party/WebKit/Source/devtools/front_end/timeline/module.json b/third_party/WebKit/Source/devtools/front_end/timeline/module.json index 6ffb5376..11d544d1 100644 --- a/third_party/WebKit/Source/devtools/front_end/timeline/module.json +++ b/third_party/WebKit/Source/devtools/front_end/timeline/module.json
@@ -106,6 +106,7 @@ "LayerViewHost.js", "Layers3DView.js", "MemoryCountersGraph.js", + "TimelineController.js", "TimelineModel.js", "TimelineIRModel.js", "TimelineJSProfile.js",
diff --git a/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js b/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js index 415b2f1..8c373b0 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/ui/UIUtils.js
@@ -1665,7 +1665,7 @@ /** * @param {string} id - * @param {!CSSStyleSheet} styleSheet + * @param {!StyleSheet} styleSheet * @return {string} */ _patchForTheme: function(id, styleSheet)
diff --git a/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js b/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js index 07724d12..046a2b5 100644 --- a/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js +++ b/third_party/WebKit/Source/devtools/front_end/ui_lazy/DataGrid.js
@@ -159,8 +159,23 @@ // Keep in sync with .data-grid col.corner style rule. WebInspector.DataGrid.CornerWidth = 14; -/** @typedef {!{id: ?string, editable: boolean, longText: ?boolean, sort: !WebInspector.DataGrid.Order, sortable: boolean, align: !WebInspector.DataGrid.Align, nonSelectable: boolean}} */ -WebInspector.DataGrid.ColumnDescriptor; +/** + * @constructor + */ +WebInspector.DataGrid.ColumnDescriptor = function() +{ + /** @type {string} */ this.id; + /** @type {string} */ this.title; + /** @type {string} */ this.width; + /** @type {boolean} */ this.fixedWidth; + /** @type {boolean} */ this.sortable; + /** @type {?WebInspector.DataGrid.Order|undefined} */ this.sort; + /** @type {?WebInspector.DataGrid.Align|undefined} */ this.align; + /** @type {boolean|undefined} */ this.editable; + /** @type {boolean|undefined} */ this.nonSelectable; + /** @type {boolean|undefined} */ this.longText; + /** @type {boolean|undefined} */ this.disclosure; +} WebInspector.DataGrid.Events = { SelectedNode: "SelectedNode",
diff --git a/third_party/WebKit/Source/devtools/protocol.json b/third_party/WebKit/Source/devtools/protocol.json index 8ca06b8..1578651 100644 --- a/third_party/WebKit/Source/devtools/protocol.json +++ b/third_party/WebKit/Source/devtools/protocol.json
@@ -994,13 +994,6 @@ "description": "Disables reporting of execution contexts creation." }, { - "name": "isRunRequired", - "returns": [ - { "name": "result", "type": "boolean", "description": "True if the Runtime is in paused on start state." } - ], - "hidden": true - }, - { "name": "setCustomObjectFormatterEnabled", "parameters": [ { @@ -4234,19 +4227,7 @@ ] }, { - "name": "connectToWorker", - "parameters": [ - { "name": "workerId", "type": "string" } - ] - }, - { - "name": "disconnectFromWorker", - "parameters": [ - { "name": "workerId", "type": "string" } - ] - }, - { - "name": "setAutoconnectToWorkers", + "name": "setWaitForDebuggerOnStart", "parameters": [ { "name": "value", "type": "boolean" } ] @@ -4258,7 +4239,7 @@ "parameters": [ { "name": "workerId", "type": "string" }, { "name": "url", "type": "string" }, - { "name": "inspectorConnected", "type": "boolean" } + { "name": "waitingForDebugger", "type": "boolean" } ] }, {
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp index 2cf10aa..5a2abc3 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.cpp
@@ -275,7 +275,7 @@ ARIARoleMap* roleMap = new ARIARoleMap; for (size_t i = 0; i < WTF_ARRAY_LENGTH(roles); ++i) - roleMap->set(roles[i].ariaRole, roles[i].webcoreRole); + roleMap->set(String(roles[i].ariaRole), roles[i].webcoreRole); return roleMap; } @@ -1013,7 +1013,7 @@ if ((role == ListBoxOptionRole && parentRole == ListBoxRole) || (role == ListItemRole && parentRole == ListRole) || (role == MenuItemRole && parentRole == MenuRole) - || (role == RadioButtonRole && parentRole == RadioGroupRole) + || (role == RadioButtonRole) || (role == TabRole && parentRole == TabListRole) || (role == TreeItemRole && parentRole == TreeRole)) return true;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObject.h b/third_party/WebKit/Source/modules/accessibility/AXObject.h index df967a7..243fa2f 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObject.h +++ b/third_party/WebKit/Source/modules/accessibility/AXObject.h
@@ -547,6 +547,7 @@ virtual bool isAXLayoutObject() const { return false; } virtual bool isAXListBox() const { return false; } virtual bool isAXListBoxOption() const { return false; } + virtual bool isAXRadioInput() const { return false; } virtual bool isAXSVGRoot() const { return false; } // Check object role or purpose.
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp index 2f0f3dd9..17a69f0 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.cpp
@@ -29,6 +29,7 @@ #include "modules/accessibility/AXObjectCacheImpl.h" #include "core/HTMLNames.h" +#include "core/InputTypeNames.h" #include "core/dom/Document.h" #include "core/frame/FrameView.h" #include "core/frame/LocalFrame.h" @@ -66,6 +67,7 @@ #include "modules/accessibility/AXMenuListOption.h" #include "modules/accessibility/AXMenuListPopup.h" #include "modules/accessibility/AXProgressIndicator.h" +#include "modules/accessibility/AXRadioInput.h" #include "modules/accessibility/AXSVGRoot.h" #include "modules/accessibility/AXSlider.h" #include "modules/accessibility/AXSpinButton.h" @@ -306,6 +308,9 @@ if (isHTMLOptionElement(node)) return AXListBoxOption::create(layoutObject, *this); + if (isHTMLInputElement(node) && toHTMLInputElement(node)->type() == InputTypeNames::radio) + return AXRadioInput::create(layoutObject, *this); + if (layoutObject->isSVGRoot()) return AXSVGRoot::create(layoutObject, *this); @@ -933,6 +938,24 @@ toAXListBox(obj)->activeIndexChanged(); } +void AXObjectCacheImpl::radiobuttonRemovedFromGroup(HTMLInputElement* groupMember) +{ + AXObject* obj = get(groupMember); + if (!obj || !obj->isAXRadioInput()) + return; + + // The 'posInSet' and 'setSize' attributes should be updated from the first node, + // as the removed node is already detached from tree. + HTMLInputElement* firstRadio = toAXRadioInput(obj)->findFirstRadioButtonInGroup(groupMember); + AXObject* firstObj = get(firstRadio); + if (!firstObj || !firstObj->isAXRadioInput()) + return; + + toAXRadioInput(firstObj)->updatePosAndSetSize(1); + postNotification(firstObj, AXAriaAttributeChanged); + toAXRadioInput(firstObj)->requestUpdateToNextNode(true); +} + void AXObjectCacheImpl::handleLayoutComplete(LayoutObject* layoutObject) { if (!layoutObject)
diff --git a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h index 062a24f..95a0233b 100644 --- a/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h +++ b/third_party/WebKit/Source/modules/accessibility/AXObjectCacheImpl.h
@@ -65,6 +65,7 @@ virtual void listboxOptionStateChanged(HTMLOptionElement*); virtual void listboxSelectedChildrenChanged(HTMLSelectElement*); virtual void listboxActiveIndexChanged(HTMLSelectElement*); + virtual void radiobuttonRemovedFromGroup(HTMLInputElement*); void remove(LayoutObject*) override; void remove(Node*) override;
diff --git a/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp b/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp new file mode 100644 index 0000000..76c7657 --- /dev/null +++ b/third_party/WebKit/Source/modules/accessibility/AXRadioInput.cpp
@@ -0,0 +1,156 @@ +// 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 "modules/accessibility/AXRadioInput.h" + +#include "core/InputTypeNames.h" +#include "core/dom/ElementTraversal.h" +#include "core/html/HTMLFormElement.h" +#include "core/html/HTMLInputElement.h" +#include "modules/accessibility/AXObjectCacheImpl.h" + +namespace blink { + +namespace { + +HTMLElement* nextElement(const HTMLElement& element, HTMLFormElement* stayWithin, bool forward) +{ + return forward ? Traversal<HTMLElement>::next(element, static_cast<Node*>(stayWithin)) : Traversal<HTMLElement>::previous(element, static_cast<Node*>(stayWithin)); +} + +} // namespace + +using namespace HTMLNames; + +AXRadioInput::AXRadioInput(LayoutObject* layoutObject, AXObjectCacheImpl& axObjectCache) + : AXLayoutObject(layoutObject, axObjectCache) +{ + // Updates posInSet and setSize for the current object and the next objects. + if (!calculatePosInSet()) + return; + // When a new object is inserted, it needs to update setSize for the previous objects. + requestUpdateToNextNode(false); +} + +AXRadioInput* AXRadioInput::create(LayoutObject* layoutObject, AXObjectCacheImpl& axObjectCache) +{ + return new AXRadioInput(layoutObject, axObjectCache); +} + +void AXRadioInput::updatePosAndSetSize(int position) +{ + if (position) + m_posInSet = position; + m_setSize = sizeOfRadioGroup(); +} + +void AXRadioInput::requestUpdateToNextNode(bool forward) +{ + HTMLInputElement* nextElement = findNextRadioButtonInGroup(element(), forward); + AXObject* nextAXobject = axObjectCache().get(nextElement); + if (!nextAXobject || !nextAXobject->isAXRadioInput()) + return; + + int position = 0; + if (forward) + position = posInSet() + 1; + // If it is backward, it keeps position as positions are already assigned for previous objects. + // updatePosAndSetSize() is called with '0' and it doesn't modify m_posInSet and updates m_setSize as size is increased. + + toAXRadioInput(nextAXobject)->updatePosAndSetSize(position); + axObjectCache().postNotification(nextAXobject, AXObjectCacheImpl::AXAriaAttributeChanged); + toAXRadioInput(nextAXobject)->requestUpdateToNextNode(forward); +} + +HTMLInputElement* AXRadioInput::findFirstRadioButtonInGroup(HTMLInputElement* current) const +{ + while (HTMLInputElement* prevElement = findNextRadioButtonInGroup(current, false)) + current = prevElement; + return current; +} + +int AXRadioInput::posInSet() const +{ + if (hasAttribute(aria_posinsetAttr)) + return getAttribute(aria_posinsetAttr).toInt(); + return m_posInSet; +} + +int AXRadioInput::setSize() const +{ + if (hasAttribute(aria_setsizeAttr)) + return getAttribute(aria_setsizeAttr).toInt(); + return m_setSize; +} + +bool AXRadioInput::calculatePosInSet() +{ + // Calculate 'posInSet' attribute when AXRadioInputs need to be updated + // as a new AXRadioInput Object is added or one of objects from RadioGroup is removed. + bool needToUpdatePrev = false; + int position = 1; + HTMLInputElement* prevElement = findNextRadioButtonInGroup(element(), false); + if (prevElement) { + AXObject* object = axObjectCache().get(prevElement); + // If the previous element doesn't have AXObject yet, caculate position from the first element. + // Otherwise, get position from the previous AXObject. + if (!object || !object->isAXRadioInput()) { + position = countFromFirstElement(); + } else { + position = object->posInSet() + 1; + // It returns true if previous objects need to be updated. + // When AX tree exists already and a new node is inserted, + // as updating is started from the inserted node, + // we need to update setSize for previous nodes. + if (setSize() != object->setSize()) + needToUpdatePrev = true; + } + } + updatePosAndSetSize(position); + + // If it is not the last element, request update to the next node. + if (position != setSize()) + requestUpdateToNextNode(true); + return needToUpdatePrev; +} + +HTMLInputElement* AXRadioInput::findNextRadioButtonInGroup(HTMLInputElement* current, bool forward) const +{ + for (HTMLElement* htmlElement = nextElement(*current, current->form(), forward); htmlElement; htmlElement = nextElement(*htmlElement, current->form(), forward)) { + if (!isHTMLInputElement(*htmlElement)) + continue; + HTMLInputElement* inputElement = toHTMLInputElement(htmlElement); + if (current->form() == inputElement->form() && inputElement->type() == InputTypeNames::radio && inputElement->name() == current->name()) + return inputElement; + } + return nullptr; +} + +int AXRadioInput::countFromFirstElement() const +{ + int count = 1; + HTMLInputElement* current = element(); + while (HTMLInputElement* prevElement = findNextRadioButtonInGroup(current, false)) { + current = prevElement; + count++; + } + return count; +} + +HTMLInputElement* AXRadioInput::element() const +{ + return toHTMLInputElement(m_layoutObject->node()); +} + +int AXRadioInput::sizeOfRadioGroup() const +{ + int size = element()->sizeOfRadioGroup(); + // If it has no size in Group, it means that there is only itself. + if (!size) + return 1; + return size; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/accessibility/AXRadioInput.h b/third_party/WebKit/Source/modules/accessibility/AXRadioInput.h new file mode 100644 index 0000000..02fff652 --- /dev/null +++ b/third_party/WebKit/Source/modules/accessibility/AXRadioInput.h
@@ -0,0 +1,47 @@ +// 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 AXRadioInput_h +#define AXRadioInput_h + +#include "modules/accessibility/AXLayoutObject.h" + +namespace blink { + +class AXObjectCacheImpl; +class HTMLInputElement; + +class AXRadioInput final : public AXLayoutObject { + +public: + static AXRadioInput* create(LayoutObject*, AXObjectCacheImpl&); + ~AXRadioInput() override { } + + bool isAXRadioInput() const override { return true; } + void updatePosAndSetSize(int position = 0); + void requestUpdateToNextNode(bool forward); + HTMLInputElement* findFirstRadioButtonInGroup(HTMLInputElement* current) const; + + int posInSet() const final; + int setSize() const final; + +private: + AXRadioInput(LayoutObject*, AXObjectCacheImpl&); + bool calculatePosInSet(); + HTMLInputElement* findNextRadioButtonInGroup(HTMLInputElement* current, bool forward) const; + int countFromFirstElement() const; + HTMLInputElement* element() const; + int sizeOfRadioGroup() const; + + int m_posInSet; + int m_setSize; +}; + +DEFINE_AX_OBJECT_TYPE_CASTS(AXRadioInput, isAXRadioInput()); + +} // namespace blink + +#endif // AXRadioInput_h +
diff --git a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp index 46a1359..438a159f 100644 --- a/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/CanvasRenderingContext2DState.cpp
@@ -296,19 +296,7 @@ static void updateFilterReferences(HTMLCanvasElement* canvasElement, CanvasRenderingContext2D* context, const FilterOperations& filters) { context->clearFilterReferences(); - for (RefPtrWillBeRawPtr<FilterOperation> filterOperation : filters.operations()) { - if (filterOperation->type() != FilterOperation::REFERENCE) - continue; - - ReferenceFilterOperation* referenceFilterOperation = toReferenceFilterOperation(filterOperation.get()); - - // TODO(ajuma): Handle the case of filters defined in external documents - // (crbug.com/581135). - Element* filter = canvasElement->document().getElementById(referenceFilterOperation->fragment()); - if (!isSVGFilterElement(filter)) - continue; - context->addFilterReference(toSVGFilterElement(filter)); - } + context->addFilterReferences(filters, canvasElement->document()); } SkImageFilter* CanvasRenderingContext2DState::getFilter(Element* styleResolutionHost, const Font& font, IntSize canvasSize, CanvasRenderingContext2D* context) const @@ -325,6 +313,7 @@ resolverState.setStyle(filterStyle); StyleBuilder::applyProperty(CSSPropertyWebkitFilter, resolverState, m_filterValue.get()); + resolverState.loadPendingResources(); RefPtrWillBeRawPtr<FilterEffectBuilder> filterEffectBuilder = FilterEffectBuilder::create(); // We can't reuse m_fillPaint and m_strokePaint for the filter, since these incorporate
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp index aa495efd..dd66695 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerGlobalScope.cpp
@@ -18,6 +18,7 @@ // passed along to the created 'context'. RefPtrWillBeRawPtr<CompositorWorkerGlobalScope> context = adoptRefWillBeNoop(new CompositorWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, timeOrigin, startupData->m_starterOriginPrivilegeData.release(), startupData->m_workerClients.release())); context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders); + context->setAddressSpace(startupData->m_addressSpace); return context.release(); }
diff --git a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp index a162b2c..52ee62d 100644 --- a/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp +++ b/third_party/WebKit/Source/modules/compositorworker/CompositorWorkerThreadTest.cpp
@@ -147,6 +147,7 @@ adoptPtr(new Vector<CSPHeaderAndType>()), m_securityOrigin.get(), clients.release(), + WebURLRequest::AddressSpaceLocal, V8CacheOptionsDefault)); return adoptPtr(workerThread); }
diff --git a/third_party/WebKit/Source/modules/modules.gypi b/third_party/WebKit/Source/modules/modules.gypi index 082ec9cb..40a2149 100644 --- a/third_party/WebKit/Source/modules/modules.gypi +++ b/third_party/WebKit/Source/modules/modules.gypi
@@ -764,6 +764,8 @@ 'accessibility/AXObject.h', 'accessibility/AXProgressIndicator.cpp', 'accessibility/AXProgressIndicator.h', + 'accessibility/AXRadioInput.cpp', + 'accessibility/AXRadioInput.h', 'accessibility/AXSVGRoot.cpp', 'accessibility/AXSVGRoot.h', 'accessibility/AXSlider.cpp',
diff --git a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp index aff2af60..595f827 100644 --- a/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp +++ b/third_party/WebKit/Source/modules/serviceworkers/ServiceWorkerGlobalScope.cpp
@@ -73,6 +73,7 @@ context->setV8CacheOptions(startupData->m_v8CacheOptions); context->applyContentSecurityPolicyFromVector(*startupData->m_contentSecurityPolicyHeaders); + context->setAddressSpace(startupData->m_addressSpace); return context.release(); }
diff --git a/third_party/WebKit/Source/platform/blink_platform.gyp b/third_party/WebKit/Source/platform/blink_platform.gyp index ed3c26e..b1c485e3 100644 --- a/third_party/WebKit/Source/platform/blink_platform.gyp +++ b/third_party/WebKit/Source/platform/blink_platform.gyp
@@ -286,6 +286,8 @@ ['include', 'mac/VersionUtilMac\\.mm$'], ['include', 'mac/WebCoreNSCellExtras\\.h$'], ['include', 'mac/WebCoreNSCellExtras\\.mm$'], + ['include', 'scroll/ScrollbarThemeMac\\.h$'], + ['include', 'scroll/ScrollbarThemeMac\\.mm$'], # Mac uses only ScrollAnimatorMac. ['exclude', 'scroll/ScrollbarThemeNonMacCommon\\.(cpp|h)$'],
diff --git a/third_party/WebKit/Source/platform/blink_platform.gypi b/third_party/WebKit/Source/platform/blink_platform.gypi index 6fcc25f0..bff02505 100644 --- a/third_party/WebKit/Source/platform/blink_platform.gypi +++ b/third_party/WebKit/Source/platform/blink_platform.gypi
@@ -822,6 +822,8 @@ 'image-encoders/skia/WEBPImageEncoder.h', 'inspector_protocol/Allocator.h', 'inspector_protocol/Array.h', + 'inspector_protocol/Collections.h', + 'inspector_protocol/CollectionsWTF.h', 'inspector_protocol/ErrorSupport.cpp', 'inspector_protocol/ErrorSupport.h', 'inspector_protocol/Maybe.h', @@ -925,12 +927,8 @@ 'scroll/ScrollbarThemeAura.cpp', 'scroll/ScrollbarThemeAura.h', 'scroll/ScrollbarThemeClient.h', - 'scroll/ScrollbarThemeMacCommon.h', - 'scroll/ScrollbarThemeMacCommon.mm', - 'scroll/ScrollbarThemeMacNonOverlayAPI.h', - 'scroll/ScrollbarThemeMacNonOverlayAPI.mm', - 'scroll/ScrollbarThemeMacOverlayAPI.h', - 'scroll/ScrollbarThemeMacOverlayAPI.mm', + 'scroll/ScrollbarThemeMac.h', + 'scroll/ScrollbarThemeMac.mm', 'scroll/ScrollbarThemeMock.cpp', 'scroll/ScrollbarThemeMock.h', 'scroll/ScrollbarThemeNonMacCommon.cpp',
diff --git a/third_party/WebKit/Source/platform/graphics/paint/CullRect.h b/third_party/WebKit/Source/platform/graphics/paint/CullRect.h index 721bc95c..7d7d025 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/CullRect.h +++ b/third_party/WebKit/Source/platform/graphics/paint/CullRect.h
@@ -44,7 +44,6 @@ friend class FramePainter; friend class GridPainter; friend class SVGInlineTextBoxPainter; - friend class ScrollbarThemeMacNonOverlayAPI; friend class ReplicaPainter; friend class SVGPaintContext; friend class SVGRootInlineBoxPainter;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp index e92c387..1e9b880 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp
@@ -98,11 +98,9 @@ DEBUG_STRING_CASE(ScrollbarForwardButtonEnd); DEBUG_STRING_CASE(ScrollbarForwardButtonStart); DEBUG_STRING_CASE(ScrollbarForwardTrack); - DEBUG_STRING_CASE(ScrollbarHorizontal); DEBUG_STRING_CASE(ScrollbarThumb); DEBUG_STRING_CASE(ScrollbarTickmarks); DEBUG_STRING_CASE(ScrollbarTrackBackground); - DEBUG_STRING_CASE(ScrollbarVertical); DEBUG_STRING_CASE(SelectionTint); DEBUG_STRING_CASE(TableCellBackgroundFromColumnGroup); DEBUG_STRING_CASE(TableCellBackgroundFromColumn);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h index 73e6e84a..2ae4995 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h
@@ -89,11 +89,9 @@ ScrollbarForwardButtonEnd, ScrollbarForwardButtonStart, ScrollbarForwardTrack, - ScrollbarHorizontal, // For ScrollbarThemeMacNonOverlayAPI only. ScrollbarThumb, ScrollbarTickmarks, ScrollbarTrackBackground, - ScrollbarVertical, // For ScrollbarThemeMacNonOverlayAPI only. SelectionTint, TableCellBackgroundFromColumnGroup, TableCellBackgroundFromColumn,
diff --git a/third_party/WebKit/Source/platform/heap/Heap.cpp b/third_party/WebKit/Source/platform/heap/Heap.cpp index 09e2d82..69cbac7 100644 --- a/third_party/WebKit/Source/platform/heap/Heap.cpp +++ b/third_party/WebKit/Source/platform/heap/Heap.cpp
@@ -528,7 +528,7 @@ ASSERT(s_markingStack->isEmpty()); double timeForGlobalWeakProcessing = WTF::currentTimeMS() - startTime; - DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, globalWeakTimeHistogram, new CustomCountHistogram("BlinkGC.TimeForGlobalWeakPrcessing", 1, 10 * 1000, 50)); + DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, globalWeakTimeHistogram, new CustomCountHistogram("BlinkGC.TimeForGlobalWeakProcessing", 1, 10 * 1000, 50)); globalWeakTimeHistogram.count(timeForGlobalWeakProcessing); }
diff --git a/third_party/WebKit/Source/platform/heap/Heap.h b/third_party/WebKit/Source/platform/heap/Heap.h index 984ab60c..a2081bd 100644 --- a/third_party/WebKit/Source/platform/heap/Heap.h +++ b/third_party/WebKit/Source/platform/heap/Heap.h
@@ -68,17 +68,6 @@ freeHook(address); } - static void reallocHookIfEnabled(Address oldAddress, Address newAddress, size_t size, const char* typeName) - { - // Report a reallocation as a free followed by an allocation. - AllocationHook* allocationHook = m_allocationHook; - FreeHook* freeHook = m_freeHook; - if (UNLIKELY(allocationHook && freeHook)) { - freeHook(oldAddress); - allocationHook(newAddress, size, typeName); - } - } - private: static AllocationHook* m_allocationHook; static FreeHook* m_freeHook; @@ -239,7 +228,7 @@ allocationSize = (allocationSize + allocationMask) & ~allocationMask; return allocationSize; } - static Address allocateOnArenaIndex(ThreadState*, size_t, int arenaIndex, size_t gcInfoIndex); + static Address allocateOnArenaIndex(ThreadState*, size_t, int arenaIndex, size_t gcInfoIndex, const char* typeName); template<typename T> static Address allocate(size_t, bool eagerlySweep = false); template<typename T> static Address reallocate(void* previous, size_t); @@ -485,22 +474,22 @@ #define EAGERLY_FINALIZE_WILL_BE_REMOVED() #endif -inline Address Heap::allocateOnArenaIndex(ThreadState* state, size_t size, int arenaIndex, size_t gcInfoIndex) +inline Address Heap::allocateOnArenaIndex(ThreadState* state, size_t size, int arenaIndex, size_t gcInfoIndex, const char* typeName) { ASSERT(state->isAllocationAllowed()); ASSERT(arenaIndex != BlinkGC::LargeObjectArenaIndex); NormalPageArena* arena = static_cast<NormalPageArena*>(state->arena(arenaIndex)); - return arena->allocateObject(allocationSizeFromSize(size), gcInfoIndex); + Address address = arena->allocateObject(allocationSizeFromSize(size), gcInfoIndex); + HeapAllocHooks::allocationHookIfEnabled(address, size, typeName); + return address; } template<typename T> Address Heap::allocate(size_t size, bool eagerlySweep) { ThreadState* state = ThreadStateFor<ThreadingTrait<T>::Affinity>::state(); - Address address = Heap::allocateOnArenaIndex(state, size, eagerlySweep ? BlinkGC::EagerSweepArenaIndex : Heap::arenaIndexForObjectSize(size), GCInfoTrait<T>::index()); const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(T); - HeapAllocHooks::allocationHookIfEnabled(address, size, typeName); - return address; + return Heap::allocateOnArenaIndex(state, size, eagerlySweep ? BlinkGC::EagerSweepArenaIndex : Heap::arenaIndexForObjectSize(size), GCInfoTrait<T>::index(), typeName); } template<typename T> @@ -528,13 +517,13 @@ // TODO(haraken): We don't support reallocate() for finalizable objects. ASSERT(!Heap::gcInfo(previousHeader->gcInfoIndex())->hasFinalizer()); ASSERT(previousHeader->gcInfoIndex() == GCInfoTrait<T>::index()); - Address address = Heap::allocateOnArenaIndex(state, size, arenaIndex, GCInfoTrait<T>::index()); + const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(T); + HeapAllocHooks::freeHookIfEnabled(static_cast<Address>(previous)); + Address address = Heap::allocateOnArenaIndex(state, size, arenaIndex, GCInfoTrait<T>::index(), typeName); size_t copySize = previousHeader->payloadSize(); if (copySize > size) copySize = size; memcpy(address, previous, copySize); - const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(T); - HeapAllocHooks::reallocHookIfEnabled(static_cast<Address>(previous), address, size, typeName); return address; }
diff --git a/third_party/WebKit/Source/platform/heap/HeapAllocator.h b/third_party/WebKit/Source/platform/heap/HeapAllocator.h index d466aff..7b2cdf1 100644 --- a/third_party/WebKit/Source/platform/heap/HeapAllocator.h +++ b/third_party/WebKit/Source/platform/heap/HeapAllocator.h
@@ -9,7 +9,6 @@ #include "platform/heap/TraceTraits.h" #include "wtf/Allocator.h" #include "wtf/Assertions.h" -#include "wtf/Atomics.h" #include "wtf/Deque.h" #include "wtf/HashCountedSet.h" #include "wtf/HashMap.h" @@ -62,7 +61,10 @@ { size_t gcInfoIndex = GCInfoTrait<HeapVectorBacking<T, VectorTraits<T>>>::index(); ThreadState* state = ThreadStateFor<ThreadingTrait<T>::Affinity>::state(); - return reinterpret_cast<T*>(Heap::allocateOnArenaIndex(state, size, BlinkGC::InlineVectorArenaIndex, gcInfoIndex)); +#define COMMA , + const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(HeapVectorBacking<T COMMA VectorTraits<T>>); +#undef COMMA + return reinterpret_cast<T*>(Heap::allocateOnArenaIndex(state, size, BlinkGC::InlineVectorArenaIndex, gcInfoIndex, typeName)); } static void freeInlineVectorBacking(void*); static bool expandInlineVectorBacking(void*, size_t); @@ -73,7 +75,8 @@ { size_t gcInfoIndex = GCInfoTrait<HeapHashTableBacking<HashTable>>::index(); ThreadState* state = ThreadStateFor<ThreadingTrait<T>::Affinity>::state(); - return reinterpret_cast<T*>(Heap::allocateOnArenaIndex(state, size, BlinkGC::HashTableArenaIndex, gcInfoIndex)); + const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(HeapHashTableBacking<HashTable>); + return reinterpret_cast<T*>(Heap::allocateOnArenaIndex(state, size, BlinkGC::HashTableArenaIndex, gcInfoIndex, typeName)); } template <typename T, typename HashTable> static T* allocateZeroedHashTableBacking(size_t size)
diff --git a/third_party/WebKit/Source/platform/heap/HeapPage.h b/third_party/WebKit/Source/platform/heap/HeapPage.h index f1c9218..77ff6fb 100644 --- a/third_party/WebKit/Source/platform/heap/HeapPage.h +++ b/third_party/WebKit/Source/platform/heap/HeapPage.h
@@ -39,7 +39,6 @@ #include "wtf/AddressSanitizer.h" #include "wtf/Allocator.h" #include "wtf/Assertions.h" -#include "wtf/Atomics.h" #include "wtf/ContainerAnnotations.h" #include "wtf/Forward.h" #include "wtf/PageAllocator.h"
diff --git a/third_party/WebKit/Source/platform/heap/HeapTest.cpp b/third_party/WebKit/Source/platform/heap/HeapTest.cpp index 19f363b..c676566 100644 --- a/third_party/WebKit/Source/platform/heap/HeapTest.cpp +++ b/third_party/WebKit/Source/platform/heap/HeapTest.cpp
@@ -775,7 +775,8 @@ void* operator new(size_t size) { ThreadState* state = ThreadState::current(); - return Heap::allocateOnArenaIndex(state, size, BlinkGC::NodeArenaIndex, GCInfoTrait<IntNode>::index()); + const char* typeName = WTF_HEAP_PROFILER_TYPE_NAME(IntNode); + return Heap::allocateOnArenaIndex(state, size, BlinkGC::NodeArenaIndex, GCInfoTrait<IntNode>::index(), typeName); } static IntNode* create(int i) @@ -5879,7 +5880,8 @@ AllocatesOnAssignment(const AllocatesOnAssignment& other) { - conservativelyCollectGarbage(); + if (!ThreadState::current()->isGCForbidden()) + conservativelyCollectGarbage(); m_value = new IntWrapper(other.m_value->value()); }
diff --git a/third_party/WebKit/Source/platform/heap/ThreadState.cpp b/third_party/WebKit/Source/platform/heap/ThreadState.cpp index e862423..7567dff 100644 --- a/third_party/WebKit/Source/platform/heap/ThreadState.cpp +++ b/third_party/WebKit/Source/platform/heap/ThreadState.cpp
@@ -498,7 +498,7 @@ if (isMainThread()) { double timeForThreadLocalWeakProcessing = WTF::currentTimeMS() - startTime; - DEFINE_STATIC_LOCAL(CustomCountHistogram, timeForWeakHistogram, ("BlinkGC.timeForThreadLocalWeakProcessing", 1, 10 * 1000, 50)); + DEFINE_STATIC_LOCAL(CustomCountHistogram, timeForWeakHistogram, ("BlinkGC.TimeForThreadLocalWeakProcessing", 1, 10 * 1000, 50)); timeForWeakHistogram.count(timeForThreadLocalWeakProcessing); } }
diff --git a/third_party/WebKit/Source/platform/heap/TraceTraits.h b/third_party/WebKit/Source/platform/heap/TraceTraits.h index 3269ae0a..cd672c4 100644 --- a/third_party/WebKit/Source/platform/heap/TraceTraits.h +++ b/third_party/WebKit/Source/platform/heap/TraceTraits.h
@@ -8,6 +8,7 @@ #include "platform/heap/GCInfo.h" #include "platform/heap/Heap.h" #include "platform/heap/InlinedGlobalMarkingVisitor.h" +#include "platform/heap/StackFrameDepth.h" #include "platform/heap/Visitor.h" #include "wtf/Allocator.h" #include "wtf/Assertions.h"
diff --git a/third_party/WebKit/Source/platform/heap/Visitor.h b/third_party/WebKit/Source/platform/heap/Visitor.h index 5f6a367..a683882c 100644 --- a/third_party/WebKit/Source/platform/heap/Visitor.h +++ b/third_party/WebKit/Source/platform/heap/Visitor.h
@@ -33,14 +33,10 @@ #include "platform/PlatformExport.h" #include "platform/heap/GarbageCollected.h" -#include "platform/heap/StackFrameDepth.h" -#include "platform/heap/ThreadState.h" #include "wtf/Allocator.h" #include "wtf/Assertions.h" -#include "wtf/Atomics.h" #include "wtf/Deque.h" #include "wtf/Forward.h" -#include "wtf/HashMap.h" #include "wtf/HashTraits.h" #include "wtf/TypeTraits.h" @@ -385,7 +381,6 @@ ThreadState* m_state; const MarkingMode m_markingMode; - bool m_isGlobalMarkingVisitor; }; } // namespace blink
diff --git a/third_party/WebKit/Source/platform/inspector_protocol/CollectionsSTL.h b/third_party/WebKit/Source/platform/inspector_protocol/CollectionsSTL.h new file mode 100644 index 0000000..4d4ea56 --- /dev/null +++ b/third_party/WebKit/Source/platform/inspector_protocol/CollectionsSTL.h
@@ -0,0 +1,223 @@ +// 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 CollectionsSTL_h +#define CollectionsSTL_h + +#include "wtf/Allocator.h" +#include "wtf/HashMap.h" +#include "wtf/PassOwnPtr.h" +#include "wtf/text/StringHash.h" + +#include <algorithm> +#include <unordered_map> +#include <vector> + +namespace std { +template<> +struct hash<String> { + std::size_t operator()(const String& k) const { return StringHash::hash(k); } +}; +} + +namespace blink { +namespace protocol { + +template <typename T> +class Vector { +public: + Vector() { } + Vector(size_t capacity) : m_impl(capacity) { } + typedef typename std::vector<T>::iterator iterator; + typedef typename std::vector<T>::const_iterator const_iterator; + + iterator begin() { return m_impl.begin(); } + iterator end() { return m_impl.end(); } + const_iterator begin() const { return m_impl.begin(); } + const_iterator end() const { return m_impl.end(); } + + void resize(size_t s) { m_impl.resize(s); } + size_t size() const { return m_impl.size(); } + bool isEmpty() const { return !m_impl.size(); } + T& operator[](size_t i) { return at(i); } + const T& operator[](size_t i) const { return at(i); } + T& at(size_t i) { return m_impl[i]; } + const T& at(size_t i) const { return m_impl.at(i); } + T& last() { return m_impl[m_impl.size() - 1]; } + const T& last() const { return m_impl[m_impl.size() - 1]; } + void append(const T& t) { m_impl.push_back(t); } + void prepend(const T& t) { m_impl.insert(m_impl.begin(), t); } + void remove(size_t i) { m_impl.erase(m_impl.begin() + i); } + void clear() { m_impl.clear(); } + void swap(Vector& other) { m_impl.swap(other.m_impl); } + void removeLast() { m_impl.pop_back(); } + +private: + std::vector<T> m_impl; +}; + +template <typename T> +class Vector<OwnPtr<T>> { + WTF_MAKE_NONCOPYABLE(Vector); +public: + Vector() { } + Vector(size_t capacity) : m_impl(capacity) { } + ~Vector() { } + + typedef typename std::vector<OwnPtr<T>>::iterator iterator; + typedef typename std::vector<OwnPtr<T>>::const_iterator const_iterator; + + iterator begin() { return m_impl.begin(); } + iterator end() { return m_impl.end(); } + const_iterator begin() const { return m_impl.begin(); } + const_iterator end() const { return m_impl.end(); } + + void resize(size_t s) { m_impl.resize(s); } + size_t size() const { return m_impl.size(); } + bool isEmpty() const { return !m_impl.size(); } + OwnPtr<T>& operator[](size_t i) { return at(i); } + const OwnPtr<T>& operator[](size_t i) const { return at(i); } + OwnPtr<T>& at(size_t i) { return m_impl[i]; } + const OwnPtr<T>& at(size_t i) const { return m_impl.at(i); } + OwnPtr<T>& last() { return m_impl[m_impl.size() - 1]; } + const OwnPtr<T>& last() const { return m_impl[m_impl.size() - 1]; } + void append(const PassOwnPtr<T>& t) { m_impl.push_back(t); } + void prepend(const PassOwnPtr<T>& t) { m_impl.insert(m_impl.begin(), t); } + void remove(size_t i) { m_impl.erase(m_impl.begin() + i); } + void clear() { m_impl.clear(); } + void swap(Vector& other) { m_impl.swap(other.m_impl); } + void removeLast() { m_impl.pop_back(); } + +private: + std::vector<OwnPtr<T>> m_impl; +}; + +template <typename K, typename V, typename I> +class HashMapIterator { + STACK_ALLOCATED(); +public: + HashMapIterator(const I& impl) : m_impl(impl) { } + std::pair<K, V*>* get() const { m_pair.first = m_impl->first; m_pair.second = &m_impl->second; return &m_pair; } + std::pair<K, V*>& operator*() const { return *get(); } + std::pair<K, V*>* operator->() const { return get(); } + + bool operator==(const HashMapIterator<K, V, I>& other) const { return m_impl == other.m_impl; } + bool operator!=(const HashMapIterator<K, V, I>& other) const { return m_impl != other.m_impl; } + + HashMapIterator<K, V, I>& operator++() { ++m_impl; return *this; } + +private: + mutable std::pair<K, V*> m_pair; + I m_impl; +}; + +template <typename K, typename V, typename I> +class HashMapIterator<K, OwnPtr<V>, I> { + STACK_ALLOCATED(); +public: + HashMapIterator(const I& impl) : m_impl(impl) { } + std::pair<K, V*>* get() const { m_pair.first = m_impl->first; m_pair.second = m_impl->second.get(); return &m_pair; } + std::pair<K, V*>& operator*() const { return *get(); } + std::pair<K, V*>* operator->() const { return get(); } + + bool operator==(const HashMapIterator<K, OwnPtr<V>, I>& other) const { return m_impl == other.m_impl; } + bool operator!=(const HashMapIterator<K, OwnPtr<V>, I>& other) const { return m_impl != other.m_impl; } + + HashMapIterator<K, OwnPtr<V>, I>& operator++() { ++m_impl; return *this; } + +private: + mutable std::pair<K, V*> m_pair; + I m_impl; +}; + +template <typename K, typename V> +class HashMap { +public: + HashMap() { } + ~HashMap() { } + + using iterator = HashMapIterator<K, V, typename std::unordered_map<K, V>::iterator>; + using const_iterator = HashMapIterator<K, const V, typename std::unordered_map<K, V>::const_iterator>; + + iterator begin() { return iterator(m_impl.begin()); } + iterator end() { return iterator(m_impl.end()); } + iterator find(const K& k) { return iterator(m_impl.find(k)); } + const_iterator begin() const { return const_iterator(m_impl.begin()); } + const_iterator end() const { return const_iterator(m_impl.end()); } + const_iterator find(const K& k) const { return const_iterator(m_impl.find(k)); } + + size_t size() const { return m_impl.size(); } + bool isEmpty() const { return !m_impl.size(); } + bool set(const K& k, const V& v) + { + bool isNew = m_impl.find(k) == m_impl.end(); + m_impl[k] = v; + return isNew; + } + bool contains(const K& k) const { return m_impl.find(k) != m_impl.end(); } + V get(const K& k) const { return m_impl.find(k)->second; } + void remove(const K& k) { m_impl.erase(k); } + void clear() { m_impl.clear(); } + V take(const K& k) + { + V result = m_impl[k]; + m_impl.erase(k); + return result; + } + +private: + std::unordered_map<K, V> m_impl; +}; + +template <typename K, typename V> +class HashMap<K, OwnPtr<V>> { +public: + HashMap() { } + ~HashMap() { } + + using iterator = HashMapIterator<K, OwnPtr<V>, typename std::unordered_map<K, OwnPtr<V>>::iterator>; + using const_iterator = HashMapIterator<K, OwnPtr<V>, typename std::unordered_map<K, OwnPtr<V>>::const_iterator>; + + iterator begin() { return iterator(m_impl.begin()); } + iterator end() { return iterator(m_impl.end()); } + iterator find(const K& k) { return iterator(m_impl.find(k)); } + const_iterator begin() const { return const_iterator(m_impl.begin()); } + const_iterator end() const { return const_iterator(m_impl.end()); } + const_iterator find(const K& k) const { return const_iterator(m_impl.find(k)); } + + size_t size() const { return m_impl.size(); } + bool isEmpty() const { return !m_impl.size(); } + bool set(const K& k, PassOwnPtr<V> v) + { + bool isNew = m_impl.find(k) == m_impl.end(); + m_impl[k] = v; + return isNew; + } + bool contains(const K& k) const { return m_impl.find(k) != m_impl.end(); } + V* get(const K& k) const { return m_impl.find(k)->second.get(); } + PassOwnPtr<V> take(const K& k) + { + if (!contains(k)) + return nullptr; + OwnPtr<V> result = std::move(m_impl[k]); + m_impl.erase(k); + return result.release(); + } + void remove(const K& k) { m_impl.erase(k); } + void clear() { m_impl.clear(); } + +private: + std::unordered_map<K, OwnPtr<V>> m_impl; +}; + +template <typename K> +class HashSet : public protocol::HashMap<K, K> { +public: + void add(const K& k) { this->set(k, k); } +}; + +} // namespace platform +} // namespace blink + +#endif // !defined(CollectionsSTL_h)
diff --git a/third_party/WebKit/Source/platform/inspector_protocol/CollectionsWTF.h b/third_party/WebKit/Source/platform/inspector_protocol/CollectionsWTF.h index 79ebe3a6..47986cc 100644 --- a/third_party/WebKit/Source/platform/inspector_protocol/CollectionsWTF.h +++ b/third_party/WebKit/Source/platform/inspector_protocol/CollectionsWTF.h
@@ -28,7 +28,6 @@ const_iterator end() const { return m_impl.end(); } void resize(size_t s) { m_impl.resize(s); } - size_t find(const T& t) const { return m_impl.find(t); } size_t size() const { return m_impl.size(); } bool isEmpty() const { return m_impl.isEmpty(); } T& operator[](size_t i) { return at(i); } @@ -40,7 +39,6 @@ void append(const T& t) { m_impl.append(t); } void prepend(const T& t) { m_impl.prepend(t); } void remove(size_t i) { m_impl.remove(i); } - void insert(size_t i, const T& t) { m_impl.insert(i, t); } void clear() { m_impl.clear(); } void swap(Vector& other) { m_impl.swap(other.m_impl); } void removeLast() { m_impl.removeLast(); } @@ -66,7 +64,6 @@ const_iterator end() const { return m_impl.end(); } void resize(size_t s) { m_impl.resize(s); } - size_t find(const T* t) const { return m_impl.find(t); } size_t size() const { return m_impl.size(); } bool isEmpty() const { return m_impl.isEmpty(); } OwnPtr<T>& operator[](size_t i) { return m_impl.at(i); } @@ -78,7 +75,6 @@ void append(PassOwnPtr<T> t) { m_impl.append(t); } void prepend(PassOwnPtr<T> t) { m_impl.prepend(t); } void remove(size_t i) { m_impl.remove(i); } - void insert(size_t i, PassOwnPtr<T> t) { m_impl.insert(i, t); } void clear() { m_impl.clear(); } void swap(Vector& other) { m_impl.swap(other.m_impl); } void removeLast() { m_impl.removeLast(); } @@ -134,12 +130,12 @@ using iterator = HashMapIterator<K, V, typename WTF::HashMap<K, V>::iterator>; using const_iterator = HashMapIterator<K, const V, typename WTF::HashMap<K, V>::const_iterator>; - iterator begin() { return HashMapIterator<K, V, typename WTF::HashMap<K, V>::iterator>(m_impl.begin()); } - iterator end() { return HashMapIterator<K, V, typename WTF::HashMap<K, V>::iterator>(m_impl.end()); } - iterator find(const K& k) { return HashMapIterator<K, V, typename WTF::HashMap<K, V>::iterator>(m_impl.find(k)); } - const_iterator begin() const { return HashMapIterator<K, const V, typename WTF::HashMap<K, V>::const_iterator>(m_impl.begin()); } - const_iterator end() const { return HashMapIterator<K, const V, typename WTF::HashMap<K, V>::const_iterator>(m_impl.end()); } - const_iterator find(const K& k) const { return HashMapIterator<K, const V, typename WTF::HashMap<K, V>::const_iterator>(m_impl.find(k)); } + iterator begin() { return iterator(m_impl.begin()); } + iterator end() { return iterator(m_impl.end()); } + iterator find(const K& k) { return iterator(m_impl.find(k)); } + const_iterator begin() const { return const_iterator(m_impl.begin()); } + const_iterator end() const { return const_iterator(m_impl.end()); } + const_iterator find(const K& k) const { return const_iterator(m_impl.find(k)); } size_t size() const { return m_impl.size(); } bool isEmpty() const { return m_impl.isEmpty(); } @@ -163,12 +159,12 @@ using iterator = HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::iterator>; using const_iterator = HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::const_iterator>; - iterator begin() { return HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::iterator>(m_impl.begin()); } - iterator end() { return HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::iterator>(m_impl.end()); } - iterator find(const K& k) { return HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::iterator>(m_impl.find(k)); } - const_iterator begin() const { return HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::const_iterator>(m_impl.begin()); } - const_iterator end() const { return HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::const_iterator>(m_impl.end()); } - const_iterator find(const K& k) const { return HashMapIterator<K, OwnPtr<V>, typename WTF::HashMap<K, OwnPtr<V>>::const_iterator>(m_impl.find(k)); } + iterator begin() { return iterator(m_impl.begin()); } + iterator end() { return iterator(m_impl.end()); } + iterator find(const K& k) { return iterator(m_impl.find(k)); } + const_iterator begin() const { return const_iterator(m_impl.begin()); } + const_iterator end() const { return const_iterator(m_impl.end()); } + const_iterator find(const K& k) const { return const_iterator(m_impl.find(k)); } size_t size() const { return m_impl.size(); } bool isEmpty() const { return m_impl.isEmpty(); }
diff --git a/third_party/WebKit/Source/platform/inspector_protocol/Dispatcher_cpp.template b/third_party/WebKit/Source/platform/inspector_protocol/Dispatcher_cpp.template index c255e06..f475712 100644 --- a/third_party/WebKit/Source/platform/inspector_protocol/Dispatcher_cpp.template +++ b/third_party/WebKit/Source/platform/inspector_protocol/Dispatcher_cpp.template
@@ -44,12 +44,13 @@ {% endfor %} // Initialize common errors. - m_commonErrors.insert(ParseError, -32700); - m_commonErrors.insert(InvalidRequest, -32600); - m_commonErrors.insert(MethodNotFound, -32601); - m_commonErrors.insert(InvalidParams, -32602); - m_commonErrors.insert(InternalError, -32603); - m_commonErrors.insert(ServerError, -32000); + m_commonErrors.resize(LastEntry); + m_commonErrors[ParseError] = -32700; + m_commonErrors[InvalidRequest] = -32600; + m_commonErrors[MethodNotFound] = -32601; + m_commonErrors[InvalidParams] = -32602; + m_commonErrors[InternalError] = -32603; + m_commonErrors[ServerError] = -32000; } ~DispatcherImpl() { clearFrontend(); }
diff --git a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h index 02e29c72..4eb2b8c 100644 --- a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h +++ b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.h
@@ -67,8 +67,6 @@ void setVisibleScrollerThumbRect(const IntRect&); - static bool canUseCoordinatedScrollbar(); - DEFINE_INLINE_VIRTUAL_TRACE() { ScrollAnimatorBase::trace(visitor);
diff --git a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm index 601be84..a711f32 100644 --- a/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm +++ b/third_party/WebKit/Source/platform/mac/ScrollAnimatorMac.mm
@@ -35,8 +35,7 @@ #include "platform/mac/NSScrollerImpDetails.h" #include "platform/scroll/ScrollableArea.h" #include "platform/scroll/ScrollbarTheme.h" -#include "platform/scroll/ScrollbarThemeMacCommon.h" -#include "platform/scroll/ScrollbarThemeMacOverlayAPI.h" +#include "platform/scroll/ScrollbarThemeMac.h" #include "public/platform/Platform.h" #include "public/platform/WebScheduler.h" #include "wtf/MainThread.h" @@ -64,16 +63,15 @@ return globalSupportsContentAreaScrolledInDirection; } -static ScrollbarThemeMacOverlayAPI* macOverlayScrollbarTheme() +static ScrollbarThemeMac* macOverlayScrollbarTheme() { - RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(ScrollbarThemeMacCommon::isOverlayAPIAvailable()); ScrollbarTheme& scrollbarTheme = ScrollbarTheme::theme(); - return !scrollbarTheme.isMockTheme() ? static_cast<ScrollbarThemeMacOverlayAPI*>(&scrollbarTheme) : nil; + return !scrollbarTheme.isMockTheme() ? static_cast<ScrollbarThemeMac*>(&scrollbarTheme) : nil; } static ScrollbarPainter scrollbarPainterForScrollbar(Scrollbar& scrollbar) { - if (ScrollbarThemeMacOverlayAPI* scrollbarTheme = macOverlayScrollbarTheme()) + if (ScrollbarThemeMac* scrollbarTheme = macOverlayScrollbarTheme()) return scrollbarTheme->painterForScrollbar(scrollbar); return nil; @@ -699,12 +697,10 @@ m_scrollAnimationHelperDelegate.adoptNS([[BlinkScrollAnimationHelperDelegate alloc] initWithScrollAnimator:this]); m_scrollAnimationHelper.adoptNS([[NSClassFromString(@"NSScrollAnimationHelper") alloc] initWithDelegate:m_scrollAnimationHelperDelegate.get()]); - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - m_scrollbarPainterControllerDelegate.adoptNS([[BlinkScrollbarPainterControllerDelegate alloc] initWithScrollableArea:scrollableArea]); - m_scrollbarPainterController = [[[NSClassFromString(@"NSScrollerImpPair") alloc] init] autorelease]; - [m_scrollbarPainterController.get() performSelector:@selector(setDelegate:) withObject:m_scrollbarPainterControllerDelegate.get()]; - [m_scrollbarPainterController.get() setScrollerStyle:ScrollbarThemeMacCommon::recommendedScrollerStyle()]; - } + m_scrollbarPainterControllerDelegate.adoptNS([[BlinkScrollbarPainterControllerDelegate alloc] initWithScrollableArea:scrollableArea]); + m_scrollbarPainterController = [[[NSClassFromString(@"NSScrollerImpPair") alloc] init] autorelease]; + [m_scrollbarPainterController.get() performSelector:@selector(setDelegate:) withObject:m_scrollbarPainterControllerDelegate.get()]; + [m_scrollbarPainterController.get() setScrollerStyle:ScrollbarThemeMac::recommendedScrollerStyle()]; } ScrollAnimatorMac::~ScrollAnimatorMac() @@ -716,15 +712,14 @@ void ScrollAnimatorMac::dispose() { - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - BEGIN_BLOCK_OBJC_EXCEPTIONS; - [m_scrollbarPainterControllerDelegate.get() invalidate]; - [m_scrollbarPainterController.get() setDelegate:nil]; - [m_horizontalScrollbarPainterDelegate.get() invalidate]; - [m_verticalScrollbarPainterDelegate.get() invalidate]; - [m_scrollAnimationHelperDelegate.get() invalidate]; - END_BLOCK_OBJC_EXCEPTIONS; - } + BEGIN_BLOCK_OBJC_EXCEPTIONS; + [m_scrollbarPainterControllerDelegate.get() invalidate]; + [m_scrollbarPainterController.get() setDelegate:nil]; + [m_horizontalScrollbarPainterDelegate.get() invalidate]; + [m_verticalScrollbarPainterDelegate.get() invalidate]; + [m_scrollAnimationHelperDelegate.get() invalidate]; + END_BLOCK_OBJC_EXCEPTIONS; + m_initialScrollbarPaintTaskFactory->cancel(); m_sendContentAreaScrolledTaskFactory->cancel(); } @@ -807,32 +802,28 @@ { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() contentAreaWillDraw]; + [m_scrollbarPainterController.get() contentAreaWillDraw]; } void ScrollAnimatorMac::mouseEnteredContentArea() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() mouseEnteredContentArea]; + [m_scrollbarPainterController.get() mouseEnteredContentArea]; } void ScrollAnimatorMac::mouseExitedContentArea() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() mouseExitedContentArea]; + [m_scrollbarPainterController.get() mouseExitedContentArea]; } void ScrollAnimatorMac::mouseMovedInContentArea() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() mouseMovedInContentArea]; + [m_scrollbarPainterController.get() mouseMovedInContentArea]; } void ScrollAnimatorMac::mouseEnteredScrollbar(Scrollbar& scrollbar) const @@ -840,12 +831,10 @@ if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - if (!supportsUIStateTransitionProgress()) - return; - if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar)) - [painter mouseEnteredScroller]; - } + if (!supportsUIStateTransitionProgress()) + return; + if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar)) + [painter mouseEnteredScroller]; } void ScrollAnimatorMac::mouseExitedScrollbar(Scrollbar& scrollbar) const @@ -853,93 +842,76 @@ if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - if (!supportsUIStateTransitionProgress()) - return; - if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar)) - [painter mouseExitedScroller]; - } + if (!supportsUIStateTransitionProgress()) + return; + if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar)) + [painter mouseExitedScroller]; } void ScrollAnimatorMac::willStartLiveResize() { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() startLiveResize]; + [m_scrollbarPainterController.get() startLiveResize]; } void ScrollAnimatorMac::contentsResized() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() contentAreaDidResize]; + [m_scrollbarPainterController.get() contentAreaDidResize]; } void ScrollAnimatorMac::willEndLiveResize() { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() endLiveResize]; + [m_scrollbarPainterController.get() endLiveResize]; } void ScrollAnimatorMac::contentAreaDidShow() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() windowOrderedIn]; + [m_scrollbarPainterController.get() windowOrderedIn]; } void ScrollAnimatorMac::contentAreaDidHide() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() windowOrderedOut]; + [m_scrollbarPainterController.get() windowOrderedOut]; } void ScrollAnimatorMac::didBeginScrollGesture() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() beginScrollGesture]; + [m_scrollbarPainterController.get() beginScrollGesture]; } void ScrollAnimatorMac::didEndScrollGesture() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - [m_scrollbarPainterController.get() endScrollGesture]; + [m_scrollbarPainterController.get() endScrollGesture]; } void ScrollAnimatorMac::mayBeginScrollGesture() const { if (!scrollableArea()->scrollbarsCanBeActive()) return; - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - [m_scrollbarPainterController.get() beginScrollGesture]; [m_scrollbarPainterController.get() contentAreaScrolled]; } void ScrollAnimatorMac::finishCurrentScrollAnimations() { - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - [m_scrollbarPainterController.get() hideOverlayScrollers]; - } + [m_scrollbarPainterController.get() hideOverlayScrollers]; } void ScrollAnimatorMac::didAddVerticalScrollbar(Scrollbar& scrollbar) { - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar); if (!painter) return; @@ -955,9 +927,6 @@ void ScrollAnimatorMac::willRemoveVerticalScrollbar(Scrollbar& scrollbar) { - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar); if (!painter) return; @@ -972,9 +941,6 @@ void ScrollAnimatorMac::didAddHorizontalScrollbar(Scrollbar& scrollbar) { - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar); if (!painter) return; @@ -990,9 +956,6 @@ void ScrollAnimatorMac::willRemoveHorizontalScrollbar(Scrollbar& scrollbar) { - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar); if (!painter) return; @@ -1008,10 +971,7 @@ bool ScrollAnimatorMac::shouldScrollbarParticipateInHitTesting(Scrollbar& scrollbar) { // Non-overlay scrollbars should always participate in hit testing. - if (ScrollbarThemeMacCommon::recommendedScrollerStyle() != NSScrollerStyleOverlay) - return true; - - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) + if (ScrollbarThemeMac::recommendedScrollerStyle() != NSScrollerStyleOverlay) return true; // Overlay scrollbars should participate in hit testing whenever they are at all visible. @@ -1023,9 +983,6 @@ void ScrollAnimatorMac::notifyContentAreaScrolled(const FloatSize& delta) { - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - // This function is called when a page is going into the page cache, but the page // isn't really scrolling in that case. We should only pass the message on to the // ScrollbarPainterController when we're really scrolling on an active page. @@ -1035,17 +992,14 @@ bool ScrollAnimatorMac::setScrollbarsVisibleForTesting(bool show) { - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - if (show) - [m_scrollbarPainterController.get() flashScrollers]; - else - [m_scrollbarPainterController.get() hideOverlayScrollers]; + if (show) + [m_scrollbarPainterController.get() flashScrollers]; + else + [m_scrollbarPainterController.get() hideOverlayScrollers]; - [m_verticalScrollbarPainterDelegate.get() updateVisibilityImmediately:show]; - [m_verticalScrollbarPainterDelegate.get() updateVisibilityImmediately:show]; - return true; - } - return false; + [m_verticalScrollbarPainterDelegate.get() updateVisibilityImmediately:show]; + [m_verticalScrollbarPainterDelegate.get() updateVisibilityImmediately:show]; + return true; } void ScrollAnimatorMac::cancelAnimation() @@ -1070,15 +1024,12 @@ void ScrollAnimatorMac::updateScrollerStyle() { - if (!ScrollbarThemeMacCommon::isOverlayAPIAvailable()) - return; - if (!scrollableArea()->scrollbarsCanBeActive()) { m_needsScrollerStyleUpdate = true; return; } - ScrollbarThemeMacOverlayAPI* macTheme = macOverlayScrollbarTheme(); + ScrollbarThemeMac* macTheme = macOverlayScrollbarTheme(); if (!macTheme) { m_needsScrollerStyleUpdate = false; return; @@ -1147,12 +1098,10 @@ void ScrollAnimatorMac::initialScrollbarPaintTask() { - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - // To force the scrollbars to flash, we have to call hide first. Otherwise, the ScrollbarPainterController - // might think that the scrollbars are already showing and bail early. - [m_scrollbarPainterController.get() hideOverlayScrollers]; - [m_scrollbarPainterController.get() flashScrollers]; - } + // To force the scrollbars to flash, we have to call hide first. Otherwise, the ScrollbarPainterController + // might think that the scrollbars are already showing and bail early. + [m_scrollbarPainterController.get() hideOverlayScrollers]; + [m_scrollbarPainterController.get() flashScrollers]; } void ScrollAnimatorMac::sendContentAreaScrolledSoon(const FloatSize& delta) @@ -1184,8 +1133,4 @@ m_visibleScrollerThumbRect = rectInViewCoordinates; } -bool ScrollAnimatorMac::canUseCoordinatedScrollbar() { - return ScrollbarThemeMacCommon::isOverlayAPIAvailable(); -} - } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacCommon.h b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMac.h similarity index 60% rename from third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacCommon.h rename to third_party/WebKit/Source/platform/scroll/ScrollbarThemeMac.h index 84ce2cb..8090fcb1a 100644 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacCommon.h +++ b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMac.h
@@ -23,21 +23,23 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef ScrollbarThemeMacCommon_h -#define ScrollbarThemeMacCommon_h +#ifndef ScrollbarThemeMac_h +#define ScrollbarThemeMac_h #include "platform/mac/NSScrollerImpDetails.h" #include "platform/scroll/ScrollbarTheme.h" +typedef id ScrollbarPainter; + class SkCanvas; namespace blink { class Pattern; -class PLATFORM_EXPORT ScrollbarThemeMacCommon : public ScrollbarTheme { +class PLATFORM_EXPORT ScrollbarThemeMac : public ScrollbarTheme { public: - ~ScrollbarThemeMacCommon() override; + ~ScrollbarThemeMac() override; void registerScrollbar(ScrollbarThemeClient&) override; void unregisterScrollbar(ScrollbarThemeClient&) override; @@ -50,12 +52,25 @@ void paintTickmarks(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&) override; + bool shouldRepaintAllPartsOnInvalidation() const override { return false; } + ScrollbarPart invalidateOnThumbPositionChange( + const ScrollbarThemeClient&, float oldPosition, float newPosition) const override; + void updateEnabledState(const ScrollbarThemeClient&) override; + int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) override; + bool usesOverlayScrollbars() const override; + void updateScrollbarOverlayStyle(const ScrollbarThemeClient&) override; + WebScrollbarButtonsPlacement buttonsPlacement() const override; + + void setNewPainterForScrollbar(ScrollbarThemeClient&, ScrollbarPainter); + ScrollbarPainter painterForScrollbar(const ScrollbarThemeClient&) const; + + void paintTrackBackground(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&) override; + void paintThumb(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&) override; + + float thumbOpacity(const ScrollbarThemeClient&) const override; + static NSScrollerStyle recommendedScrollerStyle(); - static bool isOverlayAPIAvailable(); - - static bool scrollAnimationEnabledForSystem(); - protected: int maxOverlapBetweenPages() override { return 40; } @@ -66,9 +81,18 @@ void paintGivenTickmarks(SkCanvas*, const ScrollbarThemeClient&, const IntRect&, const Vector<IntRect>&); + IntRect trackRect(const ScrollbarThemeClient&, bool painting = false) override; + IntRect backButtonRect(const ScrollbarThemeClient&, ScrollbarPart, bool painting = false) override; + IntRect forwardButtonRect(const ScrollbarThemeClient&, ScrollbarPart, bool painting = false) override; + + bool hasButtons(const ScrollbarThemeClient&) override { return false; } + bool hasThumb(const ScrollbarThemeClient&) override; + + int minimumThumbLength(const ScrollbarThemeClient&) override; + RefPtr<Pattern> m_overhangPattern; }; } -#endif // ScrollbarThemeMacCommon_h +#endif // ScrollbarThemeMac_h
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMac.mm b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMac.mm new file mode 100644 index 0000000..b20efe3 --- /dev/null +++ b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMac.mm
@@ -0,0 +1,444 @@ +/* + * Copyright (C) 2008, 2011 Apple 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: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "platform/RuntimeEnabledFeatures.h" +#include "platform/scroll/ScrollbarThemeMac.h" + +#include <Carbon/Carbon.h> +#include "platform/PlatformMouseEvent.h" +#include "platform/graphics/GraphicsContext.h" +#include "platform/graphics/GraphicsContextStateSaver.h" +#include "platform/graphics/paint/DrawingRecorder.h" +#include "platform/mac/ColorMac.h" +#include "platform/mac/LocalCurrentGraphicsContext.h" +#include "platform/mac/NSScrollerImpDetails.h" +#include "platform/mac/ScrollAnimatorMac.h" +#include "platform/scroll/ScrollbarThemeClient.h" +#include "public/platform/WebThemeEngine.h" +#include "public/platform/Platform.h" +#include "public/platform/WebRect.h" +#include "skia/ext/skia_utils_mac.h" +#include "wtf/HashSet.h" +#include "wtf/RetainPtr.h" +#include "wtf/StdLibExtras.h" +#include "wtf/TemporaryChange.h" + +// FIXME: There are repainting problems due to Aqua scroll bar buttons' visual overflow. + +using namespace blink; + +@interface NSColor (WebNSColorDetails) ++ (NSImage *)_linenPatternImage; +@end + +@interface BlinkScrollbarObserver : NSObject { + blink::ScrollbarThemeClient* _scrollbar; + RetainPtr<ScrollbarPainter> _scrollbarPainter; + BOOL _visible; +} +- (id)initWithScrollbar:(blink::ScrollbarThemeClient*)scrollbar painter:(ScrollbarPainter)painter; +@end + +@implementation BlinkScrollbarObserver + +- (id)initWithScrollbar:(blink::ScrollbarThemeClient*)scrollbar painter:(ScrollbarPainter)painter +{ + if (!(self = [super init])) + return nil; + _scrollbar = scrollbar; + _scrollbarPainter = painter; + + [_scrollbarPainter.get() addObserver:self forKeyPath:@"knobAlpha" options:0 context:nil]; + return self; +} + +- (id)painter +{ + return _scrollbarPainter.get(); +} + +- (void)dealloc +{ + + [_scrollbarPainter.get() removeObserver:self forKeyPath:@"knobAlpha"]; + [super dealloc]; +} + +- (void)observeValueForKeyPath:(NSString*)keyPath + ofObject:(id)object + change:(NSDictionary*)change + context:(void*)context +{ + if ([keyPath isEqualToString:@"knobAlpha"]) { + BOOL visible = [_scrollbarPainter.get() knobAlpha] > 0; + if (_visible != visible) { + _visible = visible; + _scrollbar->visibilityChanged(); + } + } +} + +@end + +namespace blink { + +typedef HashSet<ScrollbarThemeClient*> ScrollbarSet; + +static ScrollbarSet& scrollbarSet() +{ + DEFINE_STATIC_LOCAL(ScrollbarSet, set, ()); + return set; +} + +static float gInitialButtonDelay = 0.5f; +static float gAutoscrollButtonDelay = 0.05f; +static NSScrollerStyle gPreferredScrollerStyle = NSScrollerStyleLegacy; + +typedef HashMap<ScrollbarThemeClient*, RetainPtr<BlinkScrollbarObserver>> ScrollbarPainterMap; + +static ScrollbarPainterMap& scrollbarPainterMap() +{ + static ScrollbarPainterMap* map = new ScrollbarPainterMap; + return *map; +} + +static bool supportsExpandedScrollbars() +{ + // FIXME: This is temporary until all platforms that support ScrollbarPainter support this part of the API. + static bool globalSupportsExpandedScrollbars = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(setExpanded:)]; + return globalSupportsExpandedScrollbars; +} + +ScrollbarTheme& ScrollbarTheme::nativeTheme() +{ + DEFINE_STATIC_LOCAL(ScrollbarThemeMac, overlayTheme, ()); + return overlayTheme; +} + +void ScrollbarThemeMac::paintGivenTickmarks(SkCanvas* canvas, const ScrollbarThemeClient& scrollbar, const IntRect& rect, const Vector<IntRect>& tickmarks) +{ + if (scrollbar.orientation() != VerticalScrollbar) + return; + + if (rect.height() <= 0 || rect.width() <= 0) + return; // nothing to draw on. + + if (!tickmarks.size()) + return; + + SkAutoCanvasRestore stateSaver(canvas, true); + + SkPaint strokePaint; + strokePaint.setAntiAlias(false); + strokePaint.setColor(SkColorSetRGB(0xCC, 0xAA, 0x00)); + strokePaint.setStyle(SkPaint::kStroke_Style); + + SkPaint fillPaint; + fillPaint.setAntiAlias(false); + fillPaint.setColor(SkColorSetRGB(0xFF, 0xDD, 0x00)); + fillPaint.setStyle(SkPaint::kFill_Style); + + for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) { + // Calculate how far down (in %) the tick-mark should appear. + const float percent = static_cast<float>(i->y()) / scrollbar.totalSize(); + if (percent < 0.0 || percent > 1.0) + continue; + + // Calculate how far down (in pixels) the tick-mark should appear. + const int yPos = rect.y() + (rect.height() * percent); + + // Paint. + FloatRect tickRect(rect.x(), yPos, rect.width(), 2); + canvas->drawRect(tickRect, fillPaint); + canvas->drawRect(tickRect, strokePaint); + } +} + +void ScrollbarThemeMac::paintTickmarks(GraphicsContext& context, const ScrollbarThemeClient& scrollbar, const IntRect& rect) +{ + // Note: This is only used for css-styled scrollbars on mac. + if (scrollbar.orientation() != VerticalScrollbar) + return; + + if (rect.height() <= 0 || rect.width() <= 0) + return; + + Vector<IntRect> tickmarks; + scrollbar.getTickmarks(tickmarks); + if (!tickmarks.size()) + return; + + if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, DisplayItem::ScrollbarTickmarks)) + return; + + DrawingRecorder recorder(context, scrollbar, DisplayItem::ScrollbarTickmarks, rect); + + // Inset a bit. + IntRect tickmarkTrackRect = rect; + tickmarkTrackRect.setX(tickmarkTrackRect.x() + 1); + tickmarkTrackRect.setWidth(tickmarkTrackRect.width() - 2); + paintGivenTickmarks(context.canvas(), scrollbar, tickmarkTrackRect, tickmarks); +} + +ScrollbarThemeMac::~ScrollbarThemeMac() +{ +} + +void ScrollbarThemeMac::preferencesChanged(float initialButtonDelay, float autoscrollButtonDelay, NSScrollerStyle preferredScrollerStyle, bool redraw, WebScrollbarButtonsPlacement buttonPlacement) +{ + updateButtonPlacement(buttonPlacement); + gInitialButtonDelay = initialButtonDelay; + gAutoscrollButtonDelay = autoscrollButtonDelay; + bool sendScrollerStyleNotification = gPreferredScrollerStyle != preferredScrollerStyle; + gPreferredScrollerStyle = preferredScrollerStyle; + if (redraw && !scrollbarSet().isEmpty()) { + ScrollbarSet::iterator end = scrollbarSet().end(); + for (ScrollbarSet::iterator it = scrollbarSet().begin(); it != end; ++it) { + (*it)->styleChanged(); + (*it)->invalidate(); + } + } + if (sendScrollerStyleNotification) { + [[NSNotificationCenter defaultCenter] + postNotificationName:@"NSPreferredScrollerStyleDidChangeNotification" + object:nil + userInfo:@{ @"NSScrollerStyle" : @(gPreferredScrollerStyle) }]; + } +} + +double ScrollbarThemeMac::initialAutoscrollTimerDelay() +{ + return gInitialButtonDelay; +} + +double ScrollbarThemeMac::autoscrollTimerDelay() +{ + return gAutoscrollButtonDelay; +} + +bool ScrollbarThemeMac::shouldDragDocumentInsteadOfThumb(const ScrollbarThemeClient&, const PlatformMouseEvent& event) +{ + return event.altKey(); +} + +int ScrollbarThemeMac::scrollbarPartToHIPressedState(ScrollbarPart part) +{ + switch (part) { + case BackButtonStartPart: + return kThemeTopOutsideArrowPressed; + case BackButtonEndPart: + return kThemeTopOutsideArrowPressed; // This does not make much sense. For some reason the outside constant is required. + case ForwardButtonStartPart: + return kThemeTopInsideArrowPressed; + case ForwardButtonEndPart: + return kThemeBottomOutsideArrowPressed; + case ThumbPart: + return kThemeThumbPressed; + default: + return 0; + } +} + +ScrollbarPart ScrollbarThemeMac::invalidateOnThumbPositionChange( + const ScrollbarThemeClient& scrollbar, float oldPosition, float newPosition) const +{ + // ScrollAnimatorMac will invalidate scrollbar parts if necessary. + return NoPart; +} + +void ScrollbarThemeMac::registerScrollbar(ScrollbarThemeClient& scrollbar) +{ + scrollbarSet().add(&scrollbar); + + bool isHorizontal = scrollbar.orientation() == HorizontalScrollbar; + ScrollbarPainter scrollbarPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:recommendedScrollerStyle() controlSize:(NSControlSize)scrollbar.controlSize() horizontal:isHorizontal replacingScrollerImp:nil]; + RetainPtr<BlinkScrollbarObserver> observer = [[BlinkScrollbarObserver alloc] initWithScrollbar:&scrollbar painter:scrollbarPainter]; + + scrollbarPainterMap().add(&scrollbar, observer); + updateEnabledState(scrollbar); + updateScrollbarOverlayStyle(scrollbar); +} + +void ScrollbarThemeMac::unregisterScrollbar(ScrollbarThemeClient& scrollbar) +{ + scrollbarPainterMap().remove(&scrollbar); + scrollbarSet().remove(&scrollbar); +} + +void ScrollbarThemeMac::setNewPainterForScrollbar(ScrollbarThemeClient& scrollbar, ScrollbarPainter newPainter) +{ + RetainPtr<BlinkScrollbarObserver> observer = [[BlinkScrollbarObserver alloc] initWithScrollbar:&scrollbar painter:newPainter]; + scrollbarPainterMap().set(&scrollbar, observer); + updateEnabledState(scrollbar); + updateScrollbarOverlayStyle(scrollbar); +} + +ScrollbarPainter ScrollbarThemeMac::painterForScrollbar(const ScrollbarThemeClient& scrollbar) const +{ + return [scrollbarPainterMap().get(const_cast<ScrollbarThemeClient*>(&scrollbar)).get() painter]; +} + +void ScrollbarThemeMac::paintTrackBackground(GraphicsContext& context, const ScrollbarThemeClient& scrollbar, const IntRect& rect) { + if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, DisplayItem::ScrollbarTrackBackground)) + return; + + DrawingRecorder recorder(context, scrollbar, DisplayItem::ScrollbarTrackBackground, rect); + + GraphicsContextStateSaver stateSaver(context); + context.translate(rect.x(), rect.y()); + LocalCurrentGraphicsContext localContext(context, IntRect(IntPoint(), rect.size())); + + CGRect frameRect = scrollbar.frameRect(); + ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar); + [scrollbarPainter setEnabled:scrollbar.enabled()]; + [scrollbarPainter setBoundsSize: NSSizeFromCGSize(frameRect.size)]; + NSRect trackRect = NSMakeRect(0, 0, frameRect.size.width, frameRect.size.height); + [scrollbarPainter drawKnobSlotInRect:trackRect highlight:NO]; +} + +void ScrollbarThemeMac::paintThumb(GraphicsContext& context, const ScrollbarThemeClient& scrollbar, const IntRect& rect) { + if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, DisplayItem::ScrollbarThumb)) + return; + + // Expand dirty rect to allow for scroll thumb anti-aliasing in minimum thumb size case. + IntRect dirtyRect = IntRect(rect); + dirtyRect.inflate(1); + DrawingRecorder recorder(context, scrollbar, DisplayItem::ScrollbarThumb, dirtyRect); + + GraphicsContextStateSaver stateSaver(context); + context.translate(rect.x(), rect.y()); + LocalCurrentGraphicsContext localContext(context, IntRect(IntPoint(), rect.size())); + + ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar); + [scrollbarPainter setEnabled:scrollbar.enabled()]; + [scrollbarPainter setBoundsSize:NSSizeFromCGSize(rect.size())]; + [scrollbarPainter setDoubleValue:0]; + [scrollbarPainter setKnobProportion:1]; + + CGFloat oldKnobAlpha = [scrollbarPainter knobAlpha]; + [scrollbarPainter setKnobAlpha:1]; + + if (scrollbar.enabled()) + [scrollbarPainter drawKnob]; + + // If this state is not set, then moving the cursor over the scrollbar area will only cause the + // scrollbar to engorge when moved over the top of the scrollbar area. + [scrollbarPainter setBoundsSize: NSSizeFromCGSize(scrollbar.frameRect().size())]; + [scrollbarPainter setKnobAlpha:oldKnobAlpha]; +} + +int ScrollbarThemeMac::scrollbarThickness(ScrollbarControlSize controlSize) +{ + NSControlSize nsControlSize = static_cast<NSControlSize>(controlSize); + ScrollbarPainter scrollbarPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:recommendedScrollerStyle() controlSize:nsControlSize horizontal:NO replacingScrollerImp:nil]; + BOOL wasExpanded = NO; + if (supportsExpandedScrollbars()) { + wasExpanded = [scrollbarPainter isExpanded]; + [scrollbarPainter setExpanded:YES]; + } + int thickness = [scrollbarPainter trackBoxWidth]; + if (supportsExpandedScrollbars()) + [scrollbarPainter setExpanded:wasExpanded]; + return thickness; +} + +bool ScrollbarThemeMac::usesOverlayScrollbars() const +{ + return recommendedScrollerStyle() == NSScrollerStyleOverlay; +} + +void ScrollbarThemeMac::updateScrollbarOverlayStyle(const ScrollbarThemeClient& scrollbar) +{ + ScrollbarPainter painter = painterForScrollbar(scrollbar); + switch (scrollbar.getScrollbarOverlayStyle()) { + case ScrollbarOverlayStyleDefault: + [painter setKnobStyle:NSScrollerKnobStyleDefault]; + break; + case ScrollbarOverlayStyleDark: + [painter setKnobStyle:NSScrollerKnobStyleDark]; + break; + case ScrollbarOverlayStyleLight: + [painter setKnobStyle:NSScrollerKnobStyleLight]; + break; + } +} + +WebScrollbarButtonsPlacement ScrollbarThemeMac::buttonsPlacement() const +{ + return WebScrollbarButtonsPlacementNone; +} + +bool ScrollbarThemeMac::hasThumb(const ScrollbarThemeClient& scrollbar) +{ + ScrollbarPainter painter = painterForScrollbar(scrollbar); + int minLengthForThumb = [painter knobMinLength] + [painter trackOverlapEndInset] + [painter knobOverlapEndInset] + + 2 * ([painter trackEndInset] + [painter knobEndInset]); + return scrollbar.enabled() && (scrollbar.orientation() == HorizontalScrollbar ? + scrollbar.width() : + scrollbar.height()) >= minLengthForThumb; +} + +IntRect ScrollbarThemeMac::backButtonRect(const ScrollbarThemeClient& scrollbar, ScrollbarPart part, bool painting) +{ + ASSERT(buttonsPlacement() == WebScrollbarButtonsPlacementNone); + return IntRect(); +} + +IntRect ScrollbarThemeMac::forwardButtonRect(const ScrollbarThemeClient& scrollbar, ScrollbarPart part, bool painting) +{ + ASSERT(buttonsPlacement() == WebScrollbarButtonsPlacementNone); + return IntRect(); +} + +IntRect ScrollbarThemeMac::trackRect(const ScrollbarThemeClient& scrollbar, bool painting) +{ + ASSERT(!hasButtons(scrollbar)); + return scrollbar.frameRect(); +} + +int ScrollbarThemeMac::minimumThumbLength(const ScrollbarThemeClient& scrollbar) +{ + return [painterForScrollbar(scrollbar) knobMinLength]; +} + +void ScrollbarThemeMac::updateEnabledState(const ScrollbarThemeClient& scrollbar) +{ + [painterForScrollbar(scrollbar) setEnabled:scrollbar.enabled()]; +} + +float ScrollbarThemeMac::thumbOpacity(const ScrollbarThemeClient& scrollbar) const { + ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar); + return [scrollbarPainter knobAlpha]; +} + +// static +NSScrollerStyle ScrollbarThemeMac::recommendedScrollerStyle() +{ + if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) + return NSScrollerStyleOverlay; + return gPreferredScrollerStyle; +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacCommon.mm b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacCommon.mm deleted file mode 100644 index a1909070..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacCommon.mm +++ /dev/null
@@ -1,233 +0,0 @@ -/* - * Copyright (C) 2008, 2011 Apple 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: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "platform/RuntimeEnabledFeatures.h" -#include "platform/scroll/ScrollbarThemeMacCommon.h" - -#include <Carbon/Carbon.h> -#include "platform/PlatformMouseEvent.h" -#include "platform/graphics/GraphicsContext.h" -#include "platform/graphics/paint/DrawingRecorder.h" -#include "platform/mac/ColorMac.h" -#include "platform/mac/LocalCurrentGraphicsContext.h" -#include "platform/mac/NSScrollerImpDetails.h" -#include "platform/mac/ScrollAnimatorMac.h" -#include "platform/scroll/ScrollbarThemeClient.h" -#include "platform/scroll/ScrollbarThemeMacNonOverlayAPI.h" -#include "platform/scroll/ScrollbarThemeMacOverlayAPI.h" -#include "public/platform/WebThemeEngine.h" -#include "public/platform/Platform.h" -#include "public/platform/WebRect.h" -#include "skia/ext/skia_utils_mac.h" -#include "wtf/HashSet.h" -#include "wtf/StdLibExtras.h" -#include "wtf/TemporaryChange.h" - -// FIXME: There are repainting problems due to Aqua scroll bar buttons' visual overflow. - -using namespace blink; - -@interface NSColor (WebNSColorDetails) -+ (NSImage *)_linenPatternImage; -@end - -namespace blink { - -typedef HashSet<ScrollbarThemeClient*> ScrollbarSet; - -static ScrollbarSet& scrollbarSet() -{ - DEFINE_STATIC_LOCAL(ScrollbarSet, set, ()); - return set; -} - -static float gInitialButtonDelay = 0.5f; -static float gAutoscrollButtonDelay = 0.05f; -static NSScrollerStyle gPreferredScrollerStyle = NSScrollerStyleLegacy; - -ScrollbarTheme& ScrollbarTheme::nativeTheme() -{ - if (ScrollbarThemeMacCommon::isOverlayAPIAvailable()) { - DEFINE_STATIC_LOCAL(ScrollbarThemeMacOverlayAPI, overlayTheme, ()); - return overlayTheme; - } - { - DEFINE_STATIC_LOCAL(ScrollbarThemeMacNonOverlayAPI, nonOverlayTheme, ()); - return nonOverlayTheme; - } -} - -void ScrollbarThemeMacCommon::registerScrollbar(ScrollbarThemeClient& scrollbar) -{ - scrollbarSet().add(&scrollbar); -} - -void ScrollbarThemeMacCommon::unregisterScrollbar(ScrollbarThemeClient& scrollbar) -{ - scrollbarSet().remove(&scrollbar); -} - -void ScrollbarThemeMacCommon::paintGivenTickmarks(SkCanvas* canvas, const ScrollbarThemeClient& scrollbar, const IntRect& rect, const Vector<IntRect>& tickmarks) -{ - if (scrollbar.orientation() != VerticalScrollbar) - return; - - if (rect.height() <= 0 || rect.width() <= 0) - return; // nothing to draw on. - - if (!tickmarks.size()) - return; - - SkAutoCanvasRestore stateSaver(canvas, true); - - SkPaint strokePaint; - strokePaint.setAntiAlias(false); - strokePaint.setColor(SkColorSetRGB(0xCC, 0xAA, 0x00)); - strokePaint.setStyle(SkPaint::kStroke_Style); - - SkPaint fillPaint; - fillPaint.setAntiAlias(false); - fillPaint.setColor(SkColorSetRGB(0xFF, 0xDD, 0x00)); - fillPaint.setStyle(SkPaint::kFill_Style); - - for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) { - // Calculate how far down (in %) the tick-mark should appear. - const float percent = static_cast<float>(i->y()) / scrollbar.totalSize(); - if (percent < 0.0 || percent > 1.0) - continue; - - // Calculate how far down (in pixels) the tick-mark should appear. - const int yPos = rect.y() + (rect.height() * percent); - - // Paint. - FloatRect tickRect(rect.x(), yPos, rect.width(), 2); - canvas->drawRect(tickRect, fillPaint); - canvas->drawRect(tickRect, strokePaint); - } -} - -void ScrollbarThemeMacCommon::paintTickmarks(GraphicsContext& context, const ScrollbarThemeClient& scrollbar, const IntRect& rect) -{ - // Note: This is only used for css-styled scrollbars on mac. - if (scrollbar.orientation() != VerticalScrollbar) - return; - - if (rect.height() <= 0 || rect.width() <= 0) - return; - - Vector<IntRect> tickmarks; - scrollbar.getTickmarks(tickmarks); - if (!tickmarks.size()) - return; - - if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, DisplayItem::ScrollbarTickmarks)) - return; - - DrawingRecorder recorder(context, scrollbar, DisplayItem::ScrollbarTickmarks, rect); - - // Inset a bit. - IntRect tickmarkTrackRect = rect; - tickmarkTrackRect.setX(tickmarkTrackRect.x() + 1); - tickmarkTrackRect.setWidth(tickmarkTrackRect.width() - 2); - paintGivenTickmarks(context.canvas(), scrollbar, tickmarkTrackRect, tickmarks); -} - -ScrollbarThemeMacCommon::~ScrollbarThemeMacCommon() -{ -} - -void ScrollbarThemeMacCommon::preferencesChanged(float initialButtonDelay, float autoscrollButtonDelay, NSScrollerStyle preferredScrollerStyle, bool redraw, WebScrollbarButtonsPlacement buttonPlacement) -{ - updateButtonPlacement(buttonPlacement); - gInitialButtonDelay = initialButtonDelay; - gAutoscrollButtonDelay = autoscrollButtonDelay; - bool sendScrollerStyleNotification = gPreferredScrollerStyle != preferredScrollerStyle; - gPreferredScrollerStyle = preferredScrollerStyle; - if (redraw && !scrollbarSet().isEmpty()) { - ScrollbarSet::iterator end = scrollbarSet().end(); - for (ScrollbarSet::iterator it = scrollbarSet().begin(); it != end; ++it) { - (*it)->styleChanged(); - (*it)->invalidate(); - } - } - if (sendScrollerStyleNotification) { - [[NSNotificationCenter defaultCenter] - postNotificationName:@"NSPreferredScrollerStyleDidChangeNotification" - object:nil - userInfo:@{ @"NSScrollerStyle" : @(gPreferredScrollerStyle) }]; - } -} - -double ScrollbarThemeMacCommon::initialAutoscrollTimerDelay() -{ - return gInitialButtonDelay; -} - -double ScrollbarThemeMacCommon::autoscrollTimerDelay() -{ - return gAutoscrollButtonDelay; -} - -bool ScrollbarThemeMacCommon::shouldDragDocumentInsteadOfThumb(const ScrollbarThemeClient&, const PlatformMouseEvent& event) -{ - return event.altKey(); -} - -int ScrollbarThemeMacCommon::scrollbarPartToHIPressedState(ScrollbarPart part) -{ - switch (part) { - case BackButtonStartPart: - return kThemeTopOutsideArrowPressed; - case BackButtonEndPart: - return kThemeTopOutsideArrowPressed; // This does not make much sense. For some reason the outside constant is required. - case ForwardButtonStartPart: - return kThemeTopInsideArrowPressed; - case ForwardButtonEndPart: - return kThemeBottomOutsideArrowPressed; - case ThumbPart: - return kThemeThumbPressed; - default: - return 0; - } -} - -// static -NSScrollerStyle ScrollbarThemeMacCommon::recommendedScrollerStyle() -{ - if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) - return NSScrollerStyleOverlay; - return gPreferredScrollerStyle; -} - -// static -bool ScrollbarThemeMacCommon::isOverlayAPIAvailable() -{ - static bool apiAvailable = - [NSClassFromString(@"NSScrollerImp") respondsToSelector:@selector(scrollerImpWithStyle:controlSize:horizontal:replacingScrollerImp:)] - && [NSClassFromString(@"NSScrollerImpPair") instancesRespondToSelector:@selector(scrollerStyle)]; - return apiAvailable; -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacNonOverlayAPI.h b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacNonOverlayAPI.h deleted file mode 100644 index a0848ba..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacNonOverlayAPI.h +++ /dev/null
@@ -1,64 +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 ScrollbarThemeMacNonOverlayAPI_h -#define ScrollbarThemeMacNonOverlayAPI_h - -#include "platform/scroll/ScrollbarThemeMacCommon.h" - -namespace blink { - -class CullRect; - -class PLATFORM_EXPORT ScrollbarThemeMacNonOverlayAPI : public ScrollbarThemeMacCommon { -public: - int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) override; - bool usesOverlayScrollbars() const override { return false; } - WebScrollbarButtonsPlacement buttonsPlacement() const override; - - bool paint(const ScrollbarThemeClient&, GraphicsContext&, const CullRect&) override; - bool invalidateOnWindowActiveChange() const override { return true; } - -protected: - IntRect trackRect(const ScrollbarThemeClient&, bool painting = false) override; - IntRect backButtonRect(const ScrollbarThemeClient&, ScrollbarPart, bool painting = false) override; - IntRect forwardButtonRect(const ScrollbarThemeClient&, ScrollbarPart, bool painting = false) override; - - void updateButtonPlacement(WebScrollbarButtonsPlacement) override; - - bool hasButtons(const ScrollbarThemeClient&) override; - bool hasThumb(const ScrollbarThemeClient&) override; - - int minimumThumbLength(const ScrollbarThemeClient&) override; -}; - -} - -#endif
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacNonOverlayAPI.mm b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacNonOverlayAPI.mm deleted file mode 100644 index 1515a1f..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacNonOverlayAPI.mm +++ /dev/null
@@ -1,318 +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. - */ - -#include "platform/scroll/ScrollbarThemeMacNonOverlayAPI.h" - -#include "platform/graphics/GraphicsContext.h" -#include "platform/graphics/ImageBuffer.h" -#include "platform/graphics/paint/CullRect.h" -#include "platform/graphics/paint/DrawingRecorder.h" -#include "platform/mac/ThemeMac.h" -#include "platform/scroll/ScrollbarThemeClient.h" -#include "public/platform/Platform.h" -#include "public/platform/WebRect.h" -#include "public/platform/WebThemeEngine.h" -#include "skia/ext/skia_utils_mac.h" -#include <Carbon/Carbon.h> - -namespace blink { - -// FIXME: Get these numbers from CoreUI. -static int cRealButtonLength[] = { 28, 21 }; -static int cButtonHitInset[] = { 3, 2 }; -// cRealButtonLength - cButtonInset -static int cButtonLength[] = { 14, 10 }; -static int cScrollbarThickness[] = { 15, 11 }; -static int cButtonInset[] = { 14, 11 }; -static int cThumbMinLength[] = { 26, 20 }; - -static int cOuterButtonLength[] = { 16, 14 }; // The outer button in a double button pair is a bit bigger. -static int cOuterButtonOverlap = 2; - -static WebScrollbarButtonsPlacement gButtonPlacement = WebScrollbarButtonsPlacementDoubleEnd; - -void ScrollbarThemeMacNonOverlayAPI::updateButtonPlacement(WebScrollbarButtonsPlacement buttonPlacement) -{ - gButtonPlacement = buttonPlacement; -} - -// Override ScrollbarThemeMacCommon::paint() to add support for the following: -// - drawing using WebThemeEngine functions -// - drawing tickmarks -// - Skia specific changes -bool ScrollbarThemeMacNonOverlayAPI::paint(const ScrollbarThemeClient& scrollbar, GraphicsContext& context, const CullRect& cullRect) -{ - DisplayItem::Type displayItemType = scrollbar.orientation() == HorizontalScrollbar ? DisplayItem::ScrollbarHorizontal : DisplayItem::ScrollbarVertical; - if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, displayItemType)) - return true; - - DrawingRecorder recorder(context, scrollbar, displayItemType, scrollbar.frameRect()); - - // Get the tickmarks for the frameview. - Vector<IntRect> tickmarks; - scrollbar.getTickmarks(tickmarks); - - HIThemeTrackDrawInfo trackInfo; - trackInfo.version = 0; - trackInfo.kind = scrollbar.controlSize() == RegularScrollbar ? kThemeMediumScrollBar : kThemeSmallScrollBar; - trackInfo.bounds = scrollbar.frameRect(); - trackInfo.min = 0; - trackInfo.max = scrollbar.maximum(); - trackInfo.value = scrollbar.currentPos(); - trackInfo.trackInfo.scrollbar.viewsize = scrollbar.visibleSize(); - trackInfo.attributes = hasThumb(scrollbar) ? kThemeTrackShowThumb : 0; - - if (scrollbar.orientation() == HorizontalScrollbar) - trackInfo.attributes |= kThemeTrackHorizontal; - - if (!scrollbar.enabled()) - trackInfo.enableState = kThemeTrackDisabled; - else - trackInfo.enableState = scrollbar.isScrollableAreaActive() ? kThemeTrackActive : kThemeTrackInactive; - - if (!hasButtons(scrollbar)) - trackInfo.enableState = kThemeTrackNothingToScroll; - trackInfo.trackInfo.scrollbar.pressState = scrollbarPartToHIPressedState(scrollbar.pressedPart()); - - SkCanvas* canvas = context.canvas(); - CGAffineTransform currentCTM = skia::SkMatrixToCGAffineTransform(canvas->getTotalMatrix()); - - // The Aqua scrollbar is buggy when rotated and scaled. We will just draw into a bitmap if we detect a scale or rotation. - bool canDrawDirectly = currentCTM.a == 1.0f && currentCTM.b == 0.0f && currentCTM.c == 0.0f && (currentCTM.d == 1.0f || currentCTM.d == -1.0f); - OwnPtr<ImageBuffer> imageBuffer; - SkCanvas* drawingCanvas; - if (!canDrawDirectly) { - trackInfo.bounds = IntRect(IntPoint(), scrollbar.frameRect().size()); - - IntRect bufferRect(scrollbar.frameRect()); - bufferRect.intersect(cullRect.m_rect); - bufferRect.move(-scrollbar.frameRect().x(), -scrollbar.frameRect().y()); - - imageBuffer = ImageBuffer::create(bufferRect.size()); - if (!imageBuffer) - return true; - - drawingCanvas = imageBuffer->canvas(); - } else { - drawingCanvas = canvas; - } - - // Draw the track and its thumb. - skia::SkiaBitLocker bitLocker( - drawingCanvas, - ThemeMac::inflateRectForAA(scrollbar.frameRect()), - canDrawDirectly ? context.deviceScaleFactor() : 1.0f); - CGContextRef cgContext = bitLocker.cgContext(); - HIThemeDrawTrack(&trackInfo, 0, cgContext, kHIThemeOrientationNormal); - - IntRect tickmarkTrackRect = trackRect(scrollbar, false); - if (!canDrawDirectly) { - tickmarkTrackRect.setX(0); - tickmarkTrackRect.setY(0); - } - // The ends are rounded and the thumb doesn't go there. - tickmarkTrackRect.inflateY(-tickmarkTrackRect.width()); - // Inset a bit. - tickmarkTrackRect.setX(tickmarkTrackRect.x() + 2); - tickmarkTrackRect.setWidth(tickmarkTrackRect.width() - 5); - paintGivenTickmarks(drawingCanvas, scrollbar, tickmarkTrackRect, tickmarks); - - if (!canDrawDirectly) { - ASSERT(imageBuffer); - if (!context.contextDisabled()) { - imageBuffer->draw(context, FloatRect(scrollbar.frameRect().location(), FloatSize(imageBuffer->size())), - nullptr, SkXfermode::kSrcOver_Mode); - } - } - - return true; -} - -int ScrollbarThemeMacNonOverlayAPI::scrollbarThickness(ScrollbarControlSize controlSize) -{ - return cScrollbarThickness[controlSize]; -} - -WebScrollbarButtonsPlacement ScrollbarThemeMacNonOverlayAPI::buttonsPlacement() const -{ - return gButtonPlacement; -} - -bool ScrollbarThemeMacNonOverlayAPI::hasButtons(const ScrollbarThemeClient& scrollbar) -{ - return scrollbar.enabled() && buttonsPlacement() != WebScrollbarButtonsPlacementNone - && (scrollbar.orientation() == HorizontalScrollbar - ? scrollbar.width() - : scrollbar.height()) >= 2 * (cRealButtonLength[scrollbar.controlSize()] - cButtonHitInset[scrollbar.controlSize()]); -} - -bool ScrollbarThemeMacNonOverlayAPI::hasThumb(const ScrollbarThemeClient& scrollbar) -{ - int minLengthForThumb = 2 * cButtonInset[scrollbar.controlSize()] + cThumbMinLength[scrollbar.controlSize()] + 1; - return scrollbar.enabled() && (scrollbar.orientation() == HorizontalScrollbar ? - scrollbar.width() : - scrollbar.height()) >= minLengthForThumb; -} - -static IntRect buttonRepaintRect(const IntRect& buttonRect, ScrollbarOrientation orientation, ScrollbarControlSize controlSize, bool start) -{ - ASSERT(gButtonPlacement != WebScrollbarButtonsPlacementNone); - - IntRect paintRect(buttonRect); - if (orientation == HorizontalScrollbar) { - paintRect.setWidth(cRealButtonLength[controlSize]); - if (!start) - paintRect.setX(buttonRect.x() - (cRealButtonLength[controlSize] - buttonRect.width())); - } else { - paintRect.setHeight(cRealButtonLength[controlSize]); - if (!start) - paintRect.setY(buttonRect.y() - (cRealButtonLength[controlSize] - buttonRect.height())); - } - - return paintRect; -} - -IntRect ScrollbarThemeMacNonOverlayAPI::backButtonRect(const ScrollbarThemeClient& scrollbar, ScrollbarPart part, bool painting) -{ - IntRect result; - - if (part == BackButtonStartPart && (buttonsPlacement() == WebScrollbarButtonsPlacementNone || buttonsPlacement() == WebScrollbarButtonsPlacementDoubleEnd)) - return result; - - if (part == BackButtonEndPart && (buttonsPlacement() == WebScrollbarButtonsPlacementNone || buttonsPlacement() == WebScrollbarButtonsPlacementDoubleStart || buttonsPlacement() == WebScrollbarButtonsPlacementSingle)) - return result; - - int thickness = scrollbarThickness(scrollbar.controlSize()); - bool outerButton = part == BackButtonStartPart && (buttonsPlacement() == WebScrollbarButtonsPlacementDoubleStart || buttonsPlacement() == WebScrollbarButtonsPlacementDoubleBoth); - if (outerButton) { - if (scrollbar.orientation() == HorizontalScrollbar) - result = IntRect(scrollbar.x(), scrollbar.y(), cOuterButtonLength[scrollbar.controlSize()] + (painting ? cOuterButtonOverlap : 0), thickness); - else - result = IntRect(scrollbar.x(), scrollbar.y(), thickness, cOuterButtonLength[scrollbar.controlSize()] + (painting ? cOuterButtonOverlap : 0)); - return result; - } - - // Our repaint rect is slightly larger, since we are a button that is adjacent to the track. - if (scrollbar.orientation() == HorizontalScrollbar) { - int start = part == BackButtonStartPart ? scrollbar.x() : scrollbar.x() + scrollbar.width() - cOuterButtonLength[scrollbar.controlSize()] - cButtonLength[scrollbar.controlSize()]; - result = IntRect(start, scrollbar.y(), cButtonLength[scrollbar.controlSize()], thickness); - } else { - int start = part == BackButtonStartPart ? scrollbar.y() : scrollbar.y() + scrollbar.height() - cOuterButtonLength[scrollbar.controlSize()] - cButtonLength[scrollbar.controlSize()]; - result = IntRect(scrollbar.x(), start, thickness, cButtonLength[scrollbar.controlSize()]); - } - - if (painting) - return buttonRepaintRect(result, scrollbar.orientation(), scrollbar.controlSize(), part == BackButtonStartPart); - return result; -} - -IntRect ScrollbarThemeMacNonOverlayAPI::forwardButtonRect(const ScrollbarThemeClient& scrollbar, ScrollbarPart part, bool painting) -{ - IntRect result; - - if (part == ForwardButtonEndPart && (buttonsPlacement() == WebScrollbarButtonsPlacementNone || buttonsPlacement() == WebScrollbarButtonsPlacementDoubleStart)) - return result; - - if (part == ForwardButtonStartPart && (buttonsPlacement() == WebScrollbarButtonsPlacementNone || buttonsPlacement() == WebScrollbarButtonsPlacementDoubleEnd || buttonsPlacement() == WebScrollbarButtonsPlacementSingle)) - return result; - - int thickness = scrollbarThickness(scrollbar.controlSize()); - int outerButtonLength = cOuterButtonLength[scrollbar.controlSize()]; - int buttonLength = cButtonLength[scrollbar.controlSize()]; - - bool outerButton = part == ForwardButtonEndPart && (buttonsPlacement() == WebScrollbarButtonsPlacementDoubleEnd || buttonsPlacement() == WebScrollbarButtonsPlacementDoubleBoth); - if (outerButton) { - if (scrollbar.orientation() == HorizontalScrollbar) { - result = IntRect(scrollbar.x() + scrollbar.width() - outerButtonLength, scrollbar.y(), outerButtonLength, thickness); - if (painting) - result.inflateX(cOuterButtonOverlap); - } else { - result = IntRect(scrollbar.x(), scrollbar.y() + scrollbar.height() - outerButtonLength, thickness, outerButtonLength); - if (painting) - result.inflateY(cOuterButtonOverlap); - } - return result; - } - - if (scrollbar.orientation() == HorizontalScrollbar) { - int start = part == ForwardButtonEndPart ? scrollbar.x() + scrollbar.width() - buttonLength : scrollbar.x() + outerButtonLength; - result = IntRect(start, scrollbar.y(), buttonLength, thickness); - } else { - int start = part == ForwardButtonEndPart ? scrollbar.y() + scrollbar.height() - buttonLength : scrollbar.y() + outerButtonLength; - result = IntRect(scrollbar.x(), start, thickness, buttonLength); - } - if (painting) - return buttonRepaintRect(result, scrollbar.orientation(), scrollbar.controlSize(), part == ForwardButtonStartPart); - return result; -} - -IntRect ScrollbarThemeMacNonOverlayAPI::trackRect(const ScrollbarThemeClient& scrollbar, bool painting) -{ - if (painting || !hasButtons(scrollbar)) - return scrollbar.frameRect(); - - IntRect result; - int thickness = scrollbarThickness(scrollbar.controlSize()); - int startWidth = 0; - int endWidth = 0; - int outerButtonLength = cOuterButtonLength[scrollbar.controlSize()]; - int buttonLength = cButtonLength[scrollbar.controlSize()]; - int doubleButtonLength = outerButtonLength + buttonLength; - switch (buttonsPlacement()) { - case WebScrollbarButtonsPlacementSingle: - startWidth = buttonLength; - endWidth = buttonLength; - break; - case WebScrollbarButtonsPlacementDoubleStart: - startWidth = doubleButtonLength; - break; - case WebScrollbarButtonsPlacementDoubleEnd: - endWidth = doubleButtonLength; - break; - case WebScrollbarButtonsPlacementDoubleBoth: - startWidth = doubleButtonLength; - endWidth = doubleButtonLength; - break; - default: - break; - } - - int totalWidth = startWidth + endWidth; - if (scrollbar.orientation() == HorizontalScrollbar) - return IntRect(scrollbar.x() + startWidth, scrollbar.y(), scrollbar.width() - totalWidth, thickness); - return IntRect(scrollbar.x(), scrollbar.y() + startWidth, thickness, scrollbar.height() - totalWidth); -} - -int ScrollbarThemeMacNonOverlayAPI::minimumThumbLength(const ScrollbarThemeClient& scrollbar) -{ - return cThumbMinLength[scrollbar.controlSize()]; -} - -}
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacOverlayAPI.h b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacOverlayAPI.h deleted file mode 100644 index 40c45fa..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacOverlayAPI.h +++ /dev/null
@@ -1,75 +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 ScrollbarThemeMacOverlayAPI_h -#define ScrollbarThemeMacOverlayAPI_h - -#include "platform/scroll/ScrollbarThemeMacCommon.h" - -typedef id ScrollbarPainter; - -namespace blink { - -class PLATFORM_EXPORT ScrollbarThemeMacOverlayAPI : public ScrollbarThemeMacCommon { -public: - bool shouldRepaintAllPartsOnInvalidation() const override { return false; } - ScrollbarPart invalidateOnThumbPositionChange( - const ScrollbarThemeClient&, float oldPosition, float newPosition) const override; - void updateEnabledState(const ScrollbarThemeClient&) override; - int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) override; - bool usesOverlayScrollbars() const override; - void updateScrollbarOverlayStyle(const ScrollbarThemeClient&) override; - WebScrollbarButtonsPlacement buttonsPlacement() const override; - - void registerScrollbar(ScrollbarThemeClient&) override; - void unregisterScrollbar(ScrollbarThemeClient&) override; - - void setNewPainterForScrollbar(ScrollbarThemeClient&, ScrollbarPainter); - ScrollbarPainter painterForScrollbar(const ScrollbarThemeClient&) const; - - void paintTrackBackground(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&) override; - void paintThumb(GraphicsContext&, const ScrollbarThemeClient&, const IntRect&) override; - - float thumbOpacity(const ScrollbarThemeClient&) const override; - -protected: - IntRect trackRect(const ScrollbarThemeClient&, bool painting = false) override; - IntRect backButtonRect(const ScrollbarThemeClient&, ScrollbarPart, bool painting = false) override; - IntRect forwardButtonRect(const ScrollbarThemeClient&, ScrollbarPart, bool painting = false) override; - - bool hasButtons(const ScrollbarThemeClient&) override { return false; } - bool hasThumb(const ScrollbarThemeClient&) override; - - int minimumThumbLength(const ScrollbarThemeClient&) override; -}; - -} - -#endif
diff --git a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacOverlayAPI.mm b/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacOverlayAPI.mm deleted file mode 100644 index 12b81f4..0000000 --- a/third_party/WebKit/Source/platform/scroll/ScrollbarThemeMacOverlayAPI.mm +++ /dev/null
@@ -1,285 +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. - */ - -#include "platform/scroll/ScrollbarThemeMacOverlayAPI.h" - -#include "platform/graphics/GraphicsContext.h" -#include "platform/graphics/GraphicsContextStateSaver.h" -#include "platform/graphics/paint/DrawingRecorder.h" -#include "platform/mac/LocalCurrentGraphicsContext.h" -#include "platform/mac/NSScrollerImpDetails.h" -#include "platform/scroll/ScrollbarThemeClient.h" -#include "wtf/RetainPtr.h" - -@interface BlinkScrollbarObserver : NSObject { - blink::ScrollbarThemeClient* _scrollbar; - RetainPtr<ScrollbarPainter> _scrollbarPainter; - BOOL _visible; -} -- (id)initWithScrollbar:(blink::ScrollbarThemeClient*)scrollbar painter:(ScrollbarPainter)painter; -@end - -@implementation BlinkScrollbarObserver - -- (id)initWithScrollbar:(blink::ScrollbarThemeClient*)scrollbar painter:(ScrollbarPainter)painter -{ - if (!(self = [super init])) - return nil; - _scrollbar = scrollbar; - _scrollbarPainter = painter; - - [_scrollbarPainter.get() addObserver:self forKeyPath:@"knobAlpha" options:0 context:nil]; - return self; -} - -- (id)painter -{ - return _scrollbarPainter.get(); -} - -- (void)dealloc -{ - - [_scrollbarPainter.get() removeObserver:self forKeyPath:@"knobAlpha"]; - [super dealloc]; -} - -- (void)observeValueForKeyPath:(NSString*)keyPath - ofObject:(id)object - change:(NSDictionary*)change - context:(void*)context -{ - if ([keyPath isEqualToString:@"knobAlpha"]) { - BOOL visible = [_scrollbarPainter.get() knobAlpha] > 0; - if (_visible != visible) { - _visible = visible; - _scrollbar->visibilityChanged(); - } - } -} - -@end - -namespace blink { - -typedef HashMap<ScrollbarThemeClient*, RetainPtr<BlinkScrollbarObserver>> ScrollbarPainterMap; - -static ScrollbarPainterMap& scrollbarPainterMap() -{ - static ScrollbarPainterMap* map = new ScrollbarPainterMap; - return *map; -} - -static bool supportsExpandedScrollbars() -{ - // FIXME: This is temporary until all platforms that support ScrollbarPainter support this part of the API. - static bool globalSupportsExpandedScrollbars = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(setExpanded:)]; - return globalSupportsExpandedScrollbars; -} - -ScrollbarPart ScrollbarThemeMacOverlayAPI::invalidateOnThumbPositionChange( - const ScrollbarThemeClient& scrollbar, float oldPosition, float newPosition) const -{ - // ScrollAnimatorMac will invalidate scrollbar parts if necessary. - return NoPart; -} - -void ScrollbarThemeMacOverlayAPI::registerScrollbar(ScrollbarThemeClient& scrollbar) -{ - ScrollbarThemeMacCommon::registerScrollbar(scrollbar); - - bool isHorizontal = scrollbar.orientation() == HorizontalScrollbar; - ScrollbarPainter scrollbarPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:recommendedScrollerStyle() controlSize:(NSControlSize)scrollbar.controlSize() horizontal:isHorizontal replacingScrollerImp:nil]; - RetainPtr<BlinkScrollbarObserver> observer = [[BlinkScrollbarObserver alloc] initWithScrollbar:&scrollbar painter:scrollbarPainter]; - - scrollbarPainterMap().add(&scrollbar, observer); - updateEnabledState(scrollbar); - updateScrollbarOverlayStyle(scrollbar); -} - -void ScrollbarThemeMacOverlayAPI::unregisterScrollbar(ScrollbarThemeClient& scrollbar) -{ - scrollbarPainterMap().remove(&scrollbar); - - ScrollbarThemeMacCommon::unregisterScrollbar(scrollbar); -} - -void ScrollbarThemeMacOverlayAPI::setNewPainterForScrollbar(ScrollbarThemeClient& scrollbar, ScrollbarPainter newPainter) -{ - RetainPtr<BlinkScrollbarObserver> observer = [[BlinkScrollbarObserver alloc] initWithScrollbar:&scrollbar painter:newPainter]; - scrollbarPainterMap().set(&scrollbar, observer); - updateEnabledState(scrollbar); - updateScrollbarOverlayStyle(scrollbar); -} - -ScrollbarPainter ScrollbarThemeMacOverlayAPI::painterForScrollbar(const ScrollbarThemeClient& scrollbar) const -{ - return [scrollbarPainterMap().get(const_cast<ScrollbarThemeClient*>(&scrollbar)).get() painter]; -} - -void ScrollbarThemeMacOverlayAPI::paintTrackBackground(GraphicsContext& context, const ScrollbarThemeClient& scrollbar, const IntRect& rect) { - if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, DisplayItem::ScrollbarTrackBackground)) - return; - - DrawingRecorder recorder(context, scrollbar, DisplayItem::ScrollbarTrackBackground, rect); - - ASSERT(isOverlayAPIAvailable()); - - GraphicsContextStateSaver stateSaver(context); - context.translate(rect.x(), rect.y()); - LocalCurrentGraphicsContext localContext(context, IntRect(IntPoint(), rect.size())); - - CGRect frameRect = scrollbar.frameRect(); - ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar); - [scrollbarPainter setEnabled:scrollbar.enabled()]; - [scrollbarPainter setBoundsSize: NSSizeFromCGSize(frameRect.size)]; - NSRect trackRect = NSMakeRect(0, 0, frameRect.size.width, frameRect.size.height); - [scrollbarPainter drawKnobSlotInRect:trackRect highlight:NO]; -} - -void ScrollbarThemeMacOverlayAPI::paintThumb(GraphicsContext& context, const ScrollbarThemeClient& scrollbar, const IntRect& rect) { - if (DrawingRecorder::useCachedDrawingIfPossible(context, scrollbar, DisplayItem::ScrollbarThumb)) - return; - - // Expand dirty rect to allow for scroll thumb anti-aliasing in minimum thumb size case. - IntRect dirtyRect = IntRect(rect); - dirtyRect.inflate(1); - DrawingRecorder recorder(context, scrollbar, DisplayItem::ScrollbarThumb, dirtyRect); - - ASSERT(isOverlayAPIAvailable()); - - GraphicsContextStateSaver stateSaver(context); - context.translate(rect.x(), rect.y()); - LocalCurrentGraphicsContext localContext(context, IntRect(IntPoint(), rect.size())); - - ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar); - [scrollbarPainter setEnabled:scrollbar.enabled()]; - [scrollbarPainter setBoundsSize:NSSizeFromCGSize(rect.size())]; - [scrollbarPainter setDoubleValue:0]; - [scrollbarPainter setKnobProportion:1]; - - CGFloat oldKnobAlpha = [scrollbarPainter knobAlpha]; - [scrollbarPainter setKnobAlpha:1]; - - if (scrollbar.enabled()) - [scrollbarPainter drawKnob]; - - // If this state is not set, then moving the cursor over the scrollbar area will only cause the - // scrollbar to engorge when moved over the top of the scrollbar area. - [scrollbarPainter setBoundsSize: NSSizeFromCGSize(scrollbar.frameRect().size())]; - [scrollbarPainter setKnobAlpha:oldKnobAlpha]; -} - -int ScrollbarThemeMacOverlayAPI::scrollbarThickness(ScrollbarControlSize controlSize) -{ - NSControlSize nsControlSize = static_cast<NSControlSize>(controlSize); - ScrollbarPainter scrollbarPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:recommendedScrollerStyle() controlSize:nsControlSize horizontal:NO replacingScrollerImp:nil]; - BOOL wasExpanded = NO; - if (supportsExpandedScrollbars()) { - wasExpanded = [scrollbarPainter isExpanded]; - [scrollbarPainter setExpanded:YES]; - } - int thickness = [scrollbarPainter trackBoxWidth]; - if (supportsExpandedScrollbars()) - [scrollbarPainter setExpanded:wasExpanded]; - return thickness; -} - -bool ScrollbarThemeMacOverlayAPI::usesOverlayScrollbars() const -{ - return recommendedScrollerStyle() == NSScrollerStyleOverlay; -} - -void ScrollbarThemeMacOverlayAPI::updateScrollbarOverlayStyle(const ScrollbarThemeClient& scrollbar) -{ - ScrollbarPainter painter = painterForScrollbar(scrollbar); - switch (scrollbar.getScrollbarOverlayStyle()) { - case ScrollbarOverlayStyleDefault: - [painter setKnobStyle:NSScrollerKnobStyleDefault]; - break; - case ScrollbarOverlayStyleDark: - [painter setKnobStyle:NSScrollerKnobStyleDark]; - break; - case ScrollbarOverlayStyleLight: - [painter setKnobStyle:NSScrollerKnobStyleLight]; - break; - } -} - -WebScrollbarButtonsPlacement ScrollbarThemeMacOverlayAPI::buttonsPlacement() const -{ - return WebScrollbarButtonsPlacementNone; -} - -bool ScrollbarThemeMacOverlayAPI::hasThumb(const ScrollbarThemeClient& scrollbar) -{ - ScrollbarPainter painter = painterForScrollbar(scrollbar); - int minLengthForThumb = [painter knobMinLength] + [painter trackOverlapEndInset] + [painter knobOverlapEndInset] - + 2 * ([painter trackEndInset] + [painter knobEndInset]); - return scrollbar.enabled() && (scrollbar.orientation() == HorizontalScrollbar ? - scrollbar.width() : - scrollbar.height()) >= minLengthForThumb; -} - -IntRect ScrollbarThemeMacOverlayAPI::backButtonRect(const ScrollbarThemeClient& scrollbar, ScrollbarPart part, bool painting) -{ - ASSERT(buttonsPlacement() == WebScrollbarButtonsPlacementNone); - return IntRect(); -} - -IntRect ScrollbarThemeMacOverlayAPI::forwardButtonRect(const ScrollbarThemeClient& scrollbar, ScrollbarPart part, bool painting) -{ - ASSERT(buttonsPlacement() == WebScrollbarButtonsPlacementNone); - return IntRect(); -} - -IntRect ScrollbarThemeMacOverlayAPI::trackRect(const ScrollbarThemeClient& scrollbar, bool painting) -{ - ASSERT(!hasButtons(scrollbar)); - return scrollbar.frameRect(); -} - -int ScrollbarThemeMacOverlayAPI::minimumThumbLength(const ScrollbarThemeClient& scrollbar) -{ - return [painterForScrollbar(scrollbar) knobMinLength]; -} - -void ScrollbarThemeMacOverlayAPI::updateEnabledState(const ScrollbarThemeClient& scrollbar) -{ - [painterForScrollbar(scrollbar) setEnabled:scrollbar.enabled()]; -} - -float ScrollbarThemeMacOverlayAPI::thumbOpacity(const ScrollbarThemeClient& scrollbar) const { - ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar); - return [scrollbarPainter knobAlpha]; -} - -} // namespace blink -
diff --git a/third_party/WebKit/Source/platform/v8_inspector/DebuggerScript.js b/third_party/WebKit/Source/platform/v8_inspector/DebuggerScript.js index ca49639..44448964 100644 --- a/third_party/WebKit/Source/platform/v8_inspector/DebuggerScript.js +++ b/third_party/WebKit/Source/platform/v8_inspector/DebuggerScript.js
@@ -398,9 +398,9 @@ scopeTypes[i] = scopeDetails.type(); scopeObjects[i] = scopeDetails.object(); scopeNames[i] = scopeDetails.name(); - scopeStartPositions[i] = scopeDetails.startPosition(); - scopeEndPositions[i] = scopeDetails.endPosition(); - scopeFunctions[i] = scopeDetails.func(); + scopeStartPositions[i] = scopeDetails.startPosition ? scopeDetails.startPosition() : 0; + scopeEndPositions[i] = scopeDetails.endPosition ? scopeDetails.endPosition() : 0; + scopeFunctions[i] = scopeDetails.func ? scopeDetails.func() : null; } // Calculated lazily. @@ -436,8 +436,8 @@ scopeNames[j] = scopeNames[i]; scopeChain[j] = scopeObject; - var funcMirror = MakeMirror(scopeFunctions[i]); - if (!funcMirror.isFunction()) + var funcMirror = scopeFunctions ? MakeMirror(scopeFunctions[i]) : null; + if (!funcMirror || !funcMirror.isFunction()) funcMirror = new UnresolvedFunctionMirror(funcObject); var script = funcMirror.script();
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h index aff8f26..e28dfaf9 100644 --- a/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h +++ b/third_party/WebKit/Source/platform/v8_inspector/V8DebuggerAgentImpl.h
@@ -57,7 +57,7 @@ void setFrontend(protocol::Frontend::Debugger* frontend) override { m_frontend = frontend; } void clearFrontend() override; void restore() override; - void disable(ErrorString*); + void disable(ErrorString*) override; bool isPaused() override;
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h index 878dea7..377d52d 100644 --- a/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h +++ b/third_party/WebKit/Source/platform/v8_inspector/V8ProfilerAgentImpl.h
@@ -38,8 +38,8 @@ void consoleProfile(const String& title) override; void consoleProfileEnd(const String& title) override; - void idleStarted(); - void idleFinished(); + void idleStarted() override; + void idleFinished() override; private: String nextProfileId();
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp index 34285ad..2bf176e 100644 --- a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp +++ b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.cpp
@@ -185,11 +185,6 @@ *errorString = "Not paused"; } -void V8RuntimeAgentImpl::isRunRequired(ErrorString*, bool* out_result) -{ - *out_result = false; -} - void V8RuntimeAgentImpl::setCustomObjectFormatterEnabled(ErrorString*, bool enabled) { m_state->setBoolean(V8RuntimeAgentImplState::customObjectFormatterEnabled, enabled);
diff --git a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h index 29a6d66..d3c6e35 100644 --- a/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h +++ b/third_party/WebKit/Source/platform/v8_inspector/V8RuntimeAgentImpl.h
@@ -94,7 +94,6 @@ Maybe<protocol::Runtime::ExceptionDetails>*) override; void releaseObjectGroup(ErrorString*, const String& objectGroup) override; void run(ErrorString*) override; - void isRunRequired(ErrorString*, bool* result) override; void setCustomObjectFormatterEnabled(ErrorString*, bool) override; void compileScript(ErrorString*, const String& expression,
diff --git a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp index 453f894d..73163b1 100644 --- a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp +++ b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.cpp
@@ -72,6 +72,7 @@ #include "modules/storage/InspectorDOMStorageAgent.h" #include "modules/webdatabase/InspectorDatabaseAgent.h" #include "platform/RuntimeEnabledFeatures.h" +#include "platform/ThreadSafeFunctional.h" #include "platform/TraceEvent.h" #include "platform/graphics/GraphicsContext.h" #include "platform/graphics/paint/PaintController.h" @@ -266,31 +267,6 @@ ClientMessageLoopAdapter* ClientMessageLoopAdapter::s_instance = nullptr; -class DebuggerTask : public InspectorTaskRunner::Task { -public: - DebuggerTask(int sessionId, PassOwnPtr<WebDevToolsAgent::MessageDescriptor> descriptor) - : m_sessionId(sessionId) - , m_descriptor(descriptor) - { - } - - ~DebuggerTask() override {} - virtual void run() - { - WebDevToolsAgent* webagent = m_descriptor->agent(); - if (!webagent) - return; - - WebDevToolsAgentImpl* agentImpl = static_cast<WebDevToolsAgentImpl*>(webagent); - if (agentImpl->m_attached) - agentImpl->dispatchMessageFromFrontend(m_sessionId, m_descriptor->message()); - } - -private: - int m_sessionId; - OwnPtr<WebDevToolsAgent::MessageDescriptor> m_descriptor; -}; - // static PassOwnPtrWillBeRawPtr<WebDevToolsAgentImpl> WebDevToolsAgentImpl::create(WebLocalFrameImpl* frame, WebDevToolsAgentClient* client) { @@ -608,7 +584,7 @@ if (!m_attached) return; if (WebDevToolsAgent::shouldInterruptForMessage(message)) - MainThreadDebugger::instance()->taskRunner()->runPendingTasks(); + MainThreadDebugger::instance()->taskRunner()->runAllTasksDontWait(); else dispatchMessageFromFrontend(sessionId, message); } @@ -740,12 +716,21 @@ flushPendingProtocolNotifications(); } +void WebDevToolsAgentImpl::runDebuggerTask(int sessionId, PassOwnPtr<WebDevToolsAgent::MessageDescriptor> descriptor) +{ + WebDevToolsAgent* webagent = descriptor->agent(); + if (!webagent) + return; + + WebDevToolsAgentImpl* agentImpl = static_cast<WebDevToolsAgentImpl*>(webagent); + if (agentImpl->m_attached) + agentImpl->dispatchMessageFromFrontend(sessionId, descriptor->message()); +} + void WebDevToolsAgent::interruptAndDispatch(int sessionId, MessageDescriptor* rawDescriptor) { // rawDescriptor can't be a PassOwnPtr because interruptAndDispatch is a WebKit API function. - OwnPtr<MessageDescriptor> descriptor = adoptPtr(rawDescriptor); - OwnPtr<DebuggerTask> task = adoptPtr(new DebuggerTask(sessionId, descriptor.release())); - MainThreadDebugger::interruptMainThreadAndRun(task.release()); + MainThreadDebugger::interruptMainThreadAndRun(threadSafeBind(WebDevToolsAgentImpl::runDebuggerTask, sessionId, adoptPtr(rawDescriptor))); } bool WebDevToolsAgent::shouldInterruptForMessage(const WebString& message)
diff --git a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h index 7424e9e..0cf84be 100644 --- a/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h +++ b/third_party/WebKit/Source/web/WebDevToolsAgentImpl.h
@@ -46,7 +46,6 @@ namespace blink { -class DebuggerTask; class GraphicsLayer; class InspectedFrames; class InspectorInspectorAgent; @@ -142,6 +141,9 @@ void initializeDeferredAgents(); + friend class WebDevToolsAgent; + static void runDebuggerTask(int sessionId, PassOwnPtr<WebDevToolsAgent::MessageDescriptor>); + WebDevToolsAgentClient* m_client; RawPtrWillBeMember<WebLocalFrameImpl> m_webLocalFrameImpl; bool m_attached; @@ -173,8 +175,6 @@ int m_sessionId; String m_stateCookie; bool m_stateMuted; - - friend class DebuggerTask; }; } // namespace blink
diff --git a/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp b/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp index 14a2274..59d83a5 100644 --- a/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp +++ b/third_party/WebKit/Source/web/WebDevToolsFrontendImpl.cpp
@@ -32,6 +32,7 @@ #include "bindings/core/v8/ScriptController.h" #include "bindings/core/v8/V8DevToolsHost.h" +#include "core/frame/FrameHost.h" #include "core/frame/LocalFrame.h" #include "core/inspector/DevToolsHost.h" #include "public/platform/WebSecurityOrigin.h" @@ -56,6 +57,7 @@ , m_client(client) { m_webFrame->setDevToolsFrontend(this); + m_webFrame->frame()->host()->setDefaultPageScaleLimits(1.f, 1.f); } WebDevToolsFrontendImpl::~WebDevToolsFrontendImpl()
diff --git a/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp b/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp index a933efb..40e9b35 100644 --- a/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp +++ b/third_party/WebKit/Source/web/WebEmbeddedWorkerImpl.cpp
@@ -32,6 +32,7 @@ #include "core/dom/CrossThreadTask.h" #include "core/dom/Document.h" +#include "core/dom/SecurityContext.h" #include "core/fetch/SubstituteData.h" #include "core/frame/csp/ContentSecurityPolicy.h" #include "core/inspector/InspectorInstrumentation.h" @@ -345,10 +346,6 @@ Document* document = m_mainFrame->frame()->document(); - WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart; - if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(document)) - startMode = PauseWorkerGlobalScopeOnStart; - // FIXME: this document's origin is pristine and without any extra privileges. (crbug.com/254993) SecurityOrigin* starterOrigin = document->securityOrigin(); @@ -361,6 +358,7 @@ document->initContentSecurityPolicy(m_mainScriptLoader->releaseContentSecurityPolicy()); KURL scriptURL = m_mainScriptLoader->url(); + WorkerThreadStartMode startMode = m_workerInspectorProxy->workerStartMode(document); OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create( scriptURL, m_workerStartData.userAgent, @@ -370,6 +368,7 @@ document->contentSecurityPolicy()->headers(), starterOrigin, workerClients.release(), + m_mainScriptLoader->responseAddressSpace(), static_cast<V8CacheOptions>(m_workerStartData.v8CacheOptions)); m_mainScriptLoader.clear();
diff --git a/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp b/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp index 33fb4bf..002b61f 100644 --- a/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp +++ b/third_party/WebKit/Source/web/WebSharedWorkerImpl.cpp
@@ -322,10 +322,6 @@ } Document* document = m_mainFrame->frame()->document(); - WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart; - if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(document)) - startMode = PauseWorkerGlobalScopeOnStart; - // FIXME: this document's origin is pristine and without any extra privileges. (crbug.com/254993) SecurityOrigin* starterOrigin = document->securityOrigin(); @@ -334,6 +330,7 @@ WebSecurityOrigin webSecurityOrigin(m_loadingDocument->securityOrigin()); provideContentSettingsClientToWorker(workerClients.get(), adoptPtr(m_client->createWorkerContentSettingsClientProxy(webSecurityOrigin))); RefPtrWillBeRawPtr<ContentSecurityPolicy> contentSecurityPolicy = m_mainScriptLoader->releaseContentSecurityPolicy(); + WorkerThreadStartMode startMode = m_workerInspectorProxy->workerStartMode(document); OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create( m_url, m_loadingDocument->userAgent(), @@ -342,7 +339,8 @@ startMode, contentSecurityPolicy ? contentSecurityPolicy->headers() : nullptr, starterOrigin, - workerClients.release()); + workerClients.release(), + m_mainScriptLoader->responseAddressSpace()); m_loaderProxy = WorkerLoaderProxy::create(this); m_workerThread = SharedWorkerThread::create(m_name, m_loaderProxy, *this); InspectorInstrumentation::scriptImported(m_loadingDocument.get(), m_mainScriptLoader->identifier(), m_mainScriptLoader->script());
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index 0a2b40e..325d6088 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -410,7 +410,7 @@ , m_zoomLevel(0) , m_minimumZoomLevel(zoomFactorToZoomLevel(minTextSizeMultiplier)) , m_maximumZoomLevel(zoomFactorToZoomLevel(maxTextSizeMultiplier)) - , m_zoomFactorForDeviceScaleFactor(1.f) + , m_zoomFactorForDeviceScaleFactor(0.f) , m_maximumLegibleScale(1) , m_doubleTapZoomPageScaleFactor(0) , m_doubleTapZoomPending(false) @@ -3055,7 +3055,16 @@ LocalFrame* frame = mainFrameImpl()->frame(); if (!WebLocalFrameImpl::pluginContainerFromFrame(frame)) { float zoomFactor = m_zoomFactorOverride ? m_zoomFactorOverride : static_cast<float>(zoomLevelToZoomFactor(m_zoomLevel)); - zoomFactor *= m_zoomFactorForDeviceScaleFactor; + if (m_zoomFactorForDeviceScaleFactor) { + if (m_compositorDeviceScaleFactorOverride) { + // Adjust the page's DSF so that DevicePixelRatio becomes m_zoomFactorForDeviceScaleFactor. + page()->setDeviceScaleFactor(m_zoomFactorForDeviceScaleFactor / m_compositorDeviceScaleFactorOverride); + zoomFactor *= m_compositorDeviceScaleFactorOverride; + } else { + page()->setDeviceScaleFactor(1.f); + zoomFactor *= m_zoomFactorForDeviceScaleFactor; + } + } frame->setPageZoomFactor(zoomFactor); } @@ -3772,6 +3781,10 @@ if (m_compositorDeviceScaleFactorOverride == deviceScaleFactor) return; m_compositorDeviceScaleFactorOverride = deviceScaleFactor; + if (m_zoomFactorForDeviceScaleFactor) { + setZoomLevel(zoomLevel()); + return; + } if (page() && m_layerTreeView) updateLayerTreeDeviceScaleFactor(); }
diff --git a/third_party/WebKit/Source/web/mac/WebScrollbarTheme.mm b/third_party/WebKit/Source/web/mac/WebScrollbarTheme.mm index 6751c46..b450358 100644 --- a/third_party/WebKit/Source/web/mac/WebScrollbarTheme.mm +++ b/third_party/WebKit/Source/web/mac/WebScrollbarTheme.mm
@@ -33,7 +33,7 @@ #import <AppKit/AppKit.h> #include "platform/mac/NSScrollerImpDetails.h" -#include "platform/scroll/ScrollbarThemeMacCommon.h" +#include "platform/scroll/ScrollbarThemeMac.h" using namespace blink; @@ -50,7 +50,7 @@ if (theme.isMockTheme()) return; - static_cast<ScrollbarThemeMacCommon&>(theme).preferencesChanged( + static_cast<ScrollbarThemeMac&>(theme).preferencesChanged( initialButtonDelay, autoscrollButtonDelay, static_cast<NSScrollerStyle>(preferredScrollerStyle), redraw, buttonPlacement);
diff --git a/third_party/WebKit/Source/wtf/HashMap.h b/third_party/WebKit/Source/wtf/HashMap.h index dca62595..cb6a72f 100644 --- a/third_party/WebKit/Source/wtf/HashMap.h +++ b/third_party/WebKit/Source/wtf/HashMap.h
@@ -127,12 +127,14 @@ // replaces value but not key if key is already present return value is a // pair of the iterator to the key location, and a boolean that's true if a // new value was actually added - AddResult set(KeyPeekInType, MappedPassInType); + template <typename IncomingKeyType, typename IncomingMappedType> + AddResult set(IncomingKeyType&&, IncomingMappedType&&); // does nothing if key is already present return value is a pair of the // iterator to the key location, and a boolean that's true if a new value // was actually added - AddResult add(KeyPeekInType, MappedPassInType); + template <typename IncomingKeyType, typename IncomingMappedType> + AddResult add(IncomingKeyType&&, IncomingMappedType&&); void remove(KeyPeekInType); void remove(iterator); @@ -166,7 +168,8 @@ void trace(VisitorDispatcher visitor) { m_impl.trace(visitor); } private: - AddResult inlineAdd(KeyPeekInType, MappedPassInReferenceType); + template <typename IncomingKeyType, typename IncomingMappedType> + AddResult inlineAdd(IncomingKeyType&&, IncomingMappedType&&); HashTableType m_impl; }; @@ -264,10 +267,10 @@ STATIC_ONLY(HashMapTranslator); template <typename T> static unsigned hash(const T& key) { return HashFunctions::hash(key); } template <typename T, typename U> static bool equal(const T& a, const U& b) { return HashFunctions::equal(a, b); } - template <typename T, typename U, typename V> static void translate(T& location, const U& key, const V& mapped) + template <typename T, typename U, typename V> static void translate(T& location, U&& key, V&& mapped) { - location.key = key; - ValueTraits::ValueTraits::store(mapped, location.value); + location.key = std::forward<U>(key); + ValueTraits::ValueTraits::store(std::forward<V>(mapped), location.value); } }; @@ -276,10 +279,10 @@ STATIC_ONLY(HashMapTranslatorAdapter); template <typename T> static unsigned hash(const T& key) { return Translator::hash(key); } template <typename T, typename U> static bool equal(const T& a, const U& b) { return Translator::equal(a, b); } - template <typename T, typename U, typename V> static void translate(T& location, const U& key, const V& mapped, unsigned hashCode) + template <typename T, typename U, typename V> static void translate(T& location, U&& key, V&& mapped, unsigned hashCode) { - Translator::translate(location.key, key, hashCode); - ValueTraits::ValueTraits::store(mapped, location.value); + Translator::translate(location.key, std::forward<U>(key), hashCode); + ValueTraits::ValueTraits::store(std::forward<V>(mapped), location.value); } }; @@ -368,21 +371,25 @@ } template <typename T, typename U, typename V, typename W, typename X, typename Y> +template <typename IncomingKeyType, typename IncomingMappedType> typename HashMap<T, U, V, W, X, Y>::AddResult -HashMap<T, U, V, W, X, Y>::inlineAdd(KeyPeekInType key, MappedPassInReferenceType mapped) +HashMap<T, U, V, W, X, Y>::inlineAdd(IncomingKeyType&& key, IncomingMappedType&& mapped) { - return m_impl.template add<HashMapTranslator<ValueTraits, HashFunctions>>(key, mapped); + return m_impl.template add<HashMapTranslator<ValueTraits, HashFunctions>>(std::forward<IncomingKeyType>(key), std::forward<IncomingMappedType>(mapped)); } template <typename T, typename U, typename V, typename W, typename X, typename Y> +template <typename IncomingKeyType, typename IncomingMappedType> typename HashMap<T, U, V, W, X, Y>::AddResult -HashMap<T, U, V, W, X, Y>::set(KeyPeekInType key, MappedPassInType mapped) +HashMap<T, U, V, W, X, Y>::set(IncomingKeyType&& key, IncomingMappedType&& mapped) { - AddResult result = inlineAdd(key, mapped); + AddResult result = inlineAdd(std::forward<IncomingKeyType>(key), std::forward<IncomingMappedType>(mapped)); if (!result.isNewEntry) { // The inlineAdd call above found an existing hash table entry; we need // to set the mapped value. - MappedTraits::store(mapped, result.storedValue->value); + // + // It's safe to call std::forward again, because |mapped| isn't moved if there's an existing entry. + MappedTraits::store(std::forward<IncomingMappedType>(mapped), result.storedValue->value); } return result; } @@ -396,10 +403,11 @@ } template <typename T, typename U, typename V, typename W, typename X, typename Y> +template <typename IncomingKeyType, typename IncomingMappedType> typename HashMap<T, U, V, W, X, Y>::AddResult -HashMap<T, U, V, W, X, Y>::add(KeyPeekInType key, MappedPassInType mapped) +HashMap<T, U, V, W, X, Y>::add(IncomingKeyType&& key, IncomingMappedType&& mapped) { - return inlineAdd(key, mapped); + return inlineAdd(std::forward<IncomingKeyType>(key), std::forward<IncomingMappedType>(mapped)); } template <typename T, typename U, typename V, typename W, typename X, typename Y>
diff --git a/third_party/WebKit/Source/wtf/HashMapTest.cpp b/third_party/WebKit/Source/wtf/HashMapTest.cpp index 9f37efa..214aa1f 100644 --- a/third_party/WebKit/Source/wtf/HashMapTest.cpp +++ b/third_party/WebKit/Source/wtf/HashMapTest.cpp
@@ -302,6 +302,178 @@ EXPECT_EQ(0, InstanceCounter::counter); } +class MoveOnly { +public: + // kEmpty and kDeleted have special meanings when MoveOnly is used as the key of a hash table. + enum { + kEmpty = 0, + kDeleted = -1, + kMovedOut = -2 + }; + + explicit MoveOnly(int value = kEmpty) : m_value(value) { } + MoveOnly(MoveOnly&& other) + : m_value(other.m_value) + { + other.m_value = kMovedOut; + } + MoveOnly& operator=(MoveOnly&& other) + { + m_value = other.m_value; + other.m_value = kMovedOut; + return *this; + } + + int value() const { return m_value; } + +private: + MoveOnly(const MoveOnly&) = delete; + MoveOnly& operator=(const MoveOnly&) = delete; + + int m_value; +}; + +struct MoveOnlyHashTraits : public GenericHashTraits<MoveOnly> { + // This is actually true, but we pretend that it's false to disable the optimization. + static const bool emptyValueIsZero = false; + + static const bool hasIsEmptyValueFunction = true; + static bool isEmptyValue(const MoveOnly& value) { return value.value() == MoveOnly::kEmpty; } + static void constructDeletedValue(MoveOnly& slot, bool) { slot = MoveOnly(MoveOnly::kDeleted); } + static bool isDeletedValue(const MoveOnly& value) { return value.value() == MoveOnly::kDeleted; } +}; + +struct MoveOnlyHash { + static unsigned hash(const MoveOnly& value) { return DefaultHash<int>::Hash::hash(value.value()); } + static bool equal(const MoveOnly& left, const MoveOnly& right) + { + return DefaultHash<int>::Hash::equal(left.value(), right.value()); + } + static const bool safeToCompareToEmptyOrDeleted = true; +}; + +} // anonymous namespace + +template <> +struct HashTraits<MoveOnly> : public MoveOnlyHashTraits { }; + +template <> +struct DefaultHash<MoveOnly> { + using Hash = MoveOnlyHash; +}; + +namespace { + +TEST(HashMapTest, MoveOnlyValueType) +{ + using TheMap = HashMap<int, MoveOnly>; + TheMap map; + { + TheMap::AddResult addResult = map.add(1, MoveOnly(10)); + EXPECT_TRUE(addResult.isNewEntry); + EXPECT_EQ(1, addResult.storedValue->key); + EXPECT_EQ(10, addResult.storedValue->value.value()); + } + auto iter = map.find(1); + ASSERT_TRUE(iter != map.end()); + EXPECT_EQ(1, iter->key); + EXPECT_EQ(10, iter->value.value()); + + iter = map.find(2); + EXPECT_TRUE(iter == map.end()); + + // Try to add more to trigger rehashing. + for (int i = 2; i < 32; ++i) { + TheMap::AddResult addResult = map.add(i, MoveOnly(i * 10)); + EXPECT_TRUE(addResult.isNewEntry); + EXPECT_EQ(i, addResult.storedValue->key); + EXPECT_EQ(i * 10, addResult.storedValue->value.value()); + } + + iter = map.find(1); + ASSERT_TRUE(iter != map.end()); + EXPECT_EQ(1, iter->key); + EXPECT_EQ(10, iter->value.value()); + + iter = map.find(7); + ASSERT_TRUE(iter != map.end()); + EXPECT_EQ(7, iter->key); + EXPECT_EQ(70, iter->value.value()); + + { + TheMap::AddResult addResult = map.set(9, MoveOnly(999)); + EXPECT_FALSE(addResult.isNewEntry); + EXPECT_EQ(9, addResult.storedValue->key); + EXPECT_EQ(999, addResult.storedValue->value.value()); + } + + map.remove(11); + iter = map.find(11); + EXPECT_TRUE(iter == map.end()); + + MoveOnly oneThirty(map.take(13)); + EXPECT_EQ(130, oneThirty.value()); + iter = map.find(13); + EXPECT_TRUE(iter == map.end()); + + map.clear(); +} + +TEST(HashMapTest, MoveOnlyKeyType) +{ + // The content of this test is similar to the test above, except that the types of key and value are swapped. + using TheMap = HashMap<MoveOnly, int>; + TheMap map; + { + TheMap::AddResult addResult = map.add(MoveOnly(1), 10); + EXPECT_TRUE(addResult.isNewEntry); + EXPECT_EQ(1, addResult.storedValue->key.value()); + EXPECT_EQ(10, addResult.storedValue->value); + } + auto iter = map.find(MoveOnly(1)); + ASSERT_TRUE(iter != map.end()); + EXPECT_EQ(1, iter->key.value()); + EXPECT_EQ(10, iter->value); + + iter = map.find(MoveOnly(2)); + EXPECT_TRUE(iter == map.end()); + + for (int i = 2; i < 32; ++i) { + TheMap::AddResult addResult = map.add(MoveOnly(i), i * 10); + EXPECT_TRUE(addResult.isNewEntry); + EXPECT_EQ(i, addResult.storedValue->key.value()); + EXPECT_EQ(i * 10, addResult.storedValue->value); + } + + iter = map.find(MoveOnly(1)); + ASSERT_TRUE(iter != map.end()); + EXPECT_EQ(1, iter->key.value()); + EXPECT_EQ(10, iter->value); + + iter = map.find(MoveOnly(7)); + ASSERT_TRUE(iter != map.end()); + EXPECT_EQ(7, iter->key.value()); + EXPECT_EQ(70, iter->value); + + { + TheMap::AddResult addResult = map.set(MoveOnly(9), 999); + EXPECT_FALSE(addResult.isNewEntry); + EXPECT_EQ(9, addResult.storedValue->key.value()); + EXPECT_EQ(999, addResult.storedValue->value); + } + + map.remove(MoveOnly(11)); + iter = map.find(MoveOnly(11)); + EXPECT_TRUE(iter == map.end()); + + int oneThirty = map.take(MoveOnly(13)); + EXPECT_EQ(130, oneThirty); + iter = map.find(MoveOnly(13)); + EXPECT_TRUE(iter == map.end()); + + map.clear(); +} + } // anonymous namespace } // namespace WTF
diff --git a/third_party/WebKit/Source/wtf/HashTable.h b/third_party/WebKit/Source/wtf/HashTable.h index 85b68a72..5b6edd2 100644 --- a/third_party/WebKit/Source/wtf/HashTable.h +++ b/third_party/WebKit/Source/wtf/HashTable.h
@@ -249,37 +249,24 @@ using std::swap; -// Work around MSVC's standard library, whose swap for pairs does not swap by component. -template <typename T> inline void hashTableSwap(T& a, T& b) -{ - swap(a, b); -} - -template <typename T, typename U> inline void hashTableSwap(KeyValuePair<T, U>& a, KeyValuePair<T, U>& b) -{ - swap(a.key, b.key); - swap(a.value, b.value); -} - -template <typename T, typename Allocator, bool useSwap = !IsTriviallyDestructible<T>::value> -struct Mover; -template <typename T, typename Allocator> struct Mover<T, Allocator, true> { +template <typename T, typename Allocator, bool enterGCForbiddenScope> struct Mover { STATIC_ONLY(Mover); - static void move(T& from, T& to) + static void move(T&& from, T& to) { - // The key and value cannot be swapped atomically, and it would be wrong - // to have a GC when only one was swapped and the other still contained - // garbage (eg. from a previous use of the same slot). Therefore we - // forbid a GC until both the key and the value are swapped. - Allocator::enterGCForbiddenScope(); - hashTableSwap(from, to); - Allocator::leaveGCForbiddenScope(); + to.~T(); + new (NotNull, &to) T(std::move(from)); } }; -template <typename T, typename Allocator> struct Mover<T, Allocator, false> { +template <typename T, typename Allocator> struct Mover<T, Allocator, true> { STATIC_ONLY(Mover); - static void move(T& from, T& to) { to = from; } + static void move(T&& from, T& to) + { + to.~T(); + Allocator::enterGCForbiddenScope(); + new (NotNull, &to) T(std::move(from)); + Allocator::leaveGCForbiddenScope(); + } }; template <typename HashFunctions> class IdentityHashTranslator { @@ -287,7 +274,7 @@ public: template <typename T> static unsigned hash(const T& key) { return HashFunctions::hash(key); } template <typename T, typename U> static bool equal(const T& a, const U& b) { return HashFunctions::equal(a, b); } - template <typename T, typename U, typename V> static void translate(T& location, const U&, const V& value) { location = value; } + template <typename T, typename U, typename V> static void translate(T& location, U&&, V&& value) { location = std::forward<V>(value); } }; template <typename HashTableType, typename ValueType> struct HashTableAddResult final { @@ -475,7 +462,7 @@ // A special version of add() that finds the object by hashing and comparing // with some other type, to avoid the cost of type conversion if the object // is already in the table. - template <typename HashTranslator, typename T, typename Extra> AddResult add(const T& key, const Extra&); + template <typename HashTranslator, typename T, typename Extra> AddResult add(T&& key, Extra&&); template <typename HashTranslator, typename T, typename Extra> AddResult addPassingHashCode(const T& key, const Extra&); iterator find(KeyPeekInType key) { return find<IdentityTranslatorType>(key); } @@ -496,8 +483,8 @@ static bool isEmptyOrDeletedBucket(const ValueType& value) { return HashTableHelper<ValueType, Extractor, KeyTraits>:: isEmptyOrDeletedBucket(value); } ValueType* lookup(KeyPeekInType key) { return lookup<IdentityTranslatorType, KeyPeekInType>(key); } - template <typename HashTranslator, typename T> ValueType* lookup(T); - template <typename HashTranslator, typename T> const ValueType* lookup(T) const; + template <typename HashTranslator, typename T> ValueType* lookup(const T&); + template <typename HashTranslator, typename T> const ValueType* lookup(const T&) const; template <typename VisitorDispatcher> void trace(VisitorDispatcher); @@ -544,7 +531,7 @@ ValueType* expandBuffer(unsigned newTableSize, ValueType* entry, bool&); ValueType* rehashTo(ValueType* newTable, unsigned newTableSize, ValueType* entry); ValueType* rehash(unsigned newTableSize, ValueType* entry); - ValueType* reinsert(ValueType&); + ValueType* reinsert(ValueType&&); static void initializeBucket(ValueType& bucket); static void deleteBucket(ValueType& bucket) @@ -647,14 +634,14 @@ template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> -inline Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::lookup(T key) +inline Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::lookup(const T& key) { - return const_cast<Value*>(const_cast<const HashTable*>(this)->lookup<HashTranslator, T>(key)); + return const_cast<Value*>(const_cast<const HashTable*>(this)->lookup<HashTranslator>(key)); } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T> -inline const Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::lookup(T key) const +inline const Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::lookup(const T& key) const { ASSERT(!m_accessForbidden); ASSERT((HashTableKeyChecker<HashTranslator, KeyTraits, HashFunctions::safeToCompareToEmptyOrDeleted>::checkKey(key))); @@ -808,7 +795,7 @@ template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> template <typename HashTranslator, typename T, typename Extra> -typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::AddResult HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::add(const T& key, const Extra& extra) +typename HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::AddResult HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::add(T&& key, Extra&& extra) { ASSERT(!m_accessForbidden); ASSERT(Allocator::isAllocationAllowed()); @@ -861,7 +848,7 @@ --m_deletedCount; } - HashTranslator::translate(*entry, key, extra); + HashTranslator::translate(*entry, std::forward<T>(key), std::forward<Extra>(extra)); ASSERT(!isEmptyOrDeletedBucket(*entry)); ++m_keyCount; @@ -908,7 +895,7 @@ } template <typename Key, typename Value, typename Extractor, typename HashFunctions, typename Traits, typename KeyTraits, typename Allocator> -Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::reinsert(ValueType& entry) +Value* HashTable<Key, Value, Extractor, HashFunctions, Traits, KeyTraits, Allocator>::reinsert(ValueType&& entry) { ASSERT(m_table); registerModification(); @@ -921,7 +908,7 @@ ++m_stats->numReinserts; #endif Value* newEntry = lookupForWriting(Extractor::extract(entry)).first; - Mover<ValueType, Allocator>::move(entry, *newEntry); + Mover<ValueType, Allocator, Traits::template NeedsToForbidGCOnMove<>::value>::move(std::move(entry), *newEntry); return newEntry; } @@ -1098,7 +1085,7 @@ initializeBucket(temporaryTable[i]); } } else { - Mover<ValueType, Allocator>::move(m_table[i], temporaryTable[i]); + Mover<ValueType, Allocator, Traits::template NeedsToForbidGCOnMove<>::value>::move(std::move(m_table[i]), temporaryTable[i]); } } m_table = temporaryTable; @@ -1148,7 +1135,7 @@ ASSERT(&oldTable[i] != entry); continue; } - Value* reinsertedEntry = reinsert(oldTable[i]); + Value* reinsertedEntry = reinsert(std::move(oldTable[i])); if (&oldTable[i] == entry) { ASSERT(!newEntry); newEntry = reinsertedEntry;
diff --git a/third_party/WebKit/Source/wtf/HashTraits.h b/third_party/WebKit/Source/wtf/HashTraits.h index e280ea5..8cda7d9 100644 --- a/third_party/WebKit/Source/wtf/HashTraits.h +++ b/third_party/WebKit/Source/wtf/HashTraits.h
@@ -66,6 +66,18 @@ struct NeedsTracingLazily { static const bool value = NeedsTracing<T>::value; }; + + // The NeedsToForbidGCOnMove flag is used to make the hash table move + // operations safe when GC is enabled: if a move constructor invokes + // an allocation triggering the GC then it should be invoked within GC + // forbidden scope. + template <typename U = void> + struct NeedsToForbidGCOnMove { + // TODO(yutak): Consider using of std:::is_trivially_move_constructible + // when it is accessible. + static const bool value = !std::is_pod<T>::value; + }; + static const WeakHandlingFlag weakHandlingFlag = IsWeak<T>::value ? WeakHandlingInCollections : NoWeakHandlingInCollections; }; @@ -95,11 +107,13 @@ // The store function either not be called or called once to store something // passed in. The value passed to the store function will be PassInType. typedef const T& PassInType; - static void store(const T& value, T& storage) { storage = value; } + template <typename IncomingValueType> + static void store(IncomingValueType&& value, T& storage) { storage = std::forward<IncomingValueType>(value); } // Type for return value of functions that transfer ownership, such as take. typedef T PassOutType; - static const T& passOut(const T& value) { return value; } + static T&& passOut(T& value) { return std::move(value); } + static T&& passOut(T&& value) { return std::move(value); } // Type for return value of functions that do not transfer ownership, such // as get. @@ -138,6 +152,10 @@ template <typename T> struct SimpleClassHashTraits : GenericHashTraits<T> { static const bool emptyValueIsZero = true; + template <typename U = void> + struct NeedsToForbidGCOnMove { + static const bool value = false; + }; static void constructDeletedValue(T& slot, bool) { new (NotNull, &slot) T(HashTableDeletedValue); } static bool isDeletedValue(const T& value) { return value.isHashTableDeletedValue(); } }; @@ -248,16 +266,17 @@ struct KeyValuePair { typedef KeyTypeArg KeyType; - KeyValuePair(const KeyTypeArg& _key, const ValueTypeArg& _value) - : key(_key) - , value(_value) + template <typename IncomingKeyType, typename IncomingValueType> + KeyValuePair(IncomingKeyType&& key, IncomingValueType&& value) + : key(std::forward<IncomingKeyType>(key)) + , value(std::forward<IncomingValueType>(value)) { } template <typename OtherKeyType, typename OtherValueType> - KeyValuePair(const KeyValuePair<OtherKeyType, OtherValueType>& other) - : key(other.key) - , value(other.value) + KeyValuePair(KeyValuePair<OtherKeyType, OtherValueType>&& other) + : key(std::move(other.key)) + , value(std::move(other.value)) { } @@ -279,6 +298,12 @@ struct NeedsTracingLazily { static const bool value = NeedsTracingTrait<KeyTraits>::value || NeedsTracingTrait<ValueTraits>::value; }; + + template <typename U = void> + struct NeedsToForbidGCOnMove { + static const bool value = KeyTraits::template NeedsToForbidGCOnMove<>::value || ValueTraits::template NeedsToForbidGCOnMove<>::value; + }; + static const WeakHandlingFlag weakHandlingFlag = (KeyTraits::weakHandlingFlag == WeakHandlingInCollections || ValueTraits::weakHandlingFlag == WeakHandlingInCollections) ? WeakHandlingInCollections : NoWeakHandlingInCollections; static const unsigned minimumTableSize = KeyTraits::minimumTableSize;
diff --git a/third_party/WebKit/Source/wtf/LinkedHashSet.h b/third_party/WebKit/Source/wtf/LinkedHashSet.h index b35a362..36506687 100644 --- a/third_party/WebKit/Source/wtf/LinkedHashSet.h +++ b/third_party/WebKit/Source/wtf/LinkedHashSet.h
@@ -114,6 +114,18 @@ : m_prev(0) , m_next(0) { } + LinkedHashSetNodeBase(LinkedHashSetNodeBase&& other) + : m_prev(other.m_prev) + , m_next(other.m_next) + { + other.m_prev = nullptr; + other.m_next = nullptr; + if (m_next) { + m_prev->m_next = this; + m_next->m_prev = this; + } + } + private: // Should not be used. LinkedHashSetNodeBase& operator=(const LinkedHashSetNodeBase& other); @@ -121,7 +133,7 @@ template<typename ValueArg, typename Allocator> class LinkedHashSetNode : public LinkedHashSetNodeBase { - DISALLOW_NEW(); + DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); public: LinkedHashSetNode(const ValueArg& value, LinkedHashSetNodeBase* prev, LinkedHashSetNodeBase* next) : LinkedHashSetNodeBase(prev, next) @@ -129,11 +141,16 @@ { } + LinkedHashSetNode(LinkedHashSetNode&& other) + : LinkedHashSetNodeBase(std::move(other)) + , m_value(std::move(other.m_value)) + { + } + ValueArg m_value; private: - // Not used. - LinkedHashSetNode(const LinkedHashSetNode&); + WTF_MAKE_NONCOPYABLE(LinkedHashSetNode); }; template<
diff --git a/third_party/boringssl/BUILD.gn b/third_party/boringssl/BUILD.gn index 2ac6ec3..91c6ded 100644 --- a/third_party/boringssl/BUILD.gn +++ b/third_party/boringssl/BUILD.gn
@@ -7,16 +7,36 @@ import("//testing/libfuzzer/fuzzer_test.gni") # Config for us and everybody else depending on BoringSSL. -config("openssl_config") { +config("external_config") { include_dirs = [ "src/include" ] if (is_component_build) { defines = [ "BORINGSSL_SHARED_LIBRARY" ] } } -# Config internal to this build file. -config("openssl_internal_config") { +# Config internal to this build file, shared by boringssl and boringssl_fuzzer. +config("internal_config") { visibility = [ ":*" ] # Only targets in this file can depend on this. + defines = [ + "BORINGSSL_IMPLEMENTATION", + "BORINGSSL_NO_STATIC_INITIALIZER", + "OPENSSL_SMALL", + ] + configs = [ + # TODO(davidben): Fix size_t truncations in BoringSSL. + # https://crbug.com/429039 + "//build/config/compiler:no_size_t_to_int_warning", + ] +} + +config("no_asm_config") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + defines = [ "OPENSSL_NO_ASM" ] +} + +config("fuzzer_config") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + defines = [ "BORINGSSL_UNSAFE_FUZZER_MODE" ] } # The list of BoringSSL files is kept in boringssl.gypi. @@ -25,6 +45,8 @@ [ rebase_path("//third_party/boringssl/boringssl.gypi") ], "scope", [ "//third_party/boringssl/boringssl.gypi" ]) +boringssl_sources = + gypi_values.boringssl_crypto_sources + gypi_values.boringssl_ssl_sources # Windows' assembly is built with Yasm. The other platforms use the platform # assembler. @@ -37,83 +59,92 @@ sources = gypi_values.boringssl_win_x86_sources } } +} else { + source_set("boringssl_asm") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + + sources = [] + asmflags = [] + include_dirs = [ "src/include" ] + + if (current_cpu == "arm" && is_clang) { + # TODO(hans) Enable integrated-as (crbug.com/124610). + asmflags += [ "-fno-integrated-as" ] + if (is_android) { + rebased_android_toolchain_root = + rebase_path(android_toolchain_root, root_build_dir) + + # Else /usr/bin/as gets picked up. + asmflags += [ "-B${rebased_android_toolchain_root}/bin" ] + } + } + + if (is_msan) { + public_configs = [ ":no_asm_config" ] + } else if (current_cpu == "x64") { + if (is_mac || is_ios) { + sources += gypi_values.boringssl_mac_x86_64_sources + } else if (is_linux || is_android) { + sources += gypi_values.boringssl_linux_x86_64_sources + } else { + public_configs = [ ":no_asm_config" ] + } + } else if (current_cpu == "x86") { + if (is_mac || is_ios) { + sources += gypi_values.boringssl_mac_x86_sources + } else if (is_linux || is_android) { + sources += gypi_values.boringssl_linux_x86_sources + } else { + public_configs = [ ":no_asm_config" ] + } + } else if (current_cpu == "arm" && (is_linux || is_android)) { + sources += gypi_values.boringssl_linux_arm_sources + } else if (current_cpu == "arm64" && (is_linux || is_android)) { + sources += gypi_values.boringssl_linux_aarch64_sources + + # TODO(davidben): Remove explicit arch flag once https://crbug.com/576858 + # is fixed. + asmflags += [ "-march=armv8-a+crypto" ] + } else { + public_configs = [ ":no_asm_config" ] + } + } } component("boringssl") { - sources = gypi_values.boringssl_crypto_sources - sources += gypi_values.boringssl_ssl_sources - - public_configs = [ ":openssl_config" ] - - asmflags = [] - cflags = [] - defines = [ - "BORINGSSL_IMPLEMENTATION", - "BORINGSSL_NO_STATIC_INITIALIZER", - "OPENSSL_SMALL", + sources = boringssl_sources + deps = [ + ":boringssl_asm", ] - deps = [] - if (is_component_build) { - defines += [ "BORINGSSL_SHARED_LIBRARY" ] - } + + public_configs = [ ":external_config" ] + configs += [ ":internal_config" ] configs -= [ "//build/config/compiler:chromium_code" ] - configs += [ - "//build/config/compiler:no_chromium_code", + configs += [ "//build/config/compiler:no_chromium_code" ] - # TODO(davidben): Fix size_t truncations in BoringSSL. - # https://crbug.com/429039 - "//build/config/compiler:no_size_t_to_int_warning", + if (is_nacl) { + deps += [ "//native_client_sdk/src/libraries/nacl_io" ] + } +} + +# The same as boringssl, but builds with BORINGSSL_UNSAFE_FUZZER_MODE. +component("boringssl_fuzzer") { + visibility = [ ":*" ] # Only targets in this file can depend on this. + + sources = boringssl_sources + deps = [ + ":boringssl_asm", ] - # Also gets the include dirs from :openssl_config - include_dirs = [ "src/include" ] + public_configs = [ + ":external_config", + ":fuzzer_config", + ] + configs += [ ":internal_config" ] - if (current_cpu == "arm" && is_clang) { - # TODO(hans) Enable integrated-as (crbug.com/124610). - asmflags += [ "-fno-integrated-as" ] - if (is_android) { - rebased_android_toolchain_root = - rebase_path(android_toolchain_root, root_build_dir) - - # Else /usr/bin/as gets picked up. - asmflags += [ "-B${rebased_android_toolchain_root}/bin" ] - } - } - - if (is_msan) { - defines += [ "OPENSSL_NO_ASM" ] - } else if (current_cpu == "x64") { - if (is_mac || is_ios) { - sources += gypi_values.boringssl_mac_x86_64_sources - } else if (is_linux || is_android) { - sources += gypi_values.boringssl_linux_x86_64_sources - } else if (is_win) { - deps += [ ":boringssl_asm" ] - } else { - defines += [ "OPENSSL_NO_ASM" ] - } - } else if (current_cpu == "x86") { - if (is_mac || is_ios) { - sources += gypi_values.boringssl_mac_x86_sources - } else if (is_linux || is_android) { - sources += gypi_values.boringssl_linux_x86_sources - } else if (is_win) { - deps += [ ":boringssl_asm" ] - } else { - defines += [ "OPENSSL_NO_ASM" ] - } - } else if (current_cpu == "arm" && (is_linux || is_android)) { - sources += gypi_values.boringssl_linux_arm_sources - } else if (current_cpu == "arm64" && (is_linux || is_android)) { - sources += gypi_values.boringssl_linux_aarch64_sources - - # TODO(davidben): Remove explicit arch flag once https://crbug.com/576858 - # is fixed. - asmflags += [ "-march=armv8-a+crypto" ] - } else { - defines += [ "OPENSSL_NO_ASM" ] - } + configs -= [ "//build/config/compiler:chromium_code" ] + configs += [ "//build/config/compiler:no_chromium_code" ] if (is_nacl) { deps += [ "//native_client_sdk/src/libraries/nacl_io" ] @@ -125,7 +156,7 @@ "src/fuzz/cert.cc", ] deps = [ - ":boringssl", + ":boringssl_fuzzer", ] } @@ -134,7 +165,7 @@ "src/fuzz/client.cc", ] deps = [ - ":boringssl", + ":boringssl_fuzzer", ] } @@ -143,7 +174,7 @@ "src/fuzz/privkey.cc", ] deps = [ - ":boringssl", + ":boringssl_fuzzer", ] } @@ -152,6 +183,6 @@ "src/fuzz/server.cc", ] deps = [ - ":boringssl", + ":boringssl_fuzzer", ] }
diff --git a/third_party/boringssl/boringssl.gypi b/third_party/boringssl/boringssl.gypi index 2643855..6742d581 100644 --- a/third_party/boringssl/boringssl.gypi +++ b/third_party/boringssl/boringssl.gypi
@@ -202,6 +202,7 @@ 'src/crypto/pkcs8/p8_pkey.c', 'src/crypto/pkcs8/pkcs8.c', 'src/crypto/poly1305/poly1305.c', + 'src/crypto/rand/deterministic.c', 'src/crypto/rand/rand.c', 'src/crypto/rand/urandom.c', 'src/crypto/rand/windows.c',
diff --git a/third_party/boringssl/boringssl_tests.gypi b/third_party/boringssl/boringssl_tests.gypi index 980a8d2..863ad81 100644 --- a/third_party/boringssl/boringssl_tests.gypi +++ b/third_party/boringssl/boringssl_tests.gypi
@@ -91,6 +91,20 @@ 'msvs_disabled_warnings': [ 4267, ], }, { + 'target_name': 'boringssl_chacha_test', + 'type': 'executable', + 'dependencies': [ + 'boringssl.gyp:boringssl', + ], + 'sources': [ + 'src/crypto/chacha/chacha_test.cc', + '<@(boringssl_test_support_sources)', + ], + # TODO(davidben): Fix size_t truncations in BoringSSL. + # https://crbug.com/429039 + 'msvs_disabled_warnings': [ 4267, ], + }, + { 'target_name': 'boringssl_aead_test', 'type': 'executable', 'dependencies': [ @@ -567,6 +581,7 @@ 'boringssl_bio_test', 'boringssl_bn_test', 'boringssl_bytestring_test', + 'boringssl_chacha_test', 'boringssl_cipher_test', 'boringssl_cmac_test', 'boringssl_constant_time_test',
diff --git a/third_party/boringssl/boringssl_unittest.cc b/third_party/boringssl/boringssl_unittest.cc index 65839e1..04ce0f5 100644 --- a/third_party/boringssl/boringssl_unittest.cc +++ b/third_party/boringssl/boringssl_unittest.cc
@@ -161,6 +161,10 @@ TestSimple("bytestring_test"); } +TEST(BoringSSL, ChaCha) { + TestSimple("chacha_test"); +} + TEST(BoringSSL, Cipher) { base::FilePath data_file; ASSERT_TRUE(CryptoCipherTestPath(&data_file));
diff --git a/third_party/boringssl/linux-aarch64/crypto/poly1305/poly1305-armv8.S b/third_party/boringssl/linux-aarch64/crypto/poly1305/poly1305-armv8.S index 83aaac85..7b681aa 100644 --- a/third_party/boringssl/linux-aarch64/crypto/poly1305/poly1305-armv8.S +++ b/third_party/boringssl/linux-aarch64/crypto/poly1305/poly1305-armv8.S
@@ -739,6 +739,19 @@ .Lshort_tail: //////////////////////////////////////////////////////////////// + // horizontal add + + addp v22.2d,v22.2d,v22.2d + ldp d8,d9,[sp,#16] // meet ABI requirements + addp v19.2d,v19.2d,v19.2d + ldp d10,d11,[sp,#32] + addp v23.2d,v23.2d,v23.2d + ldp d12,d13,[sp,#48] + addp v20.2d,v20.2d,v20.2d + ldp d14,d15,[sp,#64] + addp v21.2d,v21.2d,v21.2d + + //////////////////////////////////////////////////////////////// // lazy reduction, but without narrowing ushr v29.2d,v22.2d,#26 @@ -770,19 +783,6 @@ add v23.2d,v23.2d,v30.2d // h3 -> h4 //////////////////////////////////////////////////////////////// - // horizontal add - - addp v21.2d,v21.2d,v21.2d - ldp d8,d9,[sp,#16] // meet ABI requirements - addp v19.2d,v19.2d,v19.2d - ldp d10,d11,[sp,#32] - addp v20.2d,v20.2d,v20.2d - ldp d12,d13,[sp,#48] - addp v22.2d,v22.2d,v22.2d - ldp d14,d15,[sp,#64] - addp v23.2d,v23.2d,v23.2d - - //////////////////////////////////////////////////////////////// // write the result, can be partially reduced st4 {v19.s,v20.s,v21.s,v22.s}[0],[x0],#16
diff --git a/third_party/boringssl/linux-arm/crypto/poly1305/poly1305-armv4.S b/third_party/boringssl/linux-arm/crypto/poly1305/poly1305-armv4.S index 52b0a0c8c..acd96f2 100644 --- a/third_party/boringssl/linux-arm/crypto/poly1305/poly1305-armv4.S +++ b/third_party/boringssl/linux-arm/crypto/poly1305/poly1305-armv4.S
@@ -997,6 +997,15 @@ .Lshort_tail: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + @ horizontal addition + + vadd.i64 d16,d16,d17 + vadd.i64 d10,d10,d11 + vadd.i64 d18,d18,d19 + vadd.i64 d12,d12,d13 + vadd.i64 d14,d14,d15 + + @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ lazy reduction, but without narrowing vshr.u64 q15,q8,#26 @@ -1026,15 +1035,6 @@ vadd.i64 q6,q6,q15 @ h0 -> h1 vadd.i64 q9,q9,q4 @ h3 -> h4 - @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - @ horizontal addition - - vadd.i64 d14,d14,d15 - vadd.i64 d10,d10,d11 - vadd.i64 d16,d16,d17 - vadd.i64 d12,d12,d13 - vadd.i64 d18,d18,d19 - cmp r2,#0 bne .Leven
diff --git a/third_party/boringssl/linux-x86/crypto/poly1305/poly1305-x86.S b/third_party/boringssl/linux-x86/crypto/poly1305/poly1305-x86.S index fe442f8..6821901 100644 --- a/third_party/boringssl/linux-x86/crypto/poly1305/poly1305-x86.S +++ b/third_party/boringssl/linux-x86/crypto/poly1305/poly1305-x86.S
@@ -1200,9 +1200,19 @@ paddq %xmm5,%xmm1 paddq %xmm6,%xmm2 .L017short_tail: + pshufd $78,%xmm4,%xmm6 + pshufd $78,%xmm3,%xmm5 + paddq %xmm6,%xmm4 + paddq %xmm5,%xmm3 + pshufd $78,%xmm0,%xmm6 + pshufd $78,%xmm1,%xmm5 + paddq %xmm6,%xmm0 + paddq %xmm5,%xmm1 + pshufd $78,%xmm2,%xmm6 movdqa %xmm3,%xmm5 pand %xmm7,%xmm3 psrlq $26,%xmm5 + paddq %xmm6,%xmm2 paddq %xmm4,%xmm5 movdqa %xmm0,%xmm6 pand %xmm7,%xmm0 @@ -1230,24 +1240,14 @@ paddd %xmm5,%xmm1 pand %xmm7,%xmm3 paddd %xmm6,%xmm4 - pshufd $78,%xmm0,%xmm6 - pshufd $78,%xmm1,%xmm5 - paddd %xmm6,%xmm0 - pshufd $78,%xmm2,%xmm6 - paddd %xmm5,%xmm1 - pshufd $78,%xmm3,%xmm5 - paddd %xmm6,%xmm2 - pshufd $78,%xmm4,%xmm6 - paddd %xmm5,%xmm3 - paddd %xmm6,%xmm4 .L013done: movd %xmm0,-48(%edi) movd %xmm1,-44(%edi) movd %xmm2,-40(%edi) movd %xmm3,-36(%edi) movd %xmm4,-32(%edi) -.L007nodata: movl %ebp,%esp +.L007nodata: popl %edi popl %esi popl %ebx
diff --git a/third_party/boringssl/linux-x86_64/crypto/poly1305/poly1305-x86_64.S b/third_party/boringssl/linux-x86_64/crypto/poly1305/poly1305-x86_64.S index a89874e..5f7d75b6 100644 --- a/third_party/boringssl/linux-x86_64/crypto/poly1305/poly1305-x86_64.S +++ b/third_party/boringssl/linux-x86_64/crypto/poly1305/poly1305-x86_64.S
@@ -1102,6 +1102,20 @@ + vpsrldq $8,%xmm14,%xmm9 + vpsrldq $8,%xmm13,%xmm8 + vpsrldq $8,%xmm11,%xmm6 + vpsrldq $8,%xmm10,%xmm5 + vpsrldq $8,%xmm12,%xmm7 + vpaddq %xmm8,%xmm13,%xmm13 + vpaddq %xmm9,%xmm14,%xmm14 + vpaddq %xmm5,%xmm10,%xmm10 + vpaddq %xmm6,%xmm11,%xmm11 + vpaddq %xmm7,%xmm12,%xmm12 + + + + vpsrlq $26,%xmm13,%xmm3 vpand %xmm15,%xmm13,%xmm13 vpaddq %xmm3,%xmm14,%xmm14 @@ -1133,25 +1147,11 @@ vpand %xmm15,%xmm13,%xmm13 vpaddq %xmm3,%xmm14,%xmm14 - - - - vpsrldq $8,%xmm12,%xmm7 - vpsrldq $8,%xmm10,%xmm5 - vpsrldq $8,%xmm11,%xmm6 - vpsrldq $8,%xmm13,%xmm8 - vpsrldq $8,%xmm14,%xmm9 - vpaddq %xmm7,%xmm12,%xmm2 - vpaddq %xmm5,%xmm10,%xmm0 - vpaddq %xmm6,%xmm11,%xmm1 - vpaddq %xmm8,%xmm13,%xmm3 - vpaddq %xmm9,%xmm14,%xmm4 - - vmovd %xmm0,-112(%rdi) - vmovd %xmm1,-108(%rdi) - vmovd %xmm2,-104(%rdi) - vmovd %xmm3,-100(%rdi) - vmovd %xmm4,-96(%rdi) + vmovd %xmm10,-112(%rdi) + vmovd %xmm11,-108(%rdi) + vmovd %xmm12,-104(%rdi) + vmovd %xmm13,-100(%rdi) + vmovd %xmm14,-96(%rdi) leaq 88(%r11),%rsp vzeroupper .byte 0xf3,0xc3 @@ -1747,6 +1747,31 @@ + vpsrldq $8,%ymm12,%ymm8 + vpsrldq $8,%ymm2,%ymm9 + vpsrldq $8,%ymm3,%ymm10 + vpsrldq $8,%ymm4,%ymm6 + vpsrldq $8,%ymm0,%ymm7 + vpaddq %ymm8,%ymm12,%ymm12 + vpaddq %ymm9,%ymm2,%ymm2 + vpaddq %ymm10,%ymm3,%ymm3 + vpaddq %ymm6,%ymm4,%ymm4 + vpaddq %ymm7,%ymm0,%ymm0 + + vpermq $0x2,%ymm3,%ymm10 + vpermq $0x2,%ymm4,%ymm6 + vpermq $0x2,%ymm0,%ymm7 + vpermq $0x2,%ymm12,%ymm8 + vpermq $0x2,%ymm2,%ymm9 + vpaddq %ymm10,%ymm3,%ymm3 + vpaddq %ymm6,%ymm4,%ymm4 + vpaddq %ymm7,%ymm0,%ymm0 + vpaddq %ymm8,%ymm12,%ymm12 + vpaddq %ymm9,%ymm2,%ymm2 + + + + vpsrlq $26,%ymm3,%ymm14 vpand %ymm5,%ymm3,%ymm3 vpaddq %ymm14,%ymm4,%ymm4 @@ -1778,31 +1803,6 @@ vpand %ymm5,%ymm3,%ymm3 vpaddq %ymm14,%ymm4,%ymm4 - - - - vpsrldq $8,%ymm2,%ymm9 - vpsrldq $8,%ymm0,%ymm7 - vpsrldq $8,%ymm1,%ymm8 - vpsrldq $8,%ymm3,%ymm10 - vpsrldq $8,%ymm4,%ymm6 - vpaddq %ymm9,%ymm2,%ymm2 - vpaddq %ymm7,%ymm0,%ymm0 - vpaddq %ymm8,%ymm1,%ymm1 - vpaddq %ymm10,%ymm3,%ymm3 - vpaddq %ymm6,%ymm4,%ymm4 - - vpermq $0x2,%ymm2,%ymm9 - vpermq $0x2,%ymm0,%ymm7 - vpermq $0x2,%ymm1,%ymm8 - vpermq $0x2,%ymm3,%ymm10 - vpermq $0x2,%ymm4,%ymm6 - vpaddq %ymm9,%ymm2,%ymm2 - vpaddq %ymm7,%ymm0,%ymm0 - vpaddq %ymm8,%ymm1,%ymm1 - vpaddq %ymm10,%ymm3,%ymm3 - vpaddq %ymm6,%ymm4,%ymm4 - vmovd %xmm0,-112(%rdi) vmovd %xmm1,-108(%rdi) vmovd %xmm2,-104(%rdi)
diff --git a/third_party/boringssl/mac-x86/crypto/poly1305/poly1305-x86.S b/third_party/boringssl/mac-x86/crypto/poly1305/poly1305-x86.S index f433f48..9b8f6f6 100644 --- a/third_party/boringssl/mac-x86/crypto/poly1305/poly1305-x86.S +++ b/third_party/boringssl/mac-x86/crypto/poly1305/poly1305-x86.S
@@ -1191,9 +1191,19 @@ paddq %xmm5,%xmm1 paddq %xmm6,%xmm2 L017short_tail: + pshufd $78,%xmm4,%xmm6 + pshufd $78,%xmm3,%xmm5 + paddq %xmm6,%xmm4 + paddq %xmm5,%xmm3 + pshufd $78,%xmm0,%xmm6 + pshufd $78,%xmm1,%xmm5 + paddq %xmm6,%xmm0 + paddq %xmm5,%xmm1 + pshufd $78,%xmm2,%xmm6 movdqa %xmm3,%xmm5 pand %xmm7,%xmm3 psrlq $26,%xmm5 + paddq %xmm6,%xmm2 paddq %xmm4,%xmm5 movdqa %xmm0,%xmm6 pand %xmm7,%xmm0 @@ -1221,24 +1231,14 @@ paddd %xmm5,%xmm1 pand %xmm7,%xmm3 paddd %xmm6,%xmm4 - pshufd $78,%xmm0,%xmm6 - pshufd $78,%xmm1,%xmm5 - paddd %xmm6,%xmm0 - pshufd $78,%xmm2,%xmm6 - paddd %xmm5,%xmm1 - pshufd $78,%xmm3,%xmm5 - paddd %xmm6,%xmm2 - pshufd $78,%xmm4,%xmm6 - paddd %xmm5,%xmm3 - paddd %xmm6,%xmm4 L013done: movd %xmm0,-48(%edi) movd %xmm1,-44(%edi) movd %xmm2,-40(%edi) movd %xmm3,-36(%edi) movd %xmm4,-32(%edi) -L007nodata: movl %ebp,%esp +L007nodata: popl %edi popl %esi popl %ebx
diff --git a/third_party/boringssl/mac-x86_64/crypto/poly1305/poly1305-x86_64.S b/third_party/boringssl/mac-x86_64/crypto/poly1305/poly1305-x86_64.S index 78c887dd..13f028db 100644 --- a/third_party/boringssl/mac-x86_64/crypto/poly1305/poly1305-x86_64.S +++ b/third_party/boringssl/mac-x86_64/crypto/poly1305/poly1305-x86_64.S
@@ -1101,6 +1101,20 @@ + vpsrldq $8,%xmm14,%xmm9 + vpsrldq $8,%xmm13,%xmm8 + vpsrldq $8,%xmm11,%xmm6 + vpsrldq $8,%xmm10,%xmm5 + vpsrldq $8,%xmm12,%xmm7 + vpaddq %xmm8,%xmm13,%xmm13 + vpaddq %xmm9,%xmm14,%xmm14 + vpaddq %xmm5,%xmm10,%xmm10 + vpaddq %xmm6,%xmm11,%xmm11 + vpaddq %xmm7,%xmm12,%xmm12 + + + + vpsrlq $26,%xmm13,%xmm3 vpand %xmm15,%xmm13,%xmm13 vpaddq %xmm3,%xmm14,%xmm14 @@ -1132,25 +1146,11 @@ vpand %xmm15,%xmm13,%xmm13 vpaddq %xmm3,%xmm14,%xmm14 - - - - vpsrldq $8,%xmm12,%xmm7 - vpsrldq $8,%xmm10,%xmm5 - vpsrldq $8,%xmm11,%xmm6 - vpsrldq $8,%xmm13,%xmm8 - vpsrldq $8,%xmm14,%xmm9 - vpaddq %xmm7,%xmm12,%xmm2 - vpaddq %xmm5,%xmm10,%xmm0 - vpaddq %xmm6,%xmm11,%xmm1 - vpaddq %xmm8,%xmm13,%xmm3 - vpaddq %xmm9,%xmm14,%xmm4 - - vmovd %xmm0,-112(%rdi) - vmovd %xmm1,-108(%rdi) - vmovd %xmm2,-104(%rdi) - vmovd %xmm3,-100(%rdi) - vmovd %xmm4,-96(%rdi) + vmovd %xmm10,-112(%rdi) + vmovd %xmm11,-108(%rdi) + vmovd %xmm12,-104(%rdi) + vmovd %xmm13,-100(%rdi) + vmovd %xmm14,-96(%rdi) leaq 88(%r11),%rsp vzeroupper .byte 0xf3,0xc3 @@ -1746,6 +1746,31 @@ + vpsrldq $8,%ymm12,%ymm8 + vpsrldq $8,%ymm2,%ymm9 + vpsrldq $8,%ymm3,%ymm10 + vpsrldq $8,%ymm4,%ymm6 + vpsrldq $8,%ymm0,%ymm7 + vpaddq %ymm8,%ymm12,%ymm12 + vpaddq %ymm9,%ymm2,%ymm2 + vpaddq %ymm10,%ymm3,%ymm3 + vpaddq %ymm6,%ymm4,%ymm4 + vpaddq %ymm7,%ymm0,%ymm0 + + vpermq $0x2,%ymm3,%ymm10 + vpermq $0x2,%ymm4,%ymm6 + vpermq $0x2,%ymm0,%ymm7 + vpermq $0x2,%ymm12,%ymm8 + vpermq $0x2,%ymm2,%ymm9 + vpaddq %ymm10,%ymm3,%ymm3 + vpaddq %ymm6,%ymm4,%ymm4 + vpaddq %ymm7,%ymm0,%ymm0 + vpaddq %ymm8,%ymm12,%ymm12 + vpaddq %ymm9,%ymm2,%ymm2 + + + + vpsrlq $26,%ymm3,%ymm14 vpand %ymm5,%ymm3,%ymm3 vpaddq %ymm14,%ymm4,%ymm4 @@ -1777,31 +1802,6 @@ vpand %ymm5,%ymm3,%ymm3 vpaddq %ymm14,%ymm4,%ymm4 - - - - vpsrldq $8,%ymm2,%ymm9 - vpsrldq $8,%ymm0,%ymm7 - vpsrldq $8,%ymm1,%ymm8 - vpsrldq $8,%ymm3,%ymm10 - vpsrldq $8,%ymm4,%ymm6 - vpaddq %ymm9,%ymm2,%ymm2 - vpaddq %ymm7,%ymm0,%ymm0 - vpaddq %ymm8,%ymm1,%ymm1 - vpaddq %ymm10,%ymm3,%ymm3 - vpaddq %ymm6,%ymm4,%ymm4 - - vpermq $0x2,%ymm2,%ymm9 - vpermq $0x2,%ymm0,%ymm7 - vpermq $0x2,%ymm1,%ymm8 - vpermq $0x2,%ymm3,%ymm10 - vpermq $0x2,%ymm4,%ymm6 - vpaddq %ymm9,%ymm2,%ymm2 - vpaddq %ymm7,%ymm0,%ymm0 - vpaddq %ymm8,%ymm1,%ymm1 - vpaddq %ymm10,%ymm3,%ymm3 - vpaddq %ymm6,%ymm4,%ymm4 - vmovd %xmm0,-112(%rdi) vmovd %xmm1,-108(%rdi) vmovd %xmm2,-104(%rdi)
diff --git a/third_party/boringssl/win-x86/crypto/poly1305/poly1305-x86.asm b/third_party/boringssl/win-x86/crypto/poly1305/poly1305-x86.asm index 3380c90..ca61027c 100644 --- a/third_party/boringssl/win-x86/crypto/poly1305/poly1305-x86.asm +++ b/third_party/boringssl/win-x86/crypto/poly1305/poly1305-x86.asm
@@ -1200,9 +1200,19 @@ paddq xmm1,xmm5 paddq xmm2,xmm6 L$017short_tail: + pshufd xmm6,xmm4,78 + pshufd xmm5,xmm3,78 + paddq xmm4,xmm6 + paddq xmm3,xmm5 + pshufd xmm6,xmm0,78 + pshufd xmm5,xmm1,78 + paddq xmm0,xmm6 + paddq xmm1,xmm5 + pshufd xmm6,xmm2,78 movdqa xmm5,xmm3 pand xmm3,xmm7 psrlq xmm5,26 + paddq xmm2,xmm6 paddq xmm5,xmm4 movdqa xmm6,xmm0 pand xmm0,xmm7 @@ -1230,24 +1240,14 @@ paddd xmm1,xmm5 pand xmm3,xmm7 paddd xmm4,xmm6 - pshufd xmm6,xmm0,78 - pshufd xmm5,xmm1,78 - paddd xmm0,xmm6 - pshufd xmm6,xmm2,78 - paddd xmm1,xmm5 - pshufd xmm5,xmm3,78 - paddd xmm2,xmm6 - pshufd xmm6,xmm4,78 - paddd xmm3,xmm5 - paddd xmm4,xmm6 L$013done: movd DWORD [edi-48],xmm0 movd DWORD [edi-44],xmm1 movd DWORD [edi-40],xmm2 movd DWORD [edi-36],xmm3 movd DWORD [edi-32],xmm4 -L$007nodata: mov esp,ebp +L$007nodata: pop edi pop esi pop ebx
diff --git a/third_party/boringssl/win-x86_64/crypto/poly1305/poly1305-x86_64.asm b/third_party/boringssl/win-x86_64/crypto/poly1305/poly1305-x86_64.asm index 65c9ac6..6d285b6 100644 --- a/third_party/boringssl/win-x86_64/crypto/poly1305/poly1305-x86_64.asm +++ b/third_party/boringssl/win-x86_64/crypto/poly1305/poly1305-x86_64.asm
@@ -1159,6 +1159,20 @@ + vpsrldq xmm9,xmm14,8 + vpsrldq xmm8,xmm13,8 + vpsrldq xmm6,xmm11,8 + vpsrldq xmm5,xmm10,8 + vpsrldq xmm7,xmm12,8 + vpaddq xmm13,xmm13,xmm8 + vpaddq xmm14,xmm14,xmm9 + vpaddq xmm10,xmm10,xmm5 + vpaddq xmm11,xmm11,xmm6 + vpaddq xmm12,xmm12,xmm7 + + + + vpsrlq xmm3,xmm13,26 vpand xmm13,xmm13,xmm15 vpaddq xmm14,xmm14,xmm3 @@ -1190,25 +1204,11 @@ vpand xmm13,xmm13,xmm15 vpaddq xmm14,xmm14,xmm3 - - - - vpsrldq xmm7,xmm12,8 - vpsrldq xmm5,xmm10,8 - vpsrldq xmm6,xmm11,8 - vpsrldq xmm8,xmm13,8 - vpsrldq xmm9,xmm14,8 - vpaddq xmm2,xmm12,xmm7 - vpaddq xmm0,xmm10,xmm5 - vpaddq xmm1,xmm11,xmm6 - vpaddq xmm3,xmm13,xmm8 - vpaddq xmm4,xmm14,xmm9 - - vmovd DWORD[(-112)+rdi],xmm0 - vmovd DWORD[(-108)+rdi],xmm1 - vmovd DWORD[(-104)+rdi],xmm2 - vmovd DWORD[(-100)+rdi],xmm3 - vmovd DWORD[(-96)+rdi],xmm4 + vmovd DWORD[(-112)+rdi],xmm10 + vmovd DWORD[(-108)+rdi],xmm11 + vmovd DWORD[(-104)+rdi],xmm12 + vmovd DWORD[(-100)+rdi],xmm13 + vmovd DWORD[(-96)+rdi],xmm14 vmovdqa xmm6,XMMWORD[80+r11] vmovdqa xmm7,XMMWORD[96+r11] vmovdqa xmm8,XMMWORD[112+r11] @@ -1851,6 +1851,31 @@ + vpsrldq ymm8,ymm12,8 + vpsrldq ymm9,ymm2,8 + vpsrldq ymm10,ymm3,8 + vpsrldq ymm6,ymm4,8 + vpsrldq ymm7,ymm0,8 + vpaddq ymm12,ymm12,ymm8 + vpaddq ymm2,ymm2,ymm9 + vpaddq ymm3,ymm3,ymm10 + vpaddq ymm4,ymm4,ymm6 + vpaddq ymm0,ymm0,ymm7 + + vpermq ymm10,ymm3,0x2 + vpermq ymm6,ymm4,0x2 + vpermq ymm7,ymm0,0x2 + vpermq ymm8,ymm12,0x2 + vpermq ymm9,ymm2,0x2 + vpaddq ymm3,ymm3,ymm10 + vpaddq ymm4,ymm4,ymm6 + vpaddq ymm0,ymm0,ymm7 + vpaddq ymm12,ymm12,ymm8 + vpaddq ymm2,ymm2,ymm9 + + + + vpsrlq ymm14,ymm3,26 vpand ymm3,ymm3,ymm5 vpaddq ymm4,ymm4,ymm14 @@ -1882,31 +1907,6 @@ vpand ymm3,ymm3,ymm5 vpaddq ymm4,ymm4,ymm14 - - - - vpsrldq ymm9,ymm2,8 - vpsrldq ymm7,ymm0,8 - vpsrldq ymm8,ymm1,8 - vpsrldq ymm10,ymm3,8 - vpsrldq ymm6,ymm4,8 - vpaddq ymm2,ymm2,ymm9 - vpaddq ymm0,ymm0,ymm7 - vpaddq ymm1,ymm1,ymm8 - vpaddq ymm3,ymm3,ymm10 - vpaddq ymm4,ymm4,ymm6 - - vpermq ymm9,ymm2,0x2 - vpermq ymm7,ymm0,0x2 - vpermq ymm8,ymm1,0x2 - vpermq ymm10,ymm3,0x2 - vpermq ymm6,ymm4,0x2 - vpaddq ymm2,ymm2,ymm9 - vpaddq ymm0,ymm0,ymm7 - vpaddq ymm1,ymm1,ymm8 - vpaddq ymm3,ymm3,ymm10 - vpaddq ymm4,ymm4,ymm6 - vmovd DWORD[(-112)+rdi],xmm0 vmovd DWORD[(-108)+rdi],xmm1 vmovd DWORD[(-104)+rdi],xmm2
diff --git a/third_party/closure_compiler/compile_js2.gypi b/third_party/closure_compiler/compile_js2.gypi index 191be65..9d231d9 100644 --- a/third_party/closure_compiler/compile_js2.gypi +++ b/third_party/closure_compiler/compile_js2.gypi
@@ -6,7 +6,8 @@ 'variables': { 'CLOSURE_DIR': '<(DEPTH)/third_party/closure_compiler', - 'EXTERNS_GYP': '<(CLOSURE_DIR)/externs/compiled_resources.gyp', + 'EXTERNS_GYP': '<(CLOSURE_DIR)/externs/compiled_resources2.gyp', + 'INTERFACES_GYP': '<(CLOSURE_DIR)/interfaces/compiled_resources2.gyp', 'default_source_file': '<(_target_name).js', 'source_files%': ['<(default_source_file)'], @@ -46,7 +47,7 @@ 'inputs': [ '<(CLOSURE_DIR)/compile_js2.gypi', '<(CLOSURE_DIR)/compile2.py', - '<(CLOSURE_DIR)/externs_js.gypi', + '<(CLOSURE_DIR)/include_js.gypi', '<(CLOSURE_DIR)/processor.py', '<(CLOSURE_DIR)/build/outputs.py', '<(CLOSURE_DIR)/compiler/compiler.jar',
diff --git a/third_party/closure_compiler/compiled_resources.gyp b/third_party/closure_compiler/compiled_resources.gyp index 9903f4a71..e7a8aeb 100644 --- a/third_party/closure_compiler/compiled_resources.gyp +++ b/third_party/closure_compiler/compiled_resources.gyp
@@ -21,20 +21,14 @@ 'type': 'none', 'dependencies': [ '../../chrome/browser/resources/bookmark_manager/js/compiled_resources.gyp:*', - '../../chrome/browser/resources/chromeos/braille_ime/compiled_resources.gyp:*', '../../chrome/browser/resources/chromeos/compiled_resources.gyp:*', - '../../chrome/browser/resources/chromeos/network_ui/compiled_resources.gyp:*', '../../chrome/browser/resources/extensions/compiled_resources.gyp:*', '../../chrome/browser/resources/help/compiled_resources.gyp:*', - '../../chrome/browser/resources/history/compiled_resources.gyp:*', '../../chrome/browser/resources/options/compiled_resources.gyp:*', '../../chrome/browser/resources/media_router/compiled_resources.gyp:*', - '../../chrome/browser/resources/md_downloads/compiled_resources.gyp:*', '../../chrome/browser/resources/md_extensions/compiled_resources.gyp:*', '../../chrome/browser/resources/md_history/compiled_resources.gyp:*', '../../chrome/browser/resources/ntp4/compiled_resources.gyp:*', - '../../chrome/browser/resources/settings/compiled_resources.gyp:*', - '../../chrome/browser/resources/uber/compiled_resources.gyp:*', '../../remoting/app_remoting_webapp_compile.gypi:*', '../../remoting/remoting_webapp_compile.gypi:*', '../../ui/file_manager/audio_player/js/compiled_resources.gyp:*', @@ -43,11 +37,6 @@ '../../ui/file_manager/gallery/js/compiled_resources.gyp:*', '../../ui/file_manager/image_loader/compiled_resources.gyp:*', '../../ui/file_manager/video_player/js/compiled_resources.gyp:*', - '../../ui/webui/resources/cr_elements/compiled_resources.gyp:*', - '../../ui/webui/resources/js/chromeos/compiled_resources.gyp:*', - '../../ui/webui/resources/js/chromeos/compiled_resources.gyp:*', - '../../ui/webui/resources/js/compiled_resources.gyp:*', - '../../ui/webui/resources/js/cr/ui/compiled_resources.gyp:*', ], }, ]
diff --git a/third_party/closure_compiler/compiled_resources2.gyp b/third_party/closure_compiler/compiled_resources2.gyp index bba863d..f04e090 100644 --- a/third_party/closure_compiler/compiled_resources2.gyp +++ b/third_party/closure_compiler/compiled_resources2.gyp
@@ -14,8 +14,14 @@ 'target_name': 'compile_all_resources', 'type': 'none', 'dependencies': [ + '<(DEPTH)/chrome/browser/resources/chromeos/braille_ime/compiled_resources2.gyp:*', + '<(DEPTH)/chrome/browser/resources/chromeos/network_ui/compiled_resources2.gyp:*', + '<(DEPTH)/chrome/browser/resources/history/compiled_resources2.gyp:*', '<(DEPTH)/chrome/browser/resources/md_downloads/compiled_resources2.gyp:*', '<(DEPTH)/chrome/browser/resources/settings/compiled_resources2.gyp:*', + '<(DEPTH)/chrome/browser/resources/uber/compiled_resources2.gyp:*', + '<(DEPTH)/ui/webui/resources/cr_elements/compiled_resources2.gyp:*', + '<(DEPTH)/ui/webui/resources/js/chromeos/compiled_resources2.gyp:*', '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:*', '<(DEPTH)/ui/webui/resources/js/cr/ui/compiled_resources2.gyp:*', ],
diff --git a/third_party/closure_compiler/compiler/compiler.jar b/third_party/closure_compiler/compiler/compiler.jar index 588d87f..698d3122 100644 --- a/third_party/closure_compiler/compiler/compiler.jar +++ b/third_party/closure_compiler/compiler/compiler.jar Binary files differ
diff --git a/third_party/closure_compiler/compiler_test.py b/third_party/closure_compiler/compiler_test.py index 36cf163..479fb73 100755 --- a/third_party/closure_compiler/compiler_test.py +++ b/third_party/closure_compiler/compiler_test.py
@@ -18,6 +18,7 @@ _ASSERT_JS = os.path.join(_RESOURCES_DIR, "assert.js") _CR_JS = os.path.join(_RESOURCES_DIR, "cr.js") _CR_UI_JS = os.path.join(_RESOURCES_DIR, "cr", "ui.js") +_PROMISE_RESOLVER_JS = os.path.join(_RESOURCES_DIR, "promise_resolver.js") _POLYMER_EXTERNS = os.path.join(_SRC_DIR, "third_party", "polymer", "v1_0", "components-chromium", "polymer-externs", "polymer.externs.js") @@ -31,7 +32,8 @@ class CompilerTest(unittest.TestCase): _ASSERT_DEFINITION = Processor(_ASSERT_JS).contents - _CR_DEFINE_DEFINITION = Processor(_CR_JS).contents + _CR_DEFINE_DEFINITION = (Processor(_PROMISE_RESOLVER_JS).contents + + Processor(_CR_JS).contents) _CR_UI_DECORATE_DEFINITION = Processor(_CR_UI_JS).contents def setUp(self):
diff --git a/third_party/closure_compiler/externs/compiled_resources.gyp b/third_party/closure_compiler/externs/compiled_resources.gyp deleted file mode 100644 index e1022b8..0000000 --- a/third_party/closure_compiler/externs/compiled_resources.gyp +++ /dev/null
@@ -1,72 +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. - -######################################################## -# NOTE: THIS FILE IS GENERATED. DO NOT EDIT IT! # -# Instead, run create_externs_gyp.py to regenerate it. # -######################################################## -{ - 'targets': [ - { - 'target_name': 'autofill_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'bookmark_manager_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'chrome_extensions', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'chrome_send', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'command_line_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'developer_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'file_manager_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'media_player_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'metrics_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'passwords_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'pending_compiler_externs', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'search_engines_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'settings_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'system_private', - 'includes': ['../externs_js.gypi'], - }, - { - 'target_name': 'users_private', - 'includes': ['../externs_js.gypi'], - }, - ], -}
diff --git a/third_party/closure_compiler/externs/compiled_resources2.gyp b/third_party/closure_compiler/externs/compiled_resources2.gyp new file mode 100644 index 0000000..9efbcea --- /dev/null +++ b/third_party/closure_compiler/externs/compiled_resources2.gyp
@@ -0,0 +1,88 @@ +# 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. + +######################################################## +# NOTE: THIS FILE IS GENERATED. DO NOT EDIT IT! # +# Instead, run create_include_gyp.py to regenerate it. # +######################################################## +{ + 'targets': [ + { + 'target_name': 'autofill_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'bluetooth', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'bluetooth_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'bookmark_manager_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'chrome_extensions', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'chrome_send', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'command_line_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'developer_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'file_manager_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'language_settings_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'management', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'media_player_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'metrics_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'networking_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'passwords_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'pending_compiler_externs', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'settings_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'system_private', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'users_private', + 'includes': ['../include_js.gypi'], + }, + ], +}
diff --git a/third_party/closure_compiler/externs_js.gypi b/third_party/closure_compiler/include_js.gypi similarity index 100% rename from third_party/closure_compiler/externs_js.gypi rename to third_party/closure_compiler/include_js.gypi
diff --git a/third_party/closure_compiler/externs/bluetooth_interface.js b/third_party/closure_compiler/interfaces/bluetooth_interface.js similarity index 100% rename from third_party/closure_compiler/externs/bluetooth_interface.js rename to third_party/closure_compiler/interfaces/bluetooth_interface.js
diff --git a/third_party/closure_compiler/externs/bluetooth_private_interface.js b/third_party/closure_compiler/interfaces/bluetooth_private_interface.js similarity index 100% rename from third_party/closure_compiler/externs/bluetooth_private_interface.js rename to third_party/closure_compiler/interfaces/bluetooth_private_interface.js
diff --git a/third_party/closure_compiler/interfaces/compiled_resources2.gyp b/third_party/closure_compiler/interfaces/compiled_resources2.gyp new file mode 100644 index 0000000..f02ee87e2 --- /dev/null +++ b/third_party/closure_compiler/interfaces/compiled_resources2.gyp
@@ -0,0 +1,28 @@ +# 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. + +######################################################## +# NOTE: THIS FILE IS GENERATED. DO NOT EDIT IT! # +# Instead, run create_include_gyp.py to regenerate it. # +######################################################## +{ + 'targets': [ + { + 'target_name': 'bluetooth_interface', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'bluetooth_private_interface', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'networking_private_interface', + 'includes': ['../include_js.gypi'], + }, + { + 'target_name': 'settings_private_interface', + 'includes': ['../include_js.gypi'], + }, + ], +}
diff --git a/third_party/closure_compiler/externs/networking_private_interface.js b/third_party/closure_compiler/interfaces/networking_private_interface.js similarity index 100% rename from third_party/closure_compiler/externs/networking_private_interface.js rename to third_party/closure_compiler/interfaces/networking_private_interface.js
diff --git a/third_party/closure_compiler/externs/settings_private_interface.js b/third_party/closure_compiler/interfaces/settings_private_interface.js similarity index 100% rename from third_party/closure_compiler/externs/settings_private_interface.js rename to third_party/closure_compiler/interfaces/settings_private_interface.js
diff --git a/third_party/closure_compiler/runner/runner.jar b/third_party/closure_compiler/runner/runner.jar index 80fbf49..cac47c10 100644 --- a/third_party/closure_compiler/runner/runner.jar +++ b/third_party/closure_compiler/runner/runner.jar Binary files differ
diff --git a/third_party/closure_compiler/tools/create_externs_gyp.py b/third_party/closure_compiler/tools/create_externs_gyp.py deleted file mode 100755 index 144a26c..0000000 --- a/third_party/closure_compiler/tools/create_externs_gyp.py +++ /dev/null
@@ -1,47 +0,0 @@ -#!/usr/bin/env python -# Copyright %d The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -# -# Usage: -# -# cd third_party/closure_compiler -# tools/create_externs_gyp.py > externs/compiled_resources.gyp - -from datetime import date -import os - - -_EXTERNS_TEMPLATE = """ -# Copyright %d The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -######################################################## -# NOTE: THIS FILE IS GENERATED. DO NOT EDIT IT! # -# Instead, run create_externs_gyp.py to regenerate it. # -######################################################## -{ - 'targets': [ - %s, - ], -}""".lstrip() - - -_TARGET_TEMPLATE = """ - { - 'target_name': '%s', - 'includes': ['../externs_js.gypi'], - }""" - - -def CreateExternsGyp(): - externs_dir = os.path.join(os.path.dirname(__file__), "..", "externs") - externs_files = [f for f in os.listdir(externs_dir) if f.endswith('.js')] - externs_files.sort() - targets = [_TARGET_TEMPLATE % f[:-3] for f in externs_files] - return _EXTERNS_TEMPLATE % (date.today().year, ",".join(targets).strip()) - - -if __name__ == "__main__": - print CreateExternsGyp()
diff --git a/third_party/closure_compiler/tools/create_include_gyp.py b/third_party/closure_compiler/tools/create_include_gyp.py new file mode 100755 index 0000000..2258e0ce --- /dev/null +++ b/third_party/closure_compiler/tools/create_include_gyp.py
@@ -0,0 +1,57 @@ +#!/usr/bin/env python +# 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. +# +# Usage: +# +# cd third_party/closure_compiler +# tools/create_include_gyp.py externs > externs/compiled_resources2.gyp +# tools/create_include_gyp.py interfaces > interfaces/compiled_resources2.gyp + +from datetime import date +import os +import sys + + +_INCLUDE_TEMPLATE = """ +# Copyright %d The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +######################################################## +# NOTE: THIS FILE IS GENERATED. DO NOT EDIT IT! # +# Instead, run create_include_gyp.py to regenerate it. # +######################################################## +{ + 'targets': [ + %s, + ], +}""".lstrip() + + +_TARGET_TEMPLATE = """ + { + 'target_name': '%s', + 'includes': ['../include_js.gypi'], + }""" + + +def CreateIncludeGyp(directory): + include_dir = os.path.join(os.path.dirname(__file__), "..", directory) + include_files = [f for f in os.listdir(include_dir) if f.endswith('.js')] + include_files.sort() + targets = [_TARGET_TEMPLATE % f[:-3] for f in include_files] + return _INCLUDE_TEMPLATE % (date.today().year, ",".join(targets).strip()) + + +def ShowUsageAndDie(): + print "usage: tools/create_include_gyp.py externs > externs/compiled_resources2.gyp" + sys.exit(1) + + +if __name__ == "__main__": + if len(sys.argv) != 2: + ShowUsageAndDie() + + print CreateIncludeGyp(sys.argv[1])
diff --git a/third_party/polymer/v1_0/chromium.patch b/third_party/polymer/v1_0/chromium.patch index 9b27dc9..a38a4d2 100644 --- a/third_party/polymer/v1_0/chromium.patch +++ b/third_party/polymer/v1_0/chromium.patch
@@ -23,3 +23,91 @@ }, removeCustomPropAssignment: function (cssText) { return cssText.replace(this._rx.customProp, '').replace(this._rx.mixinProp, ''); +diff --git a/components-chromium/paper-input/paper-input-addon-behavior-extracted.js b/components-chromium/paper-input/paper-input-addon-behavior-extracted.js +index d3e469c2..94313dd 100644 +--- a/components-chromium/paper-input/paper-input-addon-behavior-extracted.js ++++ b/components-chromium/paper-input/paper-input-addon-behavior-extracted.js +@@ -17,10 +17,10 @@ + /** + * The function called by `<paper-input-container>` when the input value or validity changes. + * @param {{ +- * inputElement: (Node|undefined), ++ * inputElement: (Element|undefined), + * value: (string|undefined), +- * invalid: (boolean|undefined) +- * }} state All properties are optional - ++ * invalid: boolean ++ * }} state - + * inputElement: The input element. + * value: The input value. + * invalid: True if the input value is invalid. +@@ -28,4 +28,4 @@ + update: function(state) { + } + +- }; +\ No newline at end of file ++ }; +diff --git a/components-chromium/paper-input/paper-input-char-counter-extracted.js b/comp +onents-chromium/paper-input/paper-input-char-counter-extracted.js +index 6577627..e5bb409 100644 +--- a/components-chromium/paper-input/paper-input-char-counter-extracted.js ++++ b/components-chromium/paper-input/paper-input-char-counter-extracted.js +@@ -12,6 +12,17 @@ Polymer({ + } + }, + ++ /** ++ * This overrides the update function in PaperInputAddonBehavior. ++ * @param {{ ++ * inputElement: (Element|undefined), ++ * value: (string|undefined), ++ * invalid: boolean ++ * }} state - ++ * inputElement: The input element. ++ * value: The input value. ++ * invalid: True if the input value is invalid. ++ */ + update: function(state) { + if (!state.inputElement) { + return; +@@ -20,11 +31,11 @@ Polymer({ + state.value = state.value || ''; + + // Account for the textarea's new lines. +- var str = state.value.replace(/(\r\n|\n|\r)/g, '--').length; ++ var str = state.value.replace(/(\r\n|\n|\r)/g, '--').length.toString(); + + if (state.inputElement.hasAttribute('maxlength')) { + str += '/' + state.inputElement.getAttribute('maxlength'); + } + this._charCounterStr = str; + } +- }); +\ No newline at end of file ++ }); +diff --git a/components-chromium/paper-input/paper-input-error-extracted.js b/components-chromium/paper-input/paper-input-error-extracted.js +index ac6fe00..fb45601 100644 +--- a/components-chromium/paper-input/paper-input-error-extracted.js ++++ b/components-chromium/paper-input/paper-input-error-extracted.js +@@ -16,7 +16,18 @@ Polymer({ + } + }, + ++ /** ++ * This overrides the update function in PaperInputAddonBehavior. ++ * @param {{ ++ * inputElement: (Element|undefined), ++ * value: (string|undefined), ++ * invalid: boolean ++ * }} state - ++ * inputElement: The input element. ++ * value: The input value. ++ * invalid: True if the input value is invalid. ++ */ + update: function(state) { + this._setInvalid(state.invalid); + } +- }); +\ No newline at end of file ++ });
diff --git a/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-addon-behavior-extracted.js b/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-addon-behavior-extracted.js index d3e469c2..94313dd 100644 --- a/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-addon-behavior-extracted.js +++ b/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-addon-behavior-extracted.js
@@ -17,10 +17,10 @@ /** * The function called by `<paper-input-container>` when the input value or validity changes. * @param {{ - * inputElement: (Node|undefined), + * inputElement: (Element|undefined), * value: (string|undefined), - * invalid: (boolean|undefined) - * }} state All properties are optional - + * invalid: boolean + * }} state - * inputElement: The input element. * value: The input value. * invalid: True if the input value is invalid. @@ -28,4 +28,4 @@ update: function(state) { } - }; \ No newline at end of file + };
diff --git a/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-char-counter-extracted.js b/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-char-counter-extracted.js index 6577627..e5bb409 100644 --- a/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-char-counter-extracted.js +++ b/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-char-counter-extracted.js
@@ -12,6 +12,17 @@ } }, + /** + * This overrides the update function in PaperInputAddonBehavior. + * @param {{ + * inputElement: (Element|undefined), + * value: (string|undefined), + * invalid: boolean + * }} state - + * inputElement: The input element. + * value: The input value. + * invalid: True if the input value is invalid. + */ update: function(state) { if (!state.inputElement) { return; @@ -20,11 +31,11 @@ state.value = state.value || ''; // Account for the textarea's new lines. - var str = state.value.replace(/(\r\n|\n|\r)/g, '--').length; + var str = state.value.replace(/(\r\n|\n|\r)/g, '--').length.toString(); if (state.inputElement.hasAttribute('maxlength')) { str += '/' + state.inputElement.getAttribute('maxlength'); } this._charCounterStr = str; } - }); \ No newline at end of file + });
diff --git a/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-error-extracted.js b/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-error-extracted.js index ac6fe00..fb45601 100644 --- a/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-error-extracted.js +++ b/third_party/polymer/v1_0/components-chromium/paper-input/paper-input-error-extracted.js
@@ -16,7 +16,18 @@ } }, + /** + * This overrides the update function in PaperInputAddonBehavior. + * @param {{ + * inputElement: (Element|undefined), + * value: (string|undefined), + * invalid: boolean + * }} state - + * inputElement: The input element. + * value: The input value. + * invalid: True if the input value is invalid. + */ update: function(state) { this._setInvalid(state.invalid); } - }); \ No newline at end of file + });
diff --git a/tools/android/loading/sandwich.py b/tools/android/loading/sandwich.py index 86d730f2..b4e2590 100755 --- a/tools/android/loading/sandwich.py +++ b/tools/android/loading/sandwich.py
@@ -477,8 +477,16 @@ logging.info('white-listing %s' % main_resource_request.url) whitelisted_urls.add(main_resource_request.url) for (first, second, reason) in deps: + # Work-around where the protocol may be none for an unclear reason yet. + # TODO(gabadie): Follow up on this with Clovis guys and possibly remove + # this work-around. + if not second.protocol: + logging.info('ignoring %s (no protocol)' % second.url) + continue # Ignore data protocols. if not second.protocol.startswith('http'): + logging.info('ignoring %s (`%s` is not HTTP{,S} protocol)' % ( + second.url, second.protocol)) continue if (first.request_id == main_resource_request.request_id and reason == 'parser' and second.url not in whitelisted_urls):
diff --git a/tools/battor_agent/BUILD.gn b/tools/battor_agent/BUILD.gn index 1a057f3..41f89e7d 100644 --- a/tools/battor_agent/BUILD.gn +++ b/tools/battor_agent/BUILD.gn
@@ -27,6 +27,7 @@ "battor_connection.h", "battor_connection_impl.cc", "battor_connection_impl.h", + "battor_error.cc", "battor_error.h", "battor_finder.cc", "battor_finder.h",
diff --git a/tools/battor_agent/battor_agent.gyp b/tools/battor_agent/battor_agent.gyp index d55e1f79..abbb5cf7 100644 --- a/tools/battor_agent/battor_agent.gyp +++ b/tools/battor_agent/battor_agent.gyp
@@ -34,6 +34,7 @@ 'battor_connection.h', 'battor_connection_impl.cc', 'battor_connection_impl.h', + 'battor_error.cc', 'battor_error.h', 'battor_finder.cc', 'battor_finder.h',
diff --git a/tools/battor_agent/battor_agent_bin.cc b/tools/battor_agent/battor_agent_bin.cc index 7b256ae..1c00b47 100644 --- a/tools/battor_agent/battor_agent_bin.cc +++ b/tools/battor_agent/battor_agent_bin.cc
@@ -18,8 +18,8 @@ // 5) If the last command was successful, PowerTracingAgent waits for the // duration of the trace // 6) When the tracing should end, PowerTracingAgent records the clock sync -// start timestamp and sends the subprocess the RecordClockSyncMark <marker>' -// message via STDIN. +// start timestamp and sends the subprocess the +// 'RecordClockSyncMark <marker>' message via STDIN. // 7) PowerTracingAgent waits for the subprocess to write a line to STDOUT // ('Done.' if successful, some error message otherwise) // 8) If the last command was successful, PowerTracingAgent records the clock @@ -41,6 +41,7 @@ #include "base/command_line.h" #include "base/location.h" #include "base/logging.h" +#include "base/strings/string_tokenizer.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread.h" #include "tools/battor_agent/battor_agent.h" @@ -49,6 +50,8 @@ using std::endl; +namespace battor { + namespace { const char kIoThreadName[] = "BattOr IO Thread"; @@ -75,14 +78,14 @@ "\n"; void PrintSupportsExplicitClockSync() { - std::cout << battor::BattOrAgent::SupportsExplicitClockSync() << endl; + std::cout << BattOrAgent::SupportsExplicitClockSync() << endl; } -// Checks if an error occurred and, if it did, prints the error and exits -// with an error code. -void CheckError(battor::BattOrError error) { - if (error != battor::BATTOR_ERROR_NONE) - LOG(FATAL) << "Fatal error when communicating with the BattOr: " << error; +// Logs the error and exits with an error code. +void HandleError(battor::BattOrError error) { + if (error != BATTOR_ERROR_NONE) + LOG(FATAL) << "Fatal error when communicating with the BattOr: " + << BattOrErrorToString(error); } // Prints an error message and exits due to a required thread failing to start. @@ -92,8 +95,6 @@ } // namespace -namespace battor { - // Wrapper class containing all state necessary for an independent binary to // use a BattOrAgent to communicate with a BattOr. class BattOrAgentBin : public BattOrAgent::Listener { @@ -129,8 +130,20 @@ break; } else if (cmd == "SupportsExplicitClockSync") { PrintSupportsExplicitClockSync(); - } else if (cmd == "RecordClockSyncMarker") { - // TODO(charliea): Write RecordClockSyncMarker. + } else if (cmd.find("RecordClockSyncMarker") != std::string::npos) { + base::StringTokenizer tokenizer(cmd, " "); + + std::vector<std::string> tokens; + while (tokenizer.GetNext()) + tokens.push_back(tokenizer.token()); + + if (tokens.size() != 2 || tokens[0] != "RecordClockSyncMarker") { + std::cout << "Invalid RecordClockSyncMarker command." << endl; + std::cout << kUsage << endl; + continue; + } + + RecordClockSyncMarker(tokens[1]); } else if (cmd == "Exit") { break; } else { @@ -155,7 +168,7 @@ io_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(&BattOrAgentBin::CreateAgent, base::Unretained(this), path)); - CheckError(AwaitResult()); + AwaitResult(); } // Performs any cleanup necessary after the BattOr binary is done running. @@ -163,19 +176,22 @@ io_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(&BattOrAgentBin::DeleteAgent, base::Unretained(this))); - CheckError(AwaitResult()); + AwaitResult(); } void StartTracing() { io_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(&BattOrAgent::StartTracing, base::Unretained(agent_.get()))); - CheckError(AwaitResult()); + AwaitResult(); } void OnStartTracingComplete(BattOrError error) override { - error_ = error; - std::cout << "Done." << endl; + if (error == BATTOR_ERROR_NONE) + std::cout << "Done." << endl; + else + HandleError(error); + done_.Signal(); } @@ -183,26 +199,35 @@ io_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(&BattOrAgent::StopTracing, base::Unretained(agent_.get()))); - CheckError(AwaitResult()); + AwaitResult(); } void OnStopTracingComplete(const std::string& trace, BattOrError error) override { - error_ = error; - - if (error == BATTOR_ERROR_NONE) + if (error == BATTOR_ERROR_NONE) { std::cout << trace; - - std::cout << "Done." << endl; + std::cout << "Done." << endl; + } else { + HandleError(error); + } done_.Signal(); } + void RecordClockSyncMarker(const std::string& marker) { + io_thread_.task_runner()->PostTask( + FROM_HERE, base::Bind(&BattOrAgent::RecordClockSyncMarker, + base::Unretained(agent_.get()), marker)); + AwaitResult(); + } + void OnRecordClockSyncMarkerComplete(BattOrError error) override { - // TODO(charliea): Implement RecordClockSyncMarker for this binary. This - // will probably involve reading an external file for the actual sample - // number to clock sync ID map. - NOTREACHED(); + if (error == BATTOR_ERROR_NONE) + std::cout << "Done." << endl; + else + HandleError(error); + + done_.Signal(); } // Postable task for creating the BattOrAgent. Because the BattOrAgent has @@ -223,7 +248,6 @@ agent_.reset(new BattOrAgent(path, this, file_thread_.task_runner(), ui_thread_.task_runner())); - error_ = BATTOR_ERROR_NONE; done_.Signal(); } @@ -231,26 +255,20 @@ // CreateAgent() above regarding why this is necessary. void DeleteAgent() { agent_.reset(nullptr); - error_ = BATTOR_ERROR_NONE; done_.Signal(); } // Waits until the previously executed command has finished executing. - BattOrError AwaitResult() { + void AwaitResult() { if (!done_.TimedWait( base::TimeDelta::FromSeconds(kBattOrCommandTimeoutSeconds))) - return BATTOR_ERROR_TIMEOUT; - - return error_; + HandleError(BATTOR_ERROR_TIMEOUT); } private: // Event signaled when an async task has finished executing. base::WaitableEvent done_; - // The error from the last async command that finished. - BattOrError error_; - // Threads needed for serial communication. base::Thread io_thread_; base::Thread file_thread_;
diff --git a/tools/battor_agent/battor_error.cc b/tools/battor_agent/battor_error.cc new file mode 100644 index 0000000..fa25fe5a --- /dev/null +++ b/tools/battor_agent/battor_error.cc
@@ -0,0 +1,31 @@ +// 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 "tools/battor_agent/battor_error.h" + +#include "base/logging.h" + +namespace battor { + +std::string BattOrErrorToString(BattOrError error) { + switch (error) { + case BATTOR_ERROR_NONE: + return "NONE"; + case BATTOR_ERROR_CONNECTION_FAILED: + return "CONNECTION FAILED"; + case BATTOR_ERROR_TIMEOUT: + return "TIMEOUT"; + case BATTOR_ERROR_SEND_ERROR: + return "SEND ERROR"; + case BATTOR_ERROR_RECEIVE_ERROR: + return "RECEIVE ERROR"; + case BATTOR_ERROR_UNEXPECTED_MESSAGE: + return "UNEXPECTED MESSAGE"; + } + + NOTREACHED(); + return std::string(); +} + +} // namespace battor
diff --git a/tools/battor_agent/battor_error.h b/tools/battor_agent/battor_error.h index 2e5efac8..fef354a 100644 --- a/tools/battor_agent/battor_error.h +++ b/tools/battor_agent/battor_error.h
@@ -5,17 +5,22 @@ #ifndef TOOLS_BATTOR_AGENT_BATTOR_ERROR_H_ #define TOOLS_BATTOR_AGENT_BATTOR_ERROR_H_ +#include <string> + namespace battor { // A BattOrError is an error that occurs when communicating with a BattOr. enum BattOrError { - BATTOR_ERROR_NONE = 0, - BATTOR_ERROR_CONNECTION_FAILED = 1, - BATTOR_ERROR_TIMEOUT = 2, - BATTOR_ERROR_SEND_ERROR = 3, - BATTOR_ERROR_RECEIVE_ERROR = 4, - BATTOR_ERROR_UNEXPECTED_MESSAGE = 5, + BATTOR_ERROR_NONE, + BATTOR_ERROR_CONNECTION_FAILED, + BATTOR_ERROR_TIMEOUT, + BATTOR_ERROR_SEND_ERROR, + BATTOR_ERROR_RECEIVE_ERROR, + BATTOR_ERROR_UNEXPECTED_MESSAGE, }; + +std::string BattOrErrorToString(BattOrError error); + } #endif // TOOLS_BATTOR_AGENT_BATTOR_ERROR_H_
diff --git a/tools/gn/BUILD.gn b/tools/gn/BUILD.gn index 683c8eb..b27ae70 100644 --- a/tools/gn/BUILD.gn +++ b/tools/gn/BUILD.gn
@@ -24,6 +24,8 @@ "builder.h", "builder_record.cc", "builder_record.h", + "bundle_data_target_generator.cc", + "bundle_data_target_generator.h", "c_include_iterator.cc", "c_include_iterator.h", "command_args.cc", @@ -110,6 +112,8 @@ "ninja_binary_target_writer.h", "ninja_build_writer.cc", "ninja_build_writer.h", + "ninja_bundle_data_target_writer.cc", + "ninja_bundle_data_target_writer.h", "ninja_copy_target_writer.cc", "ninja_copy_target_writer.h", "ninja_group_target_writer.cc",
diff --git a/tools/gn/action_values.cc b/tools/gn/action_values.cc index 819ead10..a7ce83d 100644 --- a/tools/gn/action_values.cc +++ b/tools/gn/action_values.cc
@@ -15,7 +15,10 @@ void ActionValues::GetOutputsAsSourceFiles( const Target* target, std::vector<SourceFile>* result) const { - if (target->output_type() == Target::COPY_FILES || + if (target->output_type() == Target::BUNDLE_DATA) { + // The bundle_data target has no output, the real output will be generated + // by the create_bundle target. + } else if (target->output_type() == Target::COPY_FILES || target->output_type() == Target::ACTION_FOREACH) { // Copy and foreach applies the outputs to the sources. SubstitutionWriter::ApplyListToSources(
diff --git a/tools/gn/bundle_data_target_generator.cc b/tools/gn/bundle_data_target_generator.cc new file mode 100644 index 0000000..81a9b959 --- /dev/null +++ b/tools/gn/bundle_data_target_generator.cc
@@ -0,0 +1,94 @@ +// 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 "tools/gn/bundle_data_target_generator.h" + +#include "tools/gn/parse_tree.h" +#include "tools/gn/scope.h" +#include "tools/gn/substitution_type.h" +#include "tools/gn/target.h" +#include "tools/gn/value.h" +#include "tools/gn/variables.h" + +BundleDataTargetGenerator::BundleDataTargetGenerator( + Target* target, + Scope* scope, + const FunctionCallNode* function_call, + Err* err) : TargetGenerator(target, scope, function_call, err) {} + +BundleDataTargetGenerator::~BundleDataTargetGenerator() {} + +void BundleDataTargetGenerator::DoRun() { + target_->set_output_type(Target::BUNDLE_DATA); + + if (!FillSources()) + return; + if (!FillOutputs()) + return; + + if (target_->sources().empty()) { + *err_ = Err(function_call_, "Empty sources for bundle_data target." + "You have to specify at least one file in the \"sources\"."); + return; + } + if (target_->action_values().outputs().list().size() != 1) { + *err_ = Err(function_call_, + "Target bundle_data must have exactly one ouput.", + "You must specify exactly one value in the \"output\" array for the" + "destination\ninto the generated bundle (see \"gn help bundle_data\"). " + "If there are multiple\nsources to copy, use source expansion (see " + "\"gn help source_expansion\")."); + return; + } +} + +bool BundleDataTargetGenerator::FillOutputs() { + const Value* value = scope_->GetValue(variables::kOutputs, true); + if (!value) + return true; + + SubstitutionList& outputs = target_->action_values().outputs(); + if (!outputs.Parse(*value, err_)) + return false; + + // Check the substitutions used are valid for this purpose. + for (SubstitutionType type : outputs.required_types()) { + if (!IsValidBundleDataSubstitution(type)) { + *err_ = Err(value->origin(), "Invalid substitution type.", + "The substitution " + std::string(kSubstitutionNames[type]) + + " isn't valid for something\n" + "operating on a bundle_data file such as this."); + return false; + } + } + + // Validate that outputs are in the bundle. + CHECK(outputs.list().size() == value->list_value().size()); + for (size_t i = 0; i < outputs.list().size(); i++) { + if (!EnsureSubstitutionIsInBundleDir(outputs.list()[i], + value->list_value()[i])) + return false; + } + + return true; +} + +bool BundleDataTargetGenerator::EnsureSubstitutionIsInBundleDir( + const SubstitutionPattern& pattern, + const Value& original_value) { + if (pattern.ranges().empty()) { + // Pattern is empty, error out (this prevents weirdness below). + *err_ = Err(original_value, "This has an empty value in it."); + return false; + } + + if (SubstitutionIsInBundleDir(pattern.ranges()[0].type)) + return true; + + *err_ = Err(original_value, + "File is not inside bundle directory.", + "The given file should be in the output directory. Normally you\n" + "would specify {{bundle_resources_dir}} or such substitution."); + return false; +}
diff --git a/tools/gn/bundle_data_target_generator.h b/tools/gn/bundle_data_target_generator.h new file mode 100644 index 0000000..49bcc45 --- /dev/null +++ b/tools/gn/bundle_data_target_generator.h
@@ -0,0 +1,33 @@ +// 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 TOOLS_GN_BUNDLE_DATA_TARGET_GENERATOR_H_ +#define TOOLS_GN_BUNDLE_DATA_TARGET_GENERATOR_H_ + +#include "base/macros.h" +#include "tools/gn/target_generator.h" + +// Populates a Target with the values from a bundle_data rule. +class BundleDataTargetGenerator : public TargetGenerator { + public: + BundleDataTargetGenerator(Target* target, + Scope* scope, + const FunctionCallNode* function_call, + Err* err); + ~BundleDataTargetGenerator() override; + + protected: + void DoRun() override; + + private: + bool FillOutputs(); + + bool EnsureSubstitutionIsInBundleDir( + const SubstitutionPattern& pattern, + const Value& original_value); + + DISALLOW_COPY_AND_ASSIGN(BundleDataTargetGenerator); +}; + +#endif // TOOLS_GN_BUNDLE_DATA_TARGET_GENERATOR_H_
diff --git a/tools/gn/command_desc.cc b/tools/gn/command_desc.cc index 27b1d01..801055b0 100644 --- a/tools/gn/command_desc.cc +++ b/tools/gn/command_desc.cc
@@ -684,7 +684,8 @@ target->output_type() != Target::GROUP && target->output_type() != Target::COPY_FILES && target->output_type() != Target::ACTION && - target->output_type() != Target::ACTION_FOREACH; + target->output_type() != Target::ACTION_FOREACH && + target->output_type() != Target::BUNDLE_DATA; // Generally we only want to display toolchains on labels when the toolchain // is different than the default one for this target (which we always print
diff --git a/tools/gn/copy_target_generator.h b/tools/gn/copy_target_generator.h index 81fbb69e..b05855f 100644 --- a/tools/gn/copy_target_generator.h +++ b/tools/gn/copy_target_generator.h
@@ -21,8 +21,6 @@ void DoRun() override; private: - void FillDestDir(); - DISALLOW_COPY_AND_ASSIGN(CopyTargetGenerator); };
diff --git a/tools/gn/function_toolchain.cc b/tools/gn/function_toolchain.cc index 3e272c9..9eeae98 100644 --- a/tools/gn/function_toolchain.cc +++ b/tools/gn/function_toolchain.cc
@@ -816,8 +816,8 @@ subst_validator = &IsValidCopySubstitution; subst_output_validator = &IsValidCopySubstitution; } else { - subst_validator = &IsValidToolSubstutition; - subst_output_validator = &IsValidToolSubstutition; + subst_validator = &IsValidToolSubstitution; + subst_output_validator = &IsValidToolSubstitution; } scoped_ptr<Tool> tool(new Tool);
diff --git a/tools/gn/functions.cc b/tools/gn/functions.cc index fb02fa8b..37b3401 100644 --- a/tools/gn/functions.cc +++ b/tools/gn/functions.cc
@@ -803,6 +803,7 @@ INSERT_FUNCTION(Action, true) INSERT_FUNCTION(ActionForEach, true) + INSERT_FUNCTION(BundleData, true) INSERT_FUNCTION(Copy, true) INSERT_FUNCTION(Executable, true) INSERT_FUNCTION(Group, true)
diff --git a/tools/gn/functions.h b/tools/gn/functions.h index b746515..1341720 100644 --- a/tools/gn/functions.h +++ b/tools/gn/functions.h
@@ -80,6 +80,15 @@ const std::vector<Value>& args, Err* err); +extern const char kBundleData[]; +extern const char kBundleData_HelpShort[]; +extern const char kBundleData_Help[]; +Value RunBundleData(Scope* scope, + const FunctionCallNode* function, + const std::vector<Value>& args, + BlockNode* block, + Err* err); + extern const char kConfig[]; extern const char kConfig_HelpShort[]; extern const char kConfig_Help[];
diff --git a/tools/gn/functions_target.cc b/tools/gn/functions_target.cc index b04fea8..7a293c7c 100644 --- a/tools/gn/functions_target.cc +++ b/tools/gn/functions_target.cc
@@ -243,6 +243,27 @@ block, err); } +// bundle_data ----------------------------------------------------------------- + +const char kBundleData[] = "bundle_data"; +const char kBundleData_HelpShort[] = + "bundle_data: Declare a target without output."; +const char kBundleData_Help[] = + "bundle_data: Declare a target without output.\n" + "\n" + " This target type allows to declare data that is required at runtime.\n" + " It is used to inform \"create_bundle\" targets of the files to copy\n" + " into generated bundle, see \"gn help create_bundle\" for help.\n"; + +Value RunBundleData(Scope* scope, + const FunctionCallNode* function, + const std::vector<Value>& args, + BlockNode* block, + Err* err) { + return ExecuteGenericTarget(functions::kBundleData, scope, function, args, + block, err); +} + // copy ------------------------------------------------------------------------ const char kCopy[] = "copy";
diff --git a/tools/gn/gn.gyp b/tools/gn/gn.gyp index 85754e08..3cd81e3 100644 --- a/tools/gn/gn.gyp +++ b/tools/gn/gn.gyp
@@ -24,6 +24,8 @@ 'builder.h', 'builder_record.cc', 'builder_record.h', + 'bundle_data_target_generator.cc', + 'bundle_data_target_generator.h', 'c_include_iterator.cc', 'c_include_iterator.h', 'command_args.cc', @@ -110,6 +112,8 @@ 'ninja_binary_target_writer.h', 'ninja_build_writer.cc', 'ninja_build_writer.h', + 'ninja_bundle_data_target_writer.cc', + 'ninja_bundle_data_target_writer.h', 'ninja_copy_target_writer.cc', 'ninja_copy_target_writer.h', 'ninja_group_target_writer.cc',
diff --git a/tools/gn/ninja_bundle_data_target_writer.cc b/tools/gn/ninja_bundle_data_target_writer.cc new file mode 100644 index 0000000..67b5a10e --- /dev/null +++ b/tools/gn/ninja_bundle_data_target_writer.cc
@@ -0,0 +1,19 @@ +// 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 "tools/gn/ninja_bundle_data_target_writer.h" + +#include "tools/gn/output_file.h" + +NinjaBundleDataTargetWriter::NinjaBundleDataTargetWriter(const Target* target, + std::ostream& out) + : NinjaTargetWriter(target, out) {} + +NinjaBundleDataTargetWriter::~NinjaBundleDataTargetWriter() {} + +void NinjaBundleDataTargetWriter::Run() { + std::vector<OutputFile> files; + files.push_back(WriteInputDepsStampAndGetDep(std::vector<const Target*>())); + WriteStampForTarget(files, std::vector<OutputFile>()); +}
diff --git a/tools/gn/ninja_bundle_data_target_writer.h b/tools/gn/ninja_bundle_data_target_writer.h new file mode 100644 index 0000000..c097f67 --- /dev/null +++ b/tools/gn/ninja_bundle_data_target_writer.h
@@ -0,0 +1,23 @@ +// 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 TOOLS_GN_NINJA_BUNDLE_DATA_TARGET_WRITER_H_ +#define TOOLS_GN_NINJA_BUNDLE_DATA_TARGET_WRITER_H_ + +#include "base/macros.h" +#include "tools/gn/ninja_target_writer.h" + +// Writes a .ninja file for a bundle_data target type. +class NinjaBundleDataTargetWriter : public NinjaTargetWriter { + public: + NinjaBundleDataTargetWriter(const Target* target, std::ostream& out); + ~NinjaBundleDataTargetWriter() override; + + void Run() override; + + private: + DISALLOW_COPY_AND_ASSIGN(NinjaBundleDataTargetWriter); +}; + +#endif // TOOLS_GN_NINJA_BUNDLE_DATA_TARGET_WRITER_H_
diff --git a/tools/gn/ninja_target_writer.cc b/tools/gn/ninja_target_writer.cc index 9f19b2b0..f4de7f2 100644 --- a/tools/gn/ninja_target_writer.cc +++ b/tools/gn/ninja_target_writer.cc
@@ -13,6 +13,7 @@ #include "tools/gn/filesystem_utils.h" #include "tools/gn/ninja_action_target_writer.h" #include "tools/gn/ninja_binary_target_writer.h" +#include "tools/gn/ninja_bundle_data_target_writer.h" #include "tools/gn/ninja_copy_target_writer.h" #include "tools/gn/ninja_group_target_writer.h" #include "tools/gn/ninja_utils.h" @@ -57,7 +58,10 @@ std::stringstream file; // Call out to the correct sub-type of writer. - if (target->output_type() == Target::COPY_FILES) { + if (target->output_type() == Target::BUNDLE_DATA) { + NinjaBundleDataTargetWriter writer(target, file); + writer.Run(); + } else if (target->output_type() == Target::COPY_FILES) { NinjaCopyTargetWriter writer(target, file); writer.Run(); } else if (target->output_type() == Target::ACTION ||
diff --git a/tools/gn/substitution_list.h b/tools/gn/substitution_list.h index 7273ece..eaf8a61 100644 --- a/tools/gn/substitution_list.h +++ b/tools/gn/substitution_list.h
@@ -30,7 +30,7 @@ const std::vector<SubstitutionPattern>& list() const { return list_; } - // Returns a list of all substitution types used by the patterns in thist + // Returns a list of all substitution types used by the patterns in this // list, with the exception of LITERAL. const std::vector<SubstitutionType>& required_types() const { return required_types_;
diff --git a/tools/gn/substitution_type.cc b/tools/gn/substitution_type.cc index b92c756..93a32bd 100644 --- a/tools/gn/substitution_type.cc +++ b/tools/gn/substitution_type.cc
@@ -46,6 +46,11 @@ "{{output_extension}}", // SUBSTITUTION_OUTPUT_EXTENSION "{{solibs}}", // SUBSTITUTION_SOLIBS + "{{bundle_root_dir}}", // SUBSTITUTION_BUNDLE_ROOT_DIR + "{{bundle_resources_dir}}", // SUBSTITUTION_BUNDLE_RESOURCES_DIR + "{{bundle_executable_dir}}", // SUBSTITUTION_BUNDLE_EXECUTABLE_DIR + "{{bundle_plugins_dir}}", // SUBSTITUTION_BUNDLE_PLUGINS_DIR + "{{response_file_name}}", // SUBSTITUTION_RSP_FILE_NAME }; @@ -89,6 +94,11 @@ "output_extension", // SUBSTITUTION_OUTPUT_EXTENSION "solibs", // SUBSTITUTION_SOLIBS + "bundle_root_dir", // SUBSTITUTION_BUNDLE_ROOT_DIR + "bundle_resources_dir", // SUBSTITUTION_BUNDLE_RESOURCES_DIR + "bundle_executable_dir", // SUBSTITUTION_BUNDLE_EXECUTABLE_DIR + "bundle_plugins_dir", // SUBSTITUTION_BUNDLE_PLUGINS_DIR + "rspfile", // SUBSTITUTION_RSP_FILE_NAME }; @@ -116,6 +126,24 @@ type == SUBSTITUTION_TARGET_OUT_DIR; } +bool SubstitutionIsInBundleDir(SubstitutionType type) { + return type == SUBSTITUTION_BUNDLE_ROOT_DIR || + type == SUBSTITUTION_BUNDLE_RESOURCES_DIR || + type == SUBSTITUTION_BUNDLE_EXECUTABLE_DIR || + type == SUBSTITUTION_BUNDLE_PLUGINS_DIR; +} + +bool IsValidBundleDataSubstitution(SubstitutionType type) { + return type == SUBSTITUTION_LITERAL || + type == SUBSTITUTION_SOURCE_NAME_PART || + type == SUBSTITUTION_SOURCE_FILE_PART || + type == SUBSTITUTION_SOURCE_ROOT_RELATIVE_DIR || + type == SUBSTITUTION_BUNDLE_ROOT_DIR || + type == SUBSTITUTION_BUNDLE_RESOURCES_DIR || + type == SUBSTITUTION_BUNDLE_EXECUTABLE_DIR || + type == SUBSTITUTION_BUNDLE_PLUGINS_DIR; +} + bool IsValidSourceSubstitution(SubstitutionType type) { return type == SUBSTITUTION_LITERAL || type == SUBSTITUTION_SOURCE || @@ -127,7 +155,7 @@ type == SUBSTITUTION_SOURCE_OUT_DIR; } -bool IsValidToolSubstutition(SubstitutionType type) { +bool IsValidToolSubstitution(SubstitutionType type) { return type == SUBSTITUTION_LITERAL || type == SUBSTITUTION_OUTPUT || type == SUBSTITUTION_LABEL || @@ -140,7 +168,7 @@ } bool IsValidCompilerSubstitution(SubstitutionType type) { - return IsValidToolSubstutition(type) || + return IsValidToolSubstitution(type) || IsValidSourceSubstitution(type) || type == SUBSTITUTION_SOURCE || type == SUBSTITUTION_ASMFLAGS || @@ -155,12 +183,12 @@ bool IsValidCompilerOutputsSubstitution(SubstitutionType type) { // All tool types except "output" (which would be infinitely recursive). - return (IsValidToolSubstutition(type) && type != SUBSTITUTION_OUTPUT) || + return (IsValidToolSubstitution(type) && type != SUBSTITUTION_OUTPUT) || IsValidSourceSubstitution(type); } bool IsValidLinkerSubstitution(SubstitutionType type) { - return IsValidToolSubstutition(type) || + return IsValidToolSubstitution(type) || type == SUBSTITUTION_LINKER_INPUTS || type == SUBSTITUTION_LINKER_INPUTS_NEWLINE || type == SUBSTITUTION_LDFLAGS || @@ -176,7 +204,7 @@ } bool IsValidCopySubstitution(SubstitutionType type) { - return IsValidToolSubstutition(type) || + return IsValidToolSubstitution(type) || type == SUBSTITUTION_SOURCE; } @@ -187,7 +215,7 @@ for (size_t i = 0; i < types.size(); i++) { if (!IsValidSourceSubstitution(types[i])) { *err = Err(origin, "Invalid substitution type.", - "The substitution " + std::string(kSubstitutionNames[i]) + + "The substitution " + std::string(kSubstitutionNames[types[i]]) + " isn't valid for something\n" "operating on a source file such as this."); return false;
diff --git a/tools/gn/substitution_type.h b/tools/gn/substitution_type.h index dfe9b54..96ae33a 100644 --- a/tools/gn/substitution_type.h +++ b/tools/gn/substitution_type.h
@@ -11,7 +11,7 @@ class ParseNode; // Keep kSubstitutionNames, kSubstitutionNinjaNames and the -// IsValid*Substutition functions in sync if you change anything here. +// IsValid*Substitution functions in sync if you change anything here. enum SubstitutionType { SUBSTITUTION_LITERAL = 0, @@ -59,6 +59,12 @@ SUBSTITUTION_OUTPUT_EXTENSION, // {{output_extension}} SUBSTITUTION_SOLIBS, // {{solibs}} + // Valid for bundle_data targets. + SUBSTITUTION_BUNDLE_ROOT_DIR, // {{bundle_root_dir}} + SUBSTITUTION_BUNDLE_RESOURCES_DIR, // {{bundle_resources_dir}} + SUBSTITUTION_BUNDLE_EXECUTABLE_DIR, // {{bundle_executable_dir}} + SUBSTITUTION_BUNDLE_PLUGINS_DIR, // {{bundle_plugins_dir}} + // Used only for the args of actions. SUBSTITUTION_RSP_FILE_NAME, // {{response_file_name}} @@ -93,13 +99,19 @@ // Returns true if the given substitution pattern references the output // directory. This is used to check strings that begin with a substitution to -// verify that the produce a file in the output directory. +// verify that they produce a file in the output directory. bool SubstitutionIsInOutputDir(SubstitutionType type); +// Returns true if the given substitution pattern references the bundle +// directory. This is used to check strings that begin with a substitution to +// verify that they produce a file in the bundle directory. +bool SubstitutionIsInBundleDir(SubstitutionType type); + // Returns true if the given substitution is valid for the named purpose. +bool IsValidBundleDataSubstitution(SubstitutionType type); bool IsValidSourceSubstitution(SubstitutionType type); // Both compiler and linker tools. -bool IsValidToolSubstutition(SubstitutionType type); +bool IsValidToolSubstitution(SubstitutionType type); bool IsValidCompilerSubstitution(SubstitutionType type); bool IsValidCompilerOutputsSubstitution(SubstitutionType type); bool IsValidLinkerSubstitution(SubstitutionType type);
diff --git a/tools/gn/substitution_writer.cc b/tools/gn/substitution_writer.cc index 2af2e18..99abced1e 100644 --- a/tools/gn/substitution_writer.cc +++ b/tools/gn/substitution_writer.cc
@@ -69,7 +69,7 @@ " {{source_name_part}}\n" " The filename part of the source file with no directory or\n" " extension. This will generally be used for specifying a\n" - " transformation from a soruce file to a destination file with the\n" + " transformation from a source file to a destination file with the\n" " same name but different extension.\n" " \"//foo/bar/baz.txt\" => \"baz\"\n" "\n" @@ -174,7 +174,7 @@ for (const auto& pattern : list.list()) { CHECK(pattern.ranges().size() == 1 && pattern.ranges()[0].type == SUBSTITUTION_LITERAL) - << "The substitution patterm \"" + << "The substitution pattern \"" << pattern.AsString() << "\" was expected to be a literal with no {{substitutions}}."; const std::string& literal = pattern.ranges()[0].literal;
diff --git a/tools/gn/substitution_writer.h b/tools/gn/substitution_writer.h index f50fb8db..a450bbb 100644 --- a/tools/gn/substitution_writer.h +++ b/tools/gn/substitution_writer.h
@@ -115,7 +115,7 @@ std::vector<OutputFile>* output); // Like ApplyListToSource but applies the list to all sources and replaces - // rather than appesnds the output (this produces the complete output). + // rather than appends the output (this produces the complete output). static void ApplyListToSources( const Settings* settings, const SubstitutionList& list,
diff --git a/tools/gn/target.cc b/tools/gn/target.cc index 594b368..9435d47 100644 --- a/tools/gn/target.cc +++ b/tools/gn/target.cc
@@ -222,6 +222,8 @@ return "Action"; case ACTION_FOREACH: return "ActionForEach"; + case BUNDLE_DATA: + return "Bundle data"; default: return ""; } @@ -479,6 +481,7 @@ bool check_tool_outputs = false; switch (output_type_) { case GROUP: + case BUNDLE_DATA: case SOURCE_SET: case COPY_FILES: case ACTION:
diff --git a/tools/gn/target.h b/tools/gn/target.h index f49fdba..9afd0fa 100644 --- a/tools/gn/target.h +++ b/tools/gn/target.h
@@ -44,6 +44,7 @@ COPY_FILES, ACTION, ACTION_FOREACH, + BUNDLE_DATA, }; enum DepsIterationType {
diff --git a/tools/gn/target_generator.cc b/tools/gn/target_generator.cc index b1ed1ea3..0a833a0 100644 --- a/tools/gn/target_generator.cc +++ b/tools/gn/target_generator.cc
@@ -9,6 +9,7 @@ #include "tools/gn/action_target_generator.h" #include "tools/gn/binary_target_generator.h" #include "tools/gn/build_settings.h" +#include "tools/gn/bundle_data_target_generator.h" #include "tools/gn/config.h" #include "tools/gn/copy_target_generator.h" #include "tools/gn/err.h" @@ -87,7 +88,11 @@ target->set_defined_from(function_call); // Create and call out to the proper generator. - if (output_type == functions::kCopy) { + if (output_type == functions::kBundleData) { + BundleDataTargetGenerator generator( + target.get(), scope, function_call, err); + generator.Run(); + } else if (output_type == functions::kCopy) { CopyTargetGenerator generator(target.get(), scope, function_call, err); generator.Run(); } else if (output_type == functions::kAction) {
diff --git a/tools/gn/toolchain.cc b/tools/gn/toolchain.cc index 2a70358..ee8e7e8 100644 --- a/tools/gn/toolchain.cc +++ b/tools/gn/toolchain.cc
@@ -151,9 +151,10 @@ return Toolchain::TYPE_ALINK; case Target::SOURCE_SET: return TYPE_STAMP; - case Target::COPY_FILES: case Target::ACTION: case Target::ACTION_FOREACH: + case Target::BUNDLE_DATA: + case Target::COPY_FILES: return TYPE_STAMP; default: NOTREACHED();
diff --git a/tools/gn/toolchain.h b/tools/gn/toolchain.h index b49153b..bcc70c06 100644 --- a/tools/gn/toolchain.h +++ b/tools/gn/toolchain.h
@@ -99,7 +99,7 @@ // Returns the tool that produces the final output for the given target type. // This isn't necessarily the tool you would expect. For copy target, this - // will return the stamp tool ionstead since the final output of a copy + // will return the stamp tool instead since the final output of a copy // target is to stamp the set of copies done so there is one output. static ToolType GetToolTypeForTargetFinalOutput(const Target* target); const Tool* GetToolForTargetFinalOutput(const Target* target) const;
diff --git a/tools/gn/variables.cc b/tools/gn/variables.cc index c0bf6cb..0242904 100644 --- a/tools/gn/variables.cc +++ b/tools/gn/variables.cc
@@ -824,7 +824,8 @@ "\n" " For action and action_foreach targets, inputs should be the inputs to\n" " script that don't vary. These should be all .py files that the script\n" - " uses via imports (the main script itself will be an implcit dependency\n" + " uses via imports (the main script itself will be an implicit dependency" + "\n" " of the action so need not be listed).\n" "\n" " For action targets, inputs and sources are treated the same, but from\n"
diff --git a/tools/ipc_fuzzer/fuzzer/fuzzer.cc b/tools/ipc_fuzzer/fuzzer/fuzzer.cc index ab5d932..f546e27 100644 --- a/tools/ipc_fuzzer/fuzzer/fuzzer.cc +++ b/tools/ipc_fuzzer/fuzzer/fuzzer.cc
@@ -1825,14 +1825,9 @@ RandInRange(ui::LatencyInfo::kMaxInputCoordinates + 1)); ui::LatencyInfo::InputCoordinate input_coordinates[ui::LatencyInfo::kMaxInputCoordinates]; - uint32_t event_timestamps_size = static_cast<uint32_t>( - RandInRange(ui::LatencyInfo::kMaxCoalescedEventTimestamps + 1)); - double event_timestamps[ui::LatencyInfo::kMaxCoalescedEventTimestamps]; if (!FuzzParamArray( input_coordinates, input_coordinates_size, fuzzer)) return false; - if (!FuzzParamArray(event_timestamps, event_timestamps_size, fuzzer)) - return false; if (!FuzzParam(&trace_id, fuzzer)) return false; if (!FuzzParam(&terminated, fuzzer)) @@ -1842,9 +1837,6 @@ for (size_t i = 0; i < input_coordinates_size; i++) { latency.AddInputCoordinate(input_coordinates[i]); } - for (size_t i = 0; i < event_timestamps_size; i++) { - latency.AddCoalescedEventTimestamp(event_timestamps[i]); - } *p = latency; return true;
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index bee5e70d..4a54f4a 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -19079,6 +19079,19 @@ </summary> </histogram> +<histogram name="Media.Audio.InputBufferSizeWasChangedAudioWorkedMac" + enum="BooleanChanged"> + <owner>henrika@chromium.org</owner> + <summary> + Indicates if the size of the audio unit's IO buffer was changed when + starting an input audio stream. Sampled each time an AUAudioInputStream + instance is closed, i.e., we know that input audio has started as it should + when this value is stored. Can be compared with + Media.Audio.InputBufferSizeWasChangedMac which is only added when input + audio fails to start. + </summary> +</histogram> + <histogram name="Media.Audio.InputBufferSizeWasChangedMac" enum="BooleanSuccess"> <owner>henrika@chromium.org</owner> @@ -19118,7 +19131,19 @@ </summary> </histogram> -<histogram name="Media.Audio.InputStartWasDeferredMac" enum="BooleanSuccess"> +<histogram name="Media.Audio.InputStartWasDeferredAudioWorkedMac" + enum="BooleanDeferred"> + <owner>henrika@chromium.org</owner> + <summary> + Indicates if audio capturing started with a small delay or not. Sampled each + time an AUAudioInputStream instance is closed, i.e., we know that input + audio has started as it should when this value is stored. Can be compared + with Media.Audio.InputStartWasDeferredMac which is only added when input + audio fails to start. + </summary> +</histogram> + +<histogram name="Media.Audio.InputStartWasDeferredMac" enum="BooleanDeferred"> <owner>henrika@chromium.org</owner> <summary> Indicates if audio capturing started with a small delay or not. Only sampled @@ -26579,6 +26604,14 @@ </summary> </histogram> +<histogram name="Net.QuicReadAvailableData.NullStream" enum="BooleanNullStream"> + <owner>rtenneti@chromium.org</owner> + <summary> + The number of times QuicHttpStream's stream_ is a nullptr before + IsDoneReading() is called. + </summary> +</histogram> + <histogram name="Net.QuicServerInfo.DiskCacheLoadTime" units="ms"> <owner>rtenneti@chromium.org</owner> <summary>Time spent to load QUIC server information from disk cache.</summary> @@ -50399,6 +50432,14 @@ </summary> </histogram> +<histogram name="Sync.DeviceCount"> + <owner>skym@chromium.org</owner> + <summary> + The largest number of active syncing devices known to any profile. May be 0 + when there are no signed in/syncing profiles open. + </summary> +</histogram> + <histogram name="Sync.DeviceIdMismatchDetails" enum="DeviceIdMismatch"> <owner>pavely@chromium.org</owner> <summary> @@ -57684,6 +57725,15 @@ </summary> </histogram> +<histogram name="WebRTC.Video.Screenshare.BitrateSentInKbps" units="kbps"> + <owner>sprang@chromium.org</owner> + <summary> + The number of sent bits per second for a sent screenshare stream. Recorded + when a stream is removed. The total number of bytes is divided by the time + the video stream exists. + </summary> +</histogram> + <histogram name="WebRTC.Video.Screenshare.EncodeTimeInMs" units="ms"> <owner>sprang@chromium.org</owner> <summary> @@ -57692,6 +57742,45 @@ </summary> </histogram> +<histogram name="WebRTC.Video.Screenshare.FecBitrateSentInKbps" units="kbps"> + <owner>sprang@chromium.org</owner> + <summary> + The number of sent FEC bits per second for a sent screenshare stream. + Recorded when a stream is removed. The total number of bytes is divided by + the time the video stream exists. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.FirPacketsReceivedPerMinute" + units="packets/minute"> + <owner>sprang@chromium.org</owner> + <summary> + The number of received RTCP FIR packets per minute for a sent screenshare + stream. Recorded when a stream is removed. The total number of packets is + divided by the time the video stream exists. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.FramesPerDrop" + units="sent/dropped ratio"> + <owner>sprang@chromium.org</owner> + <summary> + Ratio of sent frames to dropped frames at the encoder. The value is reported + when a stream is removed and is calculated as the total number frames sent + divided by the number of dropped frames. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.FramesPerOvershoot" + units="sent/overshoot ratio"> + <owner>sprang@chromium.org</owner> + <summary> + Ratio of sent frames to number of re-encoded frames (due to target bitrate + overshoot). The value is reported when a stream is removed and is calculated + as the total number frames sent divided by the number of re-encoded frames. + </summary> +</histogram> + <histogram name="WebRTC.Video.Screenshare.InputHeightInPixels" units="pixels"> <owner>sprang@chromium.org</owner> <summary> @@ -57717,6 +57806,59 @@ </summary> </histogram> +<histogram name="WebRTC.Video.Screenshare.Layer0"> + <owner>sprang@chromium.org</owner> + <summary> + Stats for the lower layer (TL0) of a screenshare stream in conference mode. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.Layer1"> + <owner>sprang@chromium.org</owner> + <summary> + Stats for the higher layer (TL1) of a screenshare stream in conference mode. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.MediaBitrateSentInKbps" units="kbps"> + <owner>sprang@chromium.org</owner> + <summary> + The number of sent media payload bits per second for a sent screenshare + stream. Recorded when a stream is removed. The total number of bytes is + divided by the time the video stream exists. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.NackPacketsReceivedPerMinute" + units="packets/minute"> + <owner>sprang@chromium.org</owner> + <summary> + The number of received RTCP NACK packets per minute for a sent screenshare + stream. Recorded when a stream is removed. The total number of packets is + divided by the time the video stream exists. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.PaddingBitrateSentInKbps" + units="kbps"> + <owner>sprang@chromium.org</owner> + <summary> + The number of sent padding bits per second for a sent screenshare stream. + Recorded when a stream is removed. The total number of bytes is divided by + the time the video stream exists. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.PliPacketsReceivedPerMinute" + units="packets/minute"> + <owner>sprang@chromium.org</owner> + <summary> + The number of received RTCP PLI packets per minute for a sent screenshare + stream. Recorded when a stream is removed. The total number of packets is + divided by the time the video stream exists. + </summary> +</histogram> + <histogram name="WebRTC.Video.Screenshare.QualityLimitedResolutionDownscales" units="downscales"> <owner>sprang@chromium.org</owner> @@ -57736,6 +57878,25 @@ </summary> </histogram> +<histogram name="WebRTC.Video.Screenshare.RetransmittedBitrateSentInKbps" + units="kbps"> + <owner>sprang@chromium.org</owner> + <summary> + The number of retransmitted bits per second for a sent screenshare stream. + Recorded when a stream is removed. The total number of bytes is divided by + the time the video stream exists. + </summary> +</histogram> + +<histogram name="WebRTC.Video.Screenshare.RtxBitrateSentInKbps" units="kbps"> + <owner>sprang@chromium.org</owner> + <summary> + The number of sent bits over RTX per second for a sent screenshare stream. + Recorded when a stream is removed. The total number of bytes is divided by + the time the video stream exists. + </summary> +</histogram> + <histogram name="WebRTC.Video.Screenshare.SendSideDelayInMs" units="ms"> <owner>sprang@chromium.org</owner> <summary> @@ -57777,6 +57938,14 @@ </summary> </histogram> +<histogram name="WebRTC.Video.Screenshare.SentPacketsLostInPercent" units="%"> + <owner>sprang@chromium.org</owner> + <summary> + Percentage of sent packets lost for a sent screenshare stream. Recorded when + a stream is removed. + </summary> +</histogram> + <histogram name="WebRTC.Video.Screenshare.SentWidthInPixels" units="pixels"> <owner>sprang@chromium.org</owner> <summary> @@ -57785,6 +57954,15 @@ </summary> </histogram> +<histogram name="WebRTC.Video.Screenshare.UniqueNackRequestsReceivedInPercent" + units="%"> + <owner>sprang@chromium.org</owner> + <summary> + Percentage of unique RTCP NACK requests that are received in response to a + sent screenshare stream. Recorded when a stream is removed. + </summary> +</histogram> + <histogram name="WebRTC.Video.SendSideDelayInMs" units="ms"> <owner>asapersson@chromium.org</owner> <summary> @@ -59846,6 +60024,11 @@ <int value="1" label="Data Reduction Proxy"/> </enum> +<enum name="BooleanDeferred" type="int"> + <int value="0" label="Not deferred"/> + <int value="1" label="Deferred"/> +</enum> + <enum name="BooleanDelete" type="int"> <int value="0" label="Ignored"/> <int value="1" label="Deleted"/> @@ -60046,6 +60229,11 @@ <int value="1" label="Missing data in disk cache"/> </enum> +<enum name="BooleanNullStream" type="int"> + <int value="0" label="Stream is not a nullptr"/> + <int value="1" label="Stream is a nullptr"/> +</enum> + <enum name="BooleanNullVisitor" type="int"> <int value="0" label="Connection's visitor is not a nullptr"/> <int value="1" label="Connection's visitor is a nullptr"/> @@ -65502,7 +65690,8 @@ <int value="641" label="GCM_SEND"/> <int value="642" label="SERIAL_CONNECT"/> <int value="643" label="SERIAL_DISCONNECT"/> - <int value="644" label="MEDIAGALLERIES_GETALLMEDIAFILESYSTEMMETADATA"/> + <int value="644" + label="DELETED_MEDIAGALLERIES_GETALLMEDIAFILESYSTEMMETADATA"/> <int value="645" label="FIRSTRUNPRIVATE_GETLOCALIZEDSTRINGS"/> <int value="646" label="FIRSTRUNPRIVATE_LAUNCHTUTORIAL"/> <int value="647" label="SOCKETS_UDP_SETPAUSED"/> @@ -65579,7 +65768,8 @@ <int value="717" label="FILESYSTEMPROVIDERINTERNAL_UNMOUNTREQUESTEDSUCCESS"/> <int value="718" label="DELETED_FILESYSTEMPROVIDERINTERNAL_UNMOUNTREQUESTEDERROR"/> - <int value="719" label="MEDIAGALLERIES_DROPPERMISSIONFORMEDIAFILESYSTEM"/> + <int value="719" + label="DELETED_MEDIAGALLERIES_DROPPERMISSIONFORMEDIAFILESYSTEM"/> <int value="720" label="WEBCAMPRIVATE_SET"/> <int value="721" label="WEBCAMPRIVATE_RESET"/> <int value="722" label="WEBCAMPRIVATE_GET"/> @@ -65759,8 +65949,8 @@ label="EASYUNLOCKPRIVATE_CONNECTTOBLUETOOTHSERVICEINSECURELY"/> <int value="885" label="MEDIAGALLERIES_ADDGALLERYWATCH"/> <int value="886" label="MEDIAGALLERIES_REMOVEGALLERYWATCH"/> - <int value="887" label="MEDIAGALLERIES_GETALLGALLERYWATCH"/> - <int value="888" label="MEDIAGALLERIES_REMOVEALLGALLERYWATCH"/> + <int value="887" label="DELETED_MEDIAGALLERIES_GETALLGALLERYWATCH"/> + <int value="888" label="DELETED_MEDIAGALLERIES_REMOVEALLGALLERYWATCH"/> <int value="889" label="MANAGEMENT_GETSELF"/> <int value="890" label="APP_CURRENTWINDOWINTERNAL_SETVISIBLEONALLWORKSPACES"/> <int value="891" label="EASYUNLOCKPRIVATE_GETSIGNINCHALLENGE"/> @@ -67869,6 +68059,15 @@ <int value="1249" label="CSSAtRuleApply"/> <int value="1250" label="CSSSelectorPseudoAny"/> <int value="1251" label="PannerNodeSetVelocity"/> + <int value="1252" label="DocumentAllItemNoArguments"/> + <int value="1253" label="DocumentAllItemNamed"/> + <int value="1254" label="DocumentAllItemIndexed"/> + <int value="1255" label="DocumentAllItemIndexedWithNonNumber"/> + <int value="1256" label="DocumentAllLegacyCallNoArguments"/> + <int value="1257" label="DocumentAllLegacyCallNamed"/> + <int value="1258" label="DocumentAllLegacyCallIndexed"/> + <int value="1259" label="DocumentAllLegacyCallIndexedWithNonNumber"/> + <int value="1260" label="DocumentAllLegacyCallTwoArguments"/> </enum> <enum name="FetchRequestMode" type="int"> @@ -73510,7 +73709,8 @@ <int value="8" label="Gallery removed from WebUI"/> <int value="9" label="Preferences initialized"/> <int value="10" label="Preferences initialization failed"/> - <int value="11" label="GetAllMediaFileSystemMetadata API invocations"/> + <int value="11" + label="GetAllMediaFileSystemMetadata API invocations (obsolete)"/> <int value="12" label="GetMetadata API invocations"/> <int value="13" label="AddUserSelectedFolder API invocations"/> <int value="14" label="StartMediaScan API invocations (obsolete)"/> @@ -73522,9 +73722,10 @@ <int value="20" label="Gallery removed from AddScanResults dialog (obsolete)"/> <int value="21" label="Gallery removed from permission dialog"/> - <int value="22" label="DropPermissionForMediaFileSystem API invocations"/> - <int value="23" label="GetAllGalleryWatch API invocations"/> - <int value="24" label="RemoveAllGalleryWatch API invocations"/> + <int value="22" + label="DropPermissionForMediaFileSystem API invocations (obsolete)"/> + <int value="23" label="GetAllGalleryWatch API invocations (obsolete)"/> + <int value="24" label="RemoveAllGalleryWatch API invocations (obsolete)"/> <int value="25" label="iTunes file system used this session"/> <int value="26" label="Picasa file system used this session"/> <int value="27" label="iPhoto file system used this session"/> @@ -88624,6 +88825,24 @@ <affected-histogram name="SB2.MalwareInterstitialTimeTakeMeBack"/> </histogram_suffixes> +<histogram_suffixes name="ScreenshareLayerStats" separator="."> + <suffix name="FrameRate" + label="Frames per second sent, in fps. The value is reported when a + stream is removed and is calculated as the total number of + frames in this layer, divided by the duration of the call."/> + <suffix name="Qp" + label="Average quantizer (qp) of frames sent. The value is reported + when a stream is removed and is calculated, for this layer, as + the sum of all qp values divided the number of frames."/> + <suffix name="TargetBitrate" + label="Average target bitrate in kbps. The value is reported when a + stream is removed and is calculated as the sum of all target + bitrates for this layer (sampled after frame has been encoded) + divided by the total number of frames for this layer."/> + <affected-histogram name="WebRTC.Video.Screenshare.Layer0"/> + <affected-histogram name="WebRTC.Video.Screenshare.Layer1"/> +</histogram_suffixes> + <histogram_suffixes name="ScrollUpdateHandledThread"> <affected-histogram name="Event.Latency.ScrollUpdate.HandledToRendererSwap"/> <suffix name="Main" label="ScrollUpdate handled on main thread"/>
diff --git a/tools/metrics/rappor/rappor.xml b/tools/metrics/rappor/rappor.xml index 1c2a281ad..49aec766 100644 --- a/tools/metrics/rappor/rappor.xml +++ b/tools/metrics/rappor/rappor.xml
@@ -581,6 +581,22 @@ </summary> </rappor-metric> +<rappor-metric name="Media.OriginUrl.MSE.Insecure" type="ETLD_PLUS_ONE"> + <owner>wolenetz@chromium.org</owner> + <summary> + The domain and registry of the URL that loads an HTML5 media player using + Media Source Extensions (MSE) from an insecure origin. + </summary> +</rappor-metric> + +<rappor-metric name="Media.OriginUrl.MSE.Secure" type="ETLD_PLUS_ONE"> + <owner>wolenetz@chromium.org</owner> + <summary> + The domain and registry of the URL that loads an HTML5 media player using + Media Source Extensions (MSE) from a potentially trustworthy origin. + </summary> +</rappor-metric> + <rappor-metric name="Media.OriginUrl.SRC" type="ETLD_PLUS_ONE"> <owner>xhwang@chromium.org</owner> <summary>
diff --git a/tools/perf/docs/perf_bot_sheriffing.md b/tools/perf/docs/perf_bot_sheriffing.md index d2bd7c9..6b072b8 100644 --- a/tools/perf/docs/perf_bot_sheriffing.md +++ b/tools/perf/docs/perf_bot_sheriffing.md
@@ -9,7 +9,6 @@ * [Handling Test Failures](#testfailures) * [Handling Device and Bot Failures](#botfailures) * [Follow up on failures](#followup) - * [Triaging Data Stoppage Alerts](#datastoppage) ###<a name="chromiumperf"></a> Keeping the chromium.perf waterfall green @@ -205,45 +204,7 @@ should be ongoing when the sheriff is not working on a Pri-1 issue. Here is the [list of Pri-2 bugs that have not been pinged in a week](https://code.google.com/p/chromium/issues/list?can=2&q=label:Performance-BotHealth%20label:Pri-2%20modified-before:today-7&sort=modified) -###<a name="datastoppage"></a> Triaging data stoppage alerts - -Data stoppage alerts are listed on the -[perf dashboard alerts page](https://chromeperf.appspot.com/alerts). Whenever -the dashboard is monitoring a metric, and that metric stops sending data, an -alert is fired. Some of these alerts are expected: - - * When a telemetry benchmark is disabled, we get a data stoppage alert. - Check the [code for the benchmark](https://code.google.com/p/chromium/codesearch#chromium/src/tools/perf/benchmarks/) - to see if it has been disabled, and if so associate the alert with the - bug for the disable. - * When a bot has been turned down. These should be announced to - perf-sheriffs@chromium.org, but if you can't find the bot on the waterfall - and you didn't see the announcement, double check in the speed infra chat. - Ideally these will be associated with the bug for the bot turndown, but - it's okay to mark them invalid if you can't find the bug. - -If there doesn't seem to be a valid reason for the alert, file a bug on it -using the perf dashboard, and cc [the owner](http://go/perf-owners). Then do -some diagnosis: - - * Look at the perf dashboard graph to see the last revision we got data for, - and note that in the bug. Click on the `buildbot stdio` link in the tooltip - to find the buildbot status page for the last good build, and increment - the build number to get the first build with no data, and note that in the - bug as well. Check for any changes to the test in the revision range. - * Go to the buildbot status page of the bot which should be running the test. - Is it running the test? If not, note that in the bug. - * If it is running the test and the test is failing, diagnose as a test - failure. - * If it is running the test and the test is passing, check the `json.output` - link on the buildbot status page for the test. This is the data the test - sent to the perf dashboard. Are there null values? Sometimes it lists a - reason as well. Please put your finding in the bug. - <!-- Unresolved issues: 1. Do perf sheriffs watch the bisect waterfall? 2. Do perf sheriffs watch the internal clank waterfall? -3. Do we use sheriff-o-matic? -4. Should we add some list of bugs that bot sheriffs could help fix, to improve -their workflow? -->
diff --git a/tools/perf/docs/perf_regression_sheriffing.md b/tools/perf/docs/perf_regression_sheriffing.md index ed8e24a8..8f45b682 100644 --- a/tools/perf/docs/perf_regression_sheriffing.md +++ b/tools/perf/docs/perf_regression_sheriffing.md
@@ -8,6 +8,7 @@ ## Key Responsibilities * [Triage Regressions on the Perf Dashboard](#triage) + * [Triaging Data Stoppage Alerts](#datastoppage) * [Follow up on Performance Regressions](#followup) * [Give Feedback on our Infrastructure](#feedback) @@ -72,6 +73,41 @@ bisects as you feel are necessary to investigate; [give feedback](#feedback) below if you feel that is not the case. +###<a name="datastoppage"></a> Triaging data stoppage alerts + +Data stoppage alerts are listed on the +[perf dashboard alerts page](https://chromeperf.appspot.com/alerts). Whenever +the dashboard is monitoring a metric, and that metric stops sending data, an +alert is fired. Some of these alerts are expected: + + * When a telemetry benchmark is disabled, we get a data stoppage alert. + Check the [code for the benchmark](https://code.google.com/p/chromium/codesearch#chromium/src/tools/perf/benchmarks/) + to see if it has been disabled, and if so associate the alert with the + bug for the disable. + * When a bot has been turned down. These should be announced to + perf-sheriffs@chromium.org, but if you can't find the bot on the waterfall + and you didn't see the announcement, double check in the speed infra chat. + Ideally these will be associated with the bug for the bot turndown, but + it's okay to mark them invalid if you can't find the bug. + +If there doesn't seem to be a valid reason for the alert, file a bug on it +using the perf dashboard, and cc [the owner](http://go/perf-owners). Then do +some diagnosis: + + * Look at the perf dashboard graph to see the last revision we got data for, + and note that in the bug. Click on the `buildbot stdio` link in the tooltip + to find the buildbot status page for the last good build, and increment + the build number to get the first build with no data, and note that in the + bug as well. Check for any changes to the test in the revision range. + * Go to the buildbot status page of the bot which should be running the test. + Is it running the test? If not, note that in the bug. + * If it is running the test and the test is failing, diagnose as a test + failure. + * If it is running the test and the test is passing, check the `json.output` + link on the buildbot status page for the test. This is the data the test + sent to the perf dashboard. Are there null values? Sometimes it lists a + reason as well. Please put your finding in the bug. + ###<a name="followup"></a> Follow up on Performance Regressions During your shift, you should try to follow up on each of the bugs you filed.
diff --git a/tools/perf/find_dependencies b/tools/perf/find_dependencies index 54abf67..ec824a2 100755 --- a/tools/perf/find_dependencies +++ b/tools/perf/find_dependencies
@@ -3,21 +3,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. - -# Temporary hack to remove stale pyc file (crbug.com/590762) -import os -_STALE_PYC_FILE = os.path.join( - os.path.dirname(__file__), '..', '..', 'third_party', 'catapult', - 'tracing', '__init__.pyc') - -if os.path.exists(_STALE_PYC_FILE): - print 'Stale file %s exists, try removing it.' % _STALE_PYC_FILE - try: - os.remove(_STALE_PYC_FILE) - except OSError: - print 'Failed to remove %s' % _STALE_PYC_FILE - pass - import sys from core import find_dependencies
diff --git a/tools/perf/page_sets/data/tough_canvas_cases.json b/tools/perf/page_sets/data/tough_canvas_cases.json index 8fc8f1d..e859517a 100644 --- a/tools/perf/page_sets/data/tough_canvas_cases.json +++ b/tools/perf/page_sets/data/tough_canvas_cases.json
@@ -18,7 +18,6 @@ "http://www.chiptune.com/starfield/starfield.html", "http://jarrodoverson.com/static/demos/particleSystem/", "http://www.effectgames.com/demos/canvascycle/", - "http://www.thewildernessdowntown.com/", "http://spielzeugz.de/html5/liquid-particles.html", "http://hakim.se/experiments/html5/magnetic/02/", "http://ie.microsoft.com/testdrive/Performance/LetItSnow/",
diff --git a/tools/perf/page_sets/tough_canvas_cases.py b/tools/perf/page_sets/tough_canvas_cases.py index ea20f32f..cd6a30b 100644 --- a/tools/perf/page_sets/tough_canvas_cases.py +++ b/tools/perf/page_sets/tough_canvas_cases.py
@@ -61,7 +61,6 @@ 'http://www.chiptune.com/starfield/starfield.html', 'http://jarrodoverson.com/static/demos/particleSystem/', 'http://www.effectgames.com/demos/canvascycle/', - 'http://www.thewildernessdowntown.com/', 'http://spielzeugz.de/html5/liquid-particles.html', 'http://hakim.se/experiments/html5/magnetic/02/', 'http://ie.microsoft.com/testdrive/Performance/LetItSnow/',
diff --git a/tools/valgrind/gtest_exclude/content_browsertests.gtest-drmemory.txt b/tools/valgrind/gtest_exclude/content_browsertests.gtest-drmemory.txt index fcbaf975..676da4d82 100644 --- a/tools/valgrind/gtest_exclude/content_browsertests.gtest-drmemory.txt +++ b/tools/valgrind/gtest_exclude/content_browsertests.gtest-drmemory.txt
@@ -61,3 +61,6 @@ # https://crbug.com/577796 WebRtcMediaRecorderTest.MediaRecorderPeerConnection + +# https://crbug.com/592320 +SitePerProcessBrowserTest.SubframeGestureEventRouting
diff --git a/ui/compositor/layer_owner.cc b/ui/compositor/layer_owner.cc index c918081..f406d884 100644 --- a/ui/compositor/layer_owner.cc +++ b/ui/compositor/layer_owner.cc
@@ -48,6 +48,7 @@ new_layer->SetFillsBoundsOpaquely(old_layer->fills_bounds_opaquely()); new_layer->SetFillsBoundsCompletely(old_layer->FillsBoundsCompletely()); new_layer->SetSubpixelPositionOffset(old_layer->subpixel_position_offset()); + new_layer->SetLayerInverted(old_layer->layer_inverted()); if (old_layer->type() == LAYER_SOLID_COLOR) new_layer->SetColor(old_layer->GetTargetColor()); SkRegion* alpha_shape = old_layer->alpha_shape();
diff --git a/ui/compositor/layer_owner_unittest.cc b/ui/compositor/layer_owner_unittest.cc index 8b6bf50..b3c08f3 100644 --- a/ui/compositor/layer_owner_unittest.cc +++ b/ui/compositor/layer_owner_unittest.cc
@@ -144,6 +144,20 @@ EXPECT_EQ(nullptr, layer_copy->GetCompositor()); } +TEST(LayerOwnerTest, InvertPropertyRemainSameWithRecreateLayer) { + LayerOwner owner; + Layer* layer = new Layer; + owner.SetLayer(layer); + + layer->SetLayerInverted(true); + scoped_ptr<Layer> old_layer1 = owner.RecreateLayer(); + EXPECT_EQ(old_layer1->layer_inverted(), owner.layer()->layer_inverted()); + + old_layer1->SetLayerInverted(false); + scoped_ptr<Layer> old_layer2 = owner.RecreateLayer(); + EXPECT_EQ(old_layer2->layer_inverted(), owner.layer()->layer_inverted()); +} + TEST_F(LayerOwnerTestWithCompositor, RecreateRootLayerWithCompositor) { LayerOwner owner; Layer* layer = new Layer;
diff --git a/ui/events/event.cc b/ui/events/event.cc index 21add836..ca6704b6 100644 --- a/ui/events/event.cc +++ b/ui/events/event.cc
@@ -844,6 +844,9 @@ return false; } +KeyEvent::KeyEvent(EventType type, base::TimeDelta time_stamp, int flags) + : Event(type, time_stamp, flags) {} + KeyEvent::KeyEvent(const base::NativeEvent& native_event) : Event(native_event, EventTypeFromNative(native_event),
diff --git a/ui/events/event.h b/ui/events/event.h index 35999bf..ca383d7 100644 --- a/ui/events/event.h +++ b/ui/events/event.h
@@ -6,7 +6,6 @@ #define UI_EVENTS_EVENT_H_ #include <stdint.h> - #include "base/compiler_specific.h" #include "base/event_types.h" #include "base/gtest_prod_util.h" @@ -27,6 +26,10 @@ class Transform; } +namespace IPC { +template <class P> struct ParamTraits; +} + namespace ui { class EventTarget; class KeyEvent; @@ -36,6 +39,10 @@ class ScrollEvent; class TouchEvent; enum class DomCode; +class Event; +class MouseWheelEvent; + +using ScopedEvent = scoped_ptr<Event>; class EVENTS_EXPORT Event { public: @@ -282,6 +289,9 @@ private: friend class EventTestApi; + // For (de)serialization. + friend struct IPC::ParamTraits<ui::ScopedEvent>; + EventType type_; std::string name_; base::TimeDelta time_stamp_; @@ -303,6 +313,13 @@ public: CancelModeEvent(); ~CancelModeEvent() override; + + private: + // For (de)serialization. + CancelModeEvent(EventType type, base::TimeDelta time_stamp, int flags) + : Event(type, time_stamp, flags) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::CancelModeEvent>; }; class EVENTS_EXPORT LocatedEvent : public Event { @@ -346,6 +363,13 @@ protected: friend class LocatedEventTestApi; + + // For (de)serialization. + LocatedEvent(EventType type, base::TimeDelta time_stamp, int flags) + : Event(type, time_stamp, flags) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::LocatedEvent>; + explicit LocatedEvent(const base::NativeEvent& native_event); // Create a new LocatedEvent which is identical to the provided model. @@ -406,6 +430,9 @@ tilt_y == other.tilt_y; } + // For serialization. + friend struct IPC::ParamTraits<ui::PointerDetails>; + // The type of pointer device. EventPointerType pointer_type = EventPointerType::POINTER_TYPE_UNKNOWN; @@ -525,6 +552,13 @@ pointer_details_ = details; } + protected: + // For (de)serialization. + MouseEvent(EventType type, base::TimeDelta time_stamp, int flags) + : LocatedEvent(type, time_stamp, flags) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::MouseEvent>; + private: FRIEND_TEST_ALL_PREFIXES(EventTest, DoubleClickRequiresRelease); FRIEND_TEST_ALL_PREFIXES(EventTest, SingleClickRightLeft); @@ -585,6 +619,12 @@ const gfx::Vector2d& offset() const { return offset_; } private: + // For (de)serialization. + MouseWheelEvent(EventType type, base::TimeDelta time_stamp, int flags) + : MouseEvent(type, time_stamp, flags) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::MouseWheelEvent>; + gfx::Vector2d offset_; }; @@ -657,15 +697,22 @@ } private: + // For (de)serialization. + TouchEvent(EventType type, base::TimeDelta time_stamp, int flags) + : LocatedEvent(type, time_stamp, flags), + should_remove_native_touch_id_mapping_(false) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::TouchEvent>; + // Adjusts rotation_angle_ to within the acceptable range. void FixRotationAngle(); // The identity (typically finger) of the touch starting at 0 and incrementing // for each separable additional touch that the hardware can detect. - const int touch_id_; + int touch_id_; // A unique identifier for the touch event. - const uint32_t unique_event_id_; + uint32_t unique_event_id_; // Clockwise angle (in degrees) of the major axis from the X axis. Must be // less than 180 and non-negative. @@ -875,6 +922,11 @@ void set_is_char(bool is_char) { is_char_ = is_char; } private: + // For (de)serialization. + KeyEvent(EventType type, base::TimeDelta time_stamp, int flags); + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::KeyEvent>; + // Determine key_ on a keystroke event from code_ and flags(). void ApplyLayout() const; @@ -953,6 +1005,12 @@ int finger_count() const { return finger_count_; } private: + // For (de)serialization. + ScrollEvent(EventType type, base::TimeDelta time_stamp, int flags) + : MouseEvent(type, time_stamp, flags) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::ScrollEvent>; + // Potential accelerated offsets. float x_offset_; float y_offset_; @@ -985,6 +1043,12 @@ const GestureEventDetails& details() const { return details_; } private: + // For (de)serialization. + GestureEvent(EventType type, base::TimeDelta time_stamp, int flags) + : LocatedEvent(type, time_stamp, flags) {} + friend struct IPC::ParamTraits<ui::ScopedEvent>; + friend struct IPC::ParamTraits<ui::GestureEvent>; + GestureEventDetails details_; };
diff --git a/ui/events/events.gyp b/ui/events/events.gyp index 4a9d471..b905a482 100644 --- a/ui/events/events.gyp +++ b/ui/events/events.gyp
@@ -312,6 +312,7 @@ 'sources': [ 'ipc/latency_info_param_traits.cc', 'ipc/latency_info_param_traits.h', + 'ipc/latency_info_param_traits_macros.h', ], }, { @@ -388,4 +389,4 @@ ], }], ], -} \ No newline at end of file +}
diff --git a/ui/events/gesture_event_details.h b/ui/events/gesture_event_details.h index ff88041..6a79a4a 100644 --- a/ui/events/gesture_event_details.h +++ b/ui/events/gesture_event_details.h
@@ -5,12 +5,18 @@ #ifndef UI_EVENTS_GESTURE_DETECTION_GESTURE_EVENT_DETAILS_H_ #define UI_EVENTS_GESTURE_DETECTION_GESTURE_EVENT_DETAILS_H_ +#include <string.h> + #include "base/logging.h" #include "ui/events/event_constants.h" #include "ui/events/events_base_export.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_conversions.h" +namespace IPC { +template <class P> struct ParamTraits; +} + namespace ui { struct EVENTS_BASE_EXPORT GestureEventDetails { @@ -137,6 +143,14 @@ return data_.scroll_update.previous_update_in_sequence_prevented; } + // Supports comparison over internal structures for testing. + bool operator==(const GestureEventDetails& other) const { + return type_ == other.type_ && + !memcmp(&data_, &other.data_, sizeof(Details)) && + touch_points_ == other.touch_points_ && + bounding_box_ == other.bounding_box_; + } + private: EventType type_; union Details { @@ -182,6 +196,10 @@ int tap_count; // TAP repeat count. } data_; + // For mojo native implementation of (de)serialization. + friend struct IPC::ParamTraits<ui::GestureEventDetails>; + friend struct IPC::ParamTraits<ui::GestureEventDetails::Details>; + int touch_points_; // Number of active touch points in the gesture. // Bounding box is an axis-aligned rectangle that contains all the
diff --git a/ui/events/ipc/BUILD.gn b/ui/events/ipc/BUILD.gn index f7eaf887..975b875f 100644 --- a/ui/events/ipc/BUILD.gn +++ b/ui/events/ipc/BUILD.gn
@@ -9,6 +9,7 @@ sources = [ "latency_info_param_traits.cc", "latency_info_param_traits.h", + "latency_info_param_traits_macros.h", ] defines = [ "EVENTS_IPC_IMPLEMENTATION" ]
diff --git a/ui/events/keycodes/dom/dom_key.h b/ui/events/keycodes/dom/dom_key.h index cb4b5ee..810f8213 100644 --- a/ui/events/keycodes/dom/dom_key.h +++ b/ui/events/keycodes/dom/dom_key.h
@@ -8,6 +8,7 @@ #include <stdint.h> #include "base/logging.h" +#include "ipc/ipc_param_traits.h" namespace ui { @@ -147,6 +148,8 @@ }; private: + friend struct IPC::ParamTraits<ui::DomKey>; + Base value_; };
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index 8fd50bd3b..fb1d5303e 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn
@@ -224,6 +224,8 @@ "win/hwnd_util.h", "win/physical_size.cc", "win/physical_size.h", + "win/rendering_window_manager.cc", + "win/rendering_window_manager.h", "win/scoped_set_map_mode.h", "win/screen_win_display.cc", "win/screen_win_display.h",
diff --git a/ui/gfx/gfx.gyp b/ui/gfx/gfx.gyp index 0d8d2d4..f5c03c46 100644 --- a/ui/gfx/gfx.gyp +++ b/ui/gfx/gfx.gyp
@@ -318,6 +318,8 @@ 'win/hwnd_util.h', "win/physical_size.cc", "win/physical_size.h", + 'win/rendering_window_manager.cc', + 'win/rendering_window_manager.h', 'win/scoped_set_map_mode.h', 'win/screen_win_display.cc', 'win/screen_win_display.h',
diff --git a/ui/gfx/ipc/gfx_param_traits.cc b/ui/gfx/ipc/gfx_param_traits.cc index 1e5d6120..e800fef 100644 --- a/ui/gfx/ipc/gfx_param_traits.cc +++ b/ui/gfx/ipc/gfx_param_traits.cc
@@ -81,6 +81,12 @@ l->append(base::StringPrintf("(%d, %d)", p.x(), p.y())); } +void ParamTraits<gfx::PointF>::GetSize(base::PickleSizer* s, + const gfx::PointF& p) { + GetParamSize(s, p.x()); + GetParamSize(s, p.y()); +} + void ParamTraits<gfx::PointF>::Write(base::Pickle* m, const gfx::PointF& p) { WriteParam(m, p.x()); WriteParam(m, p.y()); @@ -170,6 +176,11 @@ l->append(base::StringPrintf("(%f, %f)", p.width(), p.height())); } +void ParamTraits<gfx::Vector2d>::GetSize(base::PickleSizer* s, + const gfx::Vector2d& p) { + s->AddBytes(sizeof(int) * 2); +} + void ParamTraits<gfx::Vector2d>::Write(base::Pickle* m, const gfx::Vector2d& p) { int values[2] = { p.x(), p.y() }; @@ -237,6 +248,11 @@ p.width(), p.height())); } +void ParamTraits<gfx::RectF>::GetSize(base::PickleSizer* s, + const gfx::RectF& p) { + s->AddBytes(sizeof(float) * 4); +} + void ParamTraits<gfx::RectF>::Write(base::Pickle* m, const gfx::RectF& p) { float values[4] = { p.x(), p.y(), p.width(), p.height() }; m->WriteBytes(&values, sizeof(float) * 4);
diff --git a/ui/gfx/ipc/gfx_param_traits.h b/ui/gfx/ipc/gfx_param_traits.h index 55c1b85..e22d0a6 100644 --- a/ui/gfx/ipc/gfx_param_traits.h +++ b/ui/gfx/ipc/gfx_param_traits.h
@@ -48,6 +48,7 @@ template <> struct GFX_IPC_EXPORT ParamTraits<gfx::PointF> { typedef gfx::PointF param_type; + static void GetSize(base::PickleSizer* s, const param_type& p); static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, base::PickleIterator* iter, @@ -88,6 +89,7 @@ template <> struct GFX_IPC_EXPORT ParamTraits<gfx::Vector2d> { typedef gfx::Vector2d param_type; + static void GetSize(base::PickleSizer* s, const param_type& p); static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, base::PickleIterator* iter, @@ -118,6 +120,7 @@ template <> struct GFX_IPC_EXPORT ParamTraits<gfx::RectF> { typedef gfx::RectF param_type; + static void GetSize(base::PickleSizer* s, const param_type& p); static void Write(base::Pickle* m, const param_type& p); static bool Read(const base::Pickle* m, base::PickleIterator* iter,
diff --git a/ui/gfx/win/rendering_window_manager.cc b/ui/gfx/win/rendering_window_manager.cc new file mode 100644 index 0000000..a0528ecf --- /dev/null +++ b/ui/gfx/win/rendering_window_manager.cc
@@ -0,0 +1,70 @@ +// 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 "ui/gfx/win/rendering_window_manager.h" + +#include "base/memory/singleton.h" + +namespace gfx { + +// static +RenderingWindowManager* RenderingWindowManager::GetInstance() { + return base::Singleton<RenderingWindowManager>::get(); +} + +void RenderingWindowManager::RegisterParent(HWND parent) { + base::AutoLock lock(lock_); + + info_[parent] = nullptr; +} + +bool RenderingWindowManager::RegisterChild(HWND parent, HWND child_window) { + if (!child_window) + return false; + + base::AutoLock lock(lock_); + + auto it = info_.find(parent); + if (it == info_.end()) + return false; + if (it->second) + return false; + + info_[parent] = child_window; + return true; +} + +void RenderingWindowManager::DoSetParentOnChild(HWND parent) { + HWND child; + { + base::AutoLock lock(lock_); + + auto it = info_.find(parent); + if (it == info_.end()) + return; + if (!it->second) + return; + child = it->second; + } + + ::SetParent(child, parent); +} + +void RenderingWindowManager::UnregisterParent(HWND parent) { + base::AutoLock lock(lock_); + info_.erase(parent); +} + +bool RenderingWindowManager::HasValidChildWindow(HWND parent) { + base::AutoLock lock(lock_); + auto it = info_.find(parent); + if (it == info_.end()) + return false; + return !!it->second && ::IsWindow(it->second); +} + +RenderingWindowManager::RenderingWindowManager() {} +RenderingWindowManager::~RenderingWindowManager() {} + +} // namespace gfx
diff --git a/ui/gfx/win/rendering_window_manager.h b/ui/gfx/win/rendering_window_manager.h new file mode 100644 index 0000000..bbb74ac --- /dev/null +++ b/ui/gfx/win/rendering_window_manager.h
@@ -0,0 +1,48 @@ +// 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 UI_GFX_WIN_RENDERING_WINDOW_MANAGER_H_ +#define UI_GFX_WIN_RENDERING_WINDOW_MANAGER_H_ + +#include <windows.h> + +#include <map> + +#include "base/synchronization/lock.h" +#include "ui/gfx/gfx_export.h" + +namespace base { +template <typename T> +struct DefaultSingletonTraits; +} + +namespace gfx { + +// This keeps track of whether a given HWND has a child window which the GPU +// process renders into. +class GFX_EXPORT RenderingWindowManager { + public: + static RenderingWindowManager* GetInstance(); + + void RegisterParent(HWND parent); + bool RegisterChild(HWND parent, HWND child_window); + void DoSetParentOnChild(HWND parent); + void UnregisterParent(HWND parent); + bool HasValidChildWindow(HWND parent); + + private: + friend struct base::DefaultSingletonTraits<RenderingWindowManager>; + + RenderingWindowManager(); + ~RenderingWindowManager(); + + base::Lock lock_; + std::map<HWND, HWND> info_; + + DISALLOW_COPY_AND_ASSIGN(RenderingWindowManager); +}; + +} // namespace gfx + +#endif // UI_GFX_WIN_RENDERING_WINDOW_MANAGER_H_
diff --git a/ui/gl/gl_version_info.cc b/ui/gl/gl_version_info.cc index cc960b0..42616509 100644 --- a/ui/gl/gl_version_info.cc +++ b/ui/gl/gl_version_info.cc
@@ -83,6 +83,7 @@ } if (*is_es && *major_version == 3) *is_es3 = true; + DCHECK(major_version != 0); } } // namespace gfx
diff --git a/ui/metro_viewer/metro_viewer_messages.h b/ui/metro_viewer/metro_viewer_messages.h index 8dfab4d..72428f5 100644 --- a/ui/metro_viewer/metro_viewer_messages.h +++ b/ui/metro_viewer/metro_viewer_messages.h
@@ -15,22 +15,6 @@ #define IPC_MESSAGE_START MetroViewerMsgStart -IPC_ENUM_TRAITS(ui::EventType) -IPC_ENUM_TRAITS(ui::EventFlags) - -// Contains the parameters sent for a mousebutton message. -IPC_STRUCT_BEGIN(MetroViewerHostMsg_MouseButtonParams) - - IPC_STRUCT_MEMBER(int32_t, x) - IPC_STRUCT_MEMBER(int32_t, y) - IPC_STRUCT_MEMBER(int32_t, extra) - IPC_STRUCT_MEMBER(ui::EventType, event_type) - IPC_STRUCT_MEMBER(uint32_t, flags) - IPC_STRUCT_MEMBER(ui::EventFlags, changed_button) - IPC_STRUCT_MEMBER(bool, is_horizontal_wheel) - -IPC_STRUCT_END() - // Messages sent from the viewer to the browser: // Inform the browser of the surface to target for compositing. @@ -42,9 +26,6 @@ int32_t, /* x-coordinate */ int32_t, /* y-coordinate */ int32_t /* flags */) -// Informs the brower that a mouse button was pressed. -IPC_MESSAGE_CONTROL1(MetroViewerHostMsg_MouseButton, - MetroViewerHostMsg_MouseButtonParams) // Informs the browser that a key was pressed. IPC_MESSAGE_CONTROL4(MetroViewerHostMsg_KeyDown, uint32_t, /* virtual key */
diff --git a/ui/ozone/ozone.gni b/ui/ozone/ozone.gni index 31e6dbf8..2287c1ef 100644 --- a/ui/ozone/ozone.gni +++ b/ui/ozone/ozone.gni
@@ -37,22 +37,18 @@ ozone_platform_headless = true if (is_chromecast) { - if (!disable_display) { - # Enable the Cast ozone platform on all A/V Cast builds. - ozone_platform_cast = true + # Enable the Cast ozone platform on all A/V Cast builds. + ozone_platform_cast = true - # For desktop Chromecast builds, override the default "headless" - # platform with --ozone-platform=egltest - # TODO(halliwell): Create a libcast_graphics implementation for desktop - # using X11, and disable these two platforms. "cast" platform should be - # the default on every A/V build. - if (is_cast_desktop_build) { - ozone_platform_egltest = true - ozone_platform_ozonex = true - } else { - # On device builds, enable "cast" as the default platform. - ozone_platform = "cast" - } + # For visual desktop Chromecast builds, override the default "headless" + # platform with --ozone-platform=egltest + # TODO(halliwell): Create a libcast_graphics implementation for desktop + # using X11, and disable these two platforms. + if (is_cast_desktop_build && !disable_display) { + ozone_platform_egltest = true + ozone_platform_ozonex = true + } else { + ozone_platform = "cast" } } else if (is_chromeos) { ozone_platform_gbm = true
diff --git a/ui/ozone/platform/cast/BUILD.gn b/ui/ozone/platform/cast/BUILD.gn index 0a548e44..53de77f 100644 --- a/ui/ozone/platform/cast/BUILD.gn +++ b/ui/ozone/platform/cast/BUILD.gn
@@ -37,6 +37,10 @@ # do not want to statically link against EGL library. libs = [ "dl" ] + if (disable_display) { + defines = [ "DISABLE_DISPLAY" ] + } + deps = [ "//base", "//chromecast/graphics:libcast_graphics_1.0",
diff --git a/ui/ozone/platform/cast/cast.gypi b/ui/ozone/platform/cast/cast.gypi index ce3a62d..ae875b4 100644 --- a/ui/ozone/platform/cast/cast.gypi +++ b/ui/ozone/platform/cast/cast.gypi
@@ -30,6 +30,11 @@ 'include_dirs': [ '<(DEPTH)/third_party/khronos', ], + 'conditions': [ + ['disable_display==1', { + 'defines': ['DISABLE_DISPLAY'], + }], + ], 'sources': [ 'client_native_pixmap_factory_cast.cc',
diff --git a/ui/ozone/platform/cast/ozone_platform_cast.cc b/ui/ozone/platform/cast/ozone_platform_cast.cc index 5091c93..75e05c3 100644 --- a/ui/ozone/platform/cast/ozone_platform_cast.cc +++ b/ui/ozone/platform/cast/ozone_platform_cast.cc
@@ -85,8 +85,15 @@ gpu_platform_support_host_.reset(CreateStubGpuPlatformSupportHost()); // Enable dummy software rendering support if GPU process disabled + // or if we're an audio-only build. // Note: switch is kDisableGpu from content/public/common/content_switches.h - if (base::CommandLine::ForCurrentProcess()->HasSwitch("disable-gpu")) + bool enable_dummy_software_rendering = true; +#if !defined(DISABLE_DISPLAY) + enable_dummy_software_rendering = + base::CommandLine::ForCurrentProcess()->HasSwitch("disable-gpu"); +#endif + + if (enable_dummy_software_rendering) surface_factory_.reset(new SurfaceFactoryCast()); } void InitializeGPU() override {
diff --git a/ui/shell_dialogs/BUILD.gn b/ui/shell_dialogs/BUILD.gn index 01afac9a..06ca709 100644 --- a/ui/shell_dialogs/BUILD.gn +++ b/ui/shell_dialogs/BUILD.gn
@@ -14,8 +14,6 @@ "base_shell_dialog.h", "base_shell_dialog_win.cc", "base_shell_dialog_win.h", - "linux_shell_dialog.cc", - "linux_shell_dialog.h", "select_file_dialog.cc", "select_file_dialog.h", "select_file_dialog_factory.cc", @@ -28,6 +26,8 @@ "select_file_policy.h", "selected_file_info.cc", "selected_file_info.h", + "shell_dialog_linux.cc", + "shell_dialog_linux.h", ] defines = [ "SHELL_DIALOGS_IMPLEMENTATION" ]
diff --git a/ui/shell_dialogs/linux_shell_dialog.cc b/ui/shell_dialogs/linux_shell_dialog.cc deleted file mode 100644 index 059bb724..0000000 --- a/ui/shell_dialogs/linux_shell_dialog.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/shell_dialogs/linux_shell_dialog.h" - -namespace { - -ui::LinuxShellDialog* g_linux_shell_dialog = NULL; - -} // namespace - -namespace ui { - -void LinuxShellDialog::SetInstance(LinuxShellDialog* instance) { - g_linux_shell_dialog = instance; -} - -const LinuxShellDialog* LinuxShellDialog::instance() { - return g_linux_shell_dialog; -} - -} // namespace ui
diff --git a/ui/shell_dialogs/select_file_dialog.cc b/ui/shell_dialogs/select_file_dialog.cc index 82086dd..2bfacec 100644 --- a/ui/shell_dialogs/select_file_dialog.cc +++ b/ui/shell_dialogs/select_file_dialog.cc
@@ -21,7 +21,7 @@ #elif defined(OS_ANDROID) #include "ui/shell_dialogs/select_file_dialog_android.h" #elif defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS) -#include "ui/shell_dialogs/linux_shell_dialog.h" +#include "ui/shell_dialogs/shell_dialog_linux.h" #endif namespace { @@ -80,7 +80,7 @@ } #if defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS) - const ui::LinuxShellDialog* shell_dialogs = ui::LinuxShellDialog::instance(); + const ui::ShellDialogLinux* shell_dialogs = ui::ShellDialogLinux::instance(); if (shell_dialogs) return shell_dialogs->CreateSelectFileDialog(listener, policy); #endif
diff --git a/ui/shell_dialogs/select_file_dialog_mac.mm b/ui/shell_dialogs/select_file_dialog_mac.mm index 6fe6a62..e53c389 100644 --- a/ui/shell_dialogs/select_file_dialog_mac.mm +++ b/ui/shell_dialogs/select_file_dialog_mac.mm
@@ -350,6 +350,7 @@ // Create an array with each item corresponding to an array of different // extensions in an extension group. NSMutableArray* file_type_lists = [NSMutableArray array]; + int default_extension_index = -1; for (size_t i = 0; i < file_types->extensions.size(); ++i) { const std::vector<base::FilePath::StringType>& ext_list = file_types->extensions[i]; @@ -373,6 +374,9 @@ // Set to store different extensions in the current extension group. NSMutableSet* file_type_set = [NSMutableSet set]; for (const base::FilePath::StringType& ext : ext_list) { + if (ext == default_extension) + default_extension_index = i; + base::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); [file_type_set addObject:base::mac::CFToNSCast(uti.get())]; @@ -401,14 +405,21 @@ [popup setTarget:handler]; [popup setAction:@selector(popupAction:)]; - if (default_extension.empty()) { + // file_type_index uses 1 based indexing. + if (file_type_index) { + DCHECK_LE(static_cast<size_t>(file_type_index), + file_types->extensions.size()); + DCHECK_GE(file_type_index, 1); + [popup selectItemAtIndex:file_type_index - 1]; + [handler popupAction:popup]; + } else if (!default_extension.empty() && default_extension_index != -1) { + [popup selectItemAtIndex:default_extension_index]; + [dialog + setAllowedFileTypes:@[ base::SysUTF8ToNSString(default_extension) ]]; + } else { // Select the first item. [popup selectItemAtIndex:0]; [handler popupAction:popup]; - } else { - [popup selectItemAtIndex:-1]; - [dialog - setAllowedFileTypes:@[ base::SysUTF8ToNSString(default_extension) ]]; } return handler;
diff --git a/ui/shell_dialogs/shell_dialog_linux.cc b/ui/shell_dialogs/shell_dialog_linux.cc new file mode 100644 index 0000000..62bee5b --- /dev/null +++ b/ui/shell_dialogs/shell_dialog_linux.cc
@@ -0,0 +1,23 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/shell_dialogs/shell_dialog_linux.h" + +namespace { + +ui::ShellDialogLinux* g_shell_dialog_linux = nullptr; + +} // namespace + +namespace ui { + +void ShellDialogLinux::SetInstance(ShellDialogLinux* instance) { + g_shell_dialog_linux = instance; +} + +const ShellDialogLinux* ShellDialogLinux::instance() { + return g_shell_dialog_linux; +} + +} // namespace ui
diff --git a/ui/shell_dialogs/linux_shell_dialog.h b/ui/shell_dialogs/shell_dialog_linux.h similarity index 76% rename from ui/shell_dialogs/linux_shell_dialog.h rename to ui/shell_dialogs/shell_dialog_linux.h index a503b78e..1dad34d 100644 --- a/ui/shell_dialogs/linux_shell_dialog.h +++ b/ui/shell_dialogs/shell_dialog_linux.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 UI_SHELL_DIALOGS_LINUX_SHELL_DIALOG_H_ -#define UI_SHELL_DIALOGS_LINUX_SHELL_DIALOG_H_ +#ifndef UI_SHELL_DIALOGS_SHELL_DIALOG_LINUX_H_ +#define UI_SHELL_DIALOGS_SHELL_DIALOG_LINUX_H_ #include "ui/shell_dialogs/select_file_dialog.h" #include "ui/shell_dialogs/shell_dialogs_export.h" @@ -12,21 +12,21 @@ // An interface that lets different Linux platforms override the // CreateSelectFileDialog function declared here to return native file dialogs. -class SHELL_DIALOGS_EXPORT LinuxShellDialog { +class SHELL_DIALOGS_EXPORT ShellDialogLinux { public: - virtual ~LinuxShellDialog() {} + virtual ~ShellDialogLinux() {} // Sets the dynamically loaded singleton that draws the desktop native // UI. This pointer is not owned, and if this method is called a second time, // the first instance is not deleted. - static void SetInstance(LinuxShellDialog* instance); + static void SetInstance(ShellDialogLinux* instance); // Returns a LinuxUI instance for the toolkit used in the user's desktop // environment. // // Can return NULL, in case no toolkit has been set. (For example, if we're // running with the "--ash" flag.) - static const LinuxShellDialog* instance(); + static const ShellDialogLinux* instance(); // Returns a native file selection dialog. virtual SelectFileDialog* CreateSelectFileDialog( @@ -36,5 +36,4 @@ } // namespace ui -#endif // UI_SHELL_DIALOGS_LINUX_SHELL_DIALOG_H_ - +#endif // UI_SHELL_DIALOGS_SHELL_DIALOG_LINUX_H_
diff --git a/ui/shell_dialogs/shell_dialogs.gyp b/ui/shell_dialogs/shell_dialogs.gyp index 2329f8f..cb49361b 100644 --- a/ui/shell_dialogs/shell_dialogs.gyp +++ b/ui/shell_dialogs/shell_dialogs.gyp
@@ -29,8 +29,6 @@ 'base_shell_dialog.h', 'base_shell_dialog_win.cc', 'base_shell_dialog_win.h', - 'linux_shell_dialog.cc', - 'linux_shell_dialog.h', 'select_file_dialog.cc', 'select_file_dialog.h', 'select_file_dialog_android.cc', @@ -45,6 +43,8 @@ 'select_file_policy.h', 'selected_file_info.cc', 'selected_file_info.h', + 'shell_dialog_linux.cc', + 'shell_dialog_linux.h', ], 'conditions': [ ['use_aura==1', @@ -83,12 +83,12 @@ 'dependencies': [ '../../base/base.gyp:base', '../../base/base.gyp:test_support_base', - '../../base/base.gyp:run_all_unittests', '../../testing/gtest.gyp:gtest', 'shell_dialogs', ], 'sources': [ # Note: file list duplicated in GN build. + '../../base/test/run_all_unittests.cc', 'select_file_dialog_win_unittest.cc', ], },
diff --git a/ui/views/bubble/bubble_delegate_unittest.cc b/ui/views/bubble/bubble_delegate_unittest.cc index 92201c0..5998d14 100644 --- a/ui/views/bubble/bubble_delegate_unittest.cc +++ b/ui/views/bubble/bubble_delegate_unittest.cc
@@ -15,6 +15,10 @@ #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" +#if defined(OS_MACOSX) +#include "ui/base/test/scoped_fake_nswindow_focus.h" +#endif + namespace views { namespace { @@ -66,6 +70,11 @@ } private: +#if defined(OS_MACOSX) + // Ensure tests running in parallel don't steal focus from the Widget on Mac. + ui::test::ScopedFakeNSWindowFocus fake_focus_; +#endif + DISALLOW_COPY_AND_ASSIGN(BubbleDelegateTest); }; @@ -277,6 +286,7 @@ anchor_widget->GetContentsView(), BubbleBorder::NONE); bubble_delegate->set_close_on_deactivate(true); Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); + anchor_widget->Show(); bubble_widget->Show(); anchor_widget->Activate(); EXPECT_TRUE(bubble_widget->IsClosed());
diff --git a/ui/views/cocoa/bridged_content_view.mm b/ui/views/cocoa/bridged_content_view.mm index 6022a447..e2cd30e2 100644 --- a/ui/views/cocoa/bridged_content_view.mm +++ b/ui/views/cocoa/bridged_content_view.mm
@@ -407,6 +407,20 @@ return YES; } +- (BOOL)becomeFirstResponder { + BOOL result = [super becomeFirstResponder]; + if (result && hostedView_) + hostedView_->GetWidget()->GetFocusManager()->RestoreFocusedView(); + return result; +} + +- (BOOL)resignFirstResponder { + BOOL result = [super resignFirstResponder]; + if (result && hostedView_) + hostedView_->GetWidget()->GetFocusManager()->StoreFocusedView(true); + return result; +} + - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered.
diff --git a/ui/views/cocoa/bridged_native_widget_unittest.mm b/ui/views/cocoa/bridged_native_widget_unittest.mm index 5d428c0..5b39b511 100644 --- a/ui/views/cocoa/bridged_native_widget_unittest.mm +++ b/ui/views/cocoa/bridged_native_widget_unittest.mm
@@ -214,8 +214,7 @@ protected: scoped_ptr<views::View> view_; - scoped_ptr<BridgedNativeWidget> bridge_; - BridgedContentView* ns_view_; // Weak. Owned by bridge_. + BridgedContentView* ns_view_; // Weak. Owned by bridge(). base::MessageLoopForUI message_loop_; private:
diff --git a/ui/views/controls/scrollbar/base_scroll_bar.cc b/ui/views/controls/scrollbar/base_scroll_bar.cc index be0740f6..e9333e14 100644 --- a/ui/views/controls/scrollbar/base_scroll_bar.cc +++ b/ui/views/controls/scrollbar/base_scroll_bar.cc
@@ -413,7 +413,8 @@ // Thumb Height and Thumb Pos. // The height of the thumb is the ratio of the Viewport height to the // content size multiplied by the height of the thumb track. - double ratio = static_cast<double>(viewport_size) / contents_size_; + double ratio = + std::min(1.0, static_cast<double>(viewport_size) / contents_size_); int thumb_size = static_cast<int>(ratio * GetTrackSize()); thumb_->SetSize(thumb_size); @@ -505,10 +506,13 @@ int BaseScrollBar::CalculateContentsOffset(int thumb_position, bool scroll_to_middle) const { int thumb_size = thumb_->GetSize(); + int track_size = GetTrackSize(); + if (track_size == thumb_size) + return 0; if (scroll_to_middle) thumb_position = thumb_position - (thumb_size / 2); return (thumb_position * (contents_size_ - viewport_size_)) / - (GetTrackSize() - thumb_size); + (track_size - thumb_size); } void BaseScrollBar::SetThumbTrackState(CustomButton::ButtonState state) {
diff --git a/ui/views/controls/scrollbar/base_scroll_bar.h b/ui/views/controls/scrollbar/base_scroll_bar.h index f54a880..178fdc1e 100644 --- a/ui/views/controls/scrollbar/base_scroll_bar.h +++ b/ui/views/controls/scrollbar/base_scroll_bar.h
@@ -115,6 +115,7 @@ private: FRIEND_TEST_ALL_PREFIXES(NativeScrollBarTest, ScrollBarFitsToBottom); + FRIEND_TEST_ALL_PREFIXES(NativeScrollBarTest, ThumbFullLengthOfTrack); int GetThumbSizeForTest(); // Changes to 'pushed' state and starts a timer to scroll repeatedly.
diff --git a/ui/views/controls/scrollbar/scrollbar_unittest.cc b/ui/views/controls/scrollbar/scrollbar_unittest.cc index 4bfab1074..8447192 100644 --- a/ui/views/controls/scrollbar/scrollbar_unittest.cc +++ b/ui/views/controls/scrollbar/scrollbar_unittest.cc
@@ -175,4 +175,28 @@ EXPECT_TRUE(scrollbar_->ScrollByContentsOffset(-1)); } +TEST_F(NativeScrollBarTest, ThumbFullLengthOfTrack) { + // Shrink content so that it fits within the viewport. + scrollbar_->Update(100, 10, 0); + EXPECT_EQ(scrollbar_->GetTrackBounds().width(), + scrollbar_->GetThumbSizeForTest()); + // Emulate a click on the full size scroll bar. + scrollbar_->ScrollToThumbPosition(0, false); + EXPECT_EQ(0, scrollbar_->GetPosition()); + // Emulate a key down. + scrollbar_->ScrollByAmount(BaseScrollBar::SCROLL_NEXT_LINE); + EXPECT_EQ(0, scrollbar_->GetPosition()); + + // Expand content so that it fits *exactly* within the viewport. + scrollbar_->Update(100, 100, 0); + EXPECT_EQ(scrollbar_->GetTrackBounds().width(), + scrollbar_->GetThumbSizeForTest()); + // Emulate a click on the full size scroll bar. + scrollbar_->ScrollToThumbPosition(0, false); + EXPECT_EQ(0, scrollbar_->GetPosition()); + // Emulate a key down. + scrollbar_->ScrollByAmount(BaseScrollBar::SCROLL_NEXT_LINE); + EXPECT_EQ(0, scrollbar_->GetPosition()); +} + } // namespace views
diff --git a/ui/views/linux_ui/linux_ui.cc b/ui/views/linux_ui/linux_ui.cc index 63c7402..9430add 100644 --- a/ui/views/linux_ui/linux_ui.cc +++ b/ui/views/linux_ui/linux_ui.cc
@@ -6,7 +6,7 @@ #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/linux_font_delegate.h" -#include "ui/shell_dialogs/linux_shell_dialog.h" +#include "ui/shell_dialogs/shell_dialog_linux.h" namespace { @@ -21,7 +21,7 @@ g_linux_ui = instance; LinuxInputMethodContextFactory::SetInstance(instance); LinuxFontDelegate::SetInstance(instance); - LinuxShellDialog::SetInstance(instance); + ShellDialogLinux::SetInstance(instance); ui::SetTextEditKeyBindingsDelegate(instance); }
diff --git a/ui/views/linux_ui/linux_ui.h b/ui/views/linux_ui/linux_ui.h index 0a28b2e7c..d795d7c4 100644 --- a/ui/views/linux_ui/linux_ui.h +++ b/ui/views/linux_ui/linux_ui.h
@@ -12,7 +12,7 @@ #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/events/linux/text_edit_key_bindings_delegate_auralinux.h" #include "ui/gfx/linux_font_delegate.h" -#include "ui/shell_dialogs/linux_shell_dialog.h" +#include "ui/shell_dialogs/shell_dialog_linux.h" #include "ui/views/controls/button/button.h" #include "ui/views/linux_ui/status_icon_linux.h" #include "ui/views/views_export.h" @@ -52,7 +52,7 @@ // liuigtk3.so, etc. class VIEWS_EXPORT LinuxUI : public ui::LinuxInputMethodContextFactory, public gfx::LinuxFontDelegate, - public ui::LinuxShellDialog, + public ui::ShellDialogLinux, public ui::TextEditKeyBindingsDelegateAuraLinux { public: // Describes the window management actions that could be taken in response to
diff --git a/ui/views/mus/surface_context_factory.cc b/ui/views/mus/surface_context_factory.cc index 840a16b..bb27a08 100644 --- a/ui/views/mus/surface_context_factory.cc +++ b/ui/views/mus/surface_context_factory.cc
@@ -8,7 +8,7 @@ #include "cc/resources/shared_bitmap_manager.h" #include "cc/surfaces/surface_id_allocator.h" #include "components/mus/public/cpp/window.h" -#include "mojo/shell/public/interfaces/shell.mojom.h" +#include "mojo/shell/public/interfaces/connector.mojom.h" #include "ui/compositor/reflector.h" #include "ui/gl/gl_bindings.h"
diff --git a/ui/views/widget/native_widget_mac_unittest.mm b/ui/views/widget/native_widget_mac_unittest.mm index 0783ac0..635de89 100644 --- a/ui/views/widget/native_widget_mac_unittest.mm +++ b/ui/views/widget/native_widget_mac_unittest.mm
@@ -71,6 +71,9 @@ @property(assign, nonatomic) NSRect lastDirtyRect; @end +@interface FocusableTestNSView : NSView +@end + namespace views { namespace test { @@ -1309,6 +1312,31 @@ widget->CloseNow(); } +// Ensure traversing NSView focus correctly updates the views::FocusManager. +TEST_F(NativeWidgetMacTest, ChangeFocusOnChangeFirstResponder) { + Widget* widget = CreateTopLevelPlatformWidget(); + widget->GetRootView()->SetFocusable(true); + widget->Show(); + + base::scoped_nsobject<NSView> child_view([[FocusableTestNSView alloc] + initWithFrame:[widget->GetNativeView() bounds]]); + [widget->GetNativeView() addSubview:child_view]; + EXPECT_TRUE([child_view acceptsFirstResponder]); + EXPECT_TRUE(widget->GetRootView()->IsFocusable()); + + FocusManager* manager = widget->GetFocusManager(); + manager->SetFocusedView(widget->GetRootView()); + EXPECT_EQ(manager->GetFocusedView(), widget->GetRootView()); + + [widget->GetNativeWindow() makeFirstResponder:child_view]; + EXPECT_FALSE(manager->GetFocusedView()); + + [widget->GetNativeWindow() makeFirstResponder:widget->GetNativeView()]; + EXPECT_EQ(manager->GetFocusedView(), widget->GetRootView()); + + widget->CloseNow(); +} + } // namespace test } // namespace views @@ -1340,3 +1368,9 @@ } @end + +@implementation FocusableTestNSView +- (BOOL)acceptsFirstResponder { + return YES; +} +@end
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index d9aaf40..71eeafc 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -39,6 +39,7 @@ #include "ui/gfx/win/direct_manipulation.h" #include "ui/gfx/win/dpi.h" #include "ui/gfx/win/hwnd_util.h" +#include "ui/gfx/win/rendering_window_manager.h" #include "ui/native_theme/native_theme_win.h" #include "ui/views/views_delegate.h" #include "ui/views/widget/monitor_win.h" @@ -861,6 +862,13 @@ SetWindowLong(hwnd(), GWL_STYLE, style); } +bool HWNDMessageHandler::HasChildRenderingWindow() { + // This can change dynamically if the system switches between GPU and + // software rendering. + return gfx::RenderingWindowManager::GetInstance()->HasValidChildWindow( + hwnd()); +} + //////////////////////////////////////////////////////////////////////////////// // HWNDMessageHandler, gfx::WindowImpl overrides: @@ -1909,8 +1917,18 @@ << ", GDI peak count: " << peak_gdi_objects; } - if (!IsRectEmpty(&ps.rcPaint)) + if (!IsRectEmpty(&ps.rcPaint)) { + if (HasChildRenderingWindow()) { + // If there's a child window that's being rendered to then clear the + // area outside it (as WS_CLIPCHILDREN is set) with transparent black. + // Otherwise, other portions of the backing store for the window can + // flicker opaque black. http://crbug.com/586454 + + FillRect(ps.hdc, &ps.rcPaint, + reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH))); + } delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint)); + } EndPaint(hwnd(), &ps); }
diff --git a/ui/views/win/hwnd_message_handler.h b/ui/views/win/hwnd_message_handler.h index 3f7b752..65578e8 100644 --- a/ui/views/win/hwnd_message_handler.h +++ b/ui/views/win/hwnd_message_handler.h
@@ -206,6 +206,10 @@ // Updates the window style to reflect whether it can be resized or maximized. void SizeConstraintsChanged(); + // Returns true if content is rendered to a child window instead of directly + // to this window. + bool HasChildRenderingWindow(); + private: typedef std::set<DWORD> TouchIDs;
diff --git a/ui/webui/resources/cr_elements/compiled_resources.gyp b/ui/webui/resources/cr_elements/compiled_resources2.gyp similarity index 76% rename from ui/webui/resources/cr_elements/compiled_resources.gyp rename to ui/webui/resources/cr_elements/compiled_resources2.gyp index 7b24a06..cbd3234 100644 --- a/ui/webui/resources/cr_elements/compiled_resources.gyp +++ b/ui/webui/resources/cr_elements/compiled_resources2.gyp
@@ -7,8 +7,8 @@ 'target_name': 'cr_elements_resources', 'type': 'none', 'dependencies': [ - 'network/compiled_resources.gyp:*', - 'policy/compiled_resources.gyp:*', + 'network/compiled_resources2.gyp:*', + 'policy/compiled_resources2.gyp:*', ], }, ]
diff --git a/ui/webui/resources/cr_elements/cr_shared_menu/compiled_resources.gyp b/ui/webui/resources/cr_elements/cr_shared_menu/compiled_resources.gyp new file mode 100644 index 0000000..ee4ebfb --- /dev/null +++ b/ui/webui/resources/cr_elements/cr_shared_menu/compiled_resources.gyp
@@ -0,0 +1,20 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'cr_shared_menu', + 'variables': { + 'depends': [ + '../../../../../third_party/polymer/v1_0/components-chromium/iron-list/iron-list-extracted.js', + '../../js/assert.js', + '../../js/cr.js', + '../../js/cr/ui/position_util.js', + '../../js/util.js', + ], + }, + 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], + }, + ], +}
diff --git a/ui/webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.html b/ui/webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.html new file mode 100644 index 0000000..fc122f4c --- /dev/null +++ b/ui/webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.html
@@ -0,0 +1,27 @@ +<link rel="import" href="chrome://resources/polymer/v1_0/polymer/polymer.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-styles/shadow.html"> +<link rel="import" href="chrome://resources/polymer/v1_0/paper-menu/paper-menu.html"> +<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/cr/ui/position_util.html"> +<link rel="import" href="chrome://resources/html/util.html"> + +<dom-module id="cr-shared-menu"> + <template> + <style> + :host { + @apply(--shadow-elevation-2dp); + display: none; + position: absolute; + } + + :host([menu-open]) { + display: block; + } + </style> + <paper-menu id="menu"> + <content></content> + </paper-menu> + </template> + <script src="cr_shared_menu.js"></script> +</dom-module>
diff --git a/ui/webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.js b/ui/webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.js new file mode 100644 index 0000000..e0b2415 --- /dev/null +++ b/ui/webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.js
@@ -0,0 +1,76 @@ +// 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. + +Polymer({ + is: 'cr-shared-menu', + + properties: { + menuOpen: { + type: Boolean, + value: false, + reflectToAttribute: true + }, + }, + + /** + * The last anchor that was used to open a menu. It's necessary for toggling. + * @type {?Element} + */ + lastAnchor_: null, + + /** + * Adds listeners to the window in order to dismiss the menu on resize and + * when escape is pressed. + */ + attached: function() { + window.addEventListener('resize', this.closeMenu.bind(this)); + window.addEventListener('keydown', function(e) { + // Escape button on keyboard + if (e.keyCode == 27) + this.closeMenu(); + }.bind(this)); + }, + + /** Closes the menu. */ + closeMenu: function() { + this.menuOpen = false; + }, + + /** + * Opens the menu at the anchor location. + * @param {!Element} anchor The location to display the menu. + */ + openMenu: function(anchor) { + this.menuOpen = true; + this.lastAnchor_ = anchor; + + // Move the menu to the anchor. + var anchorRect = anchor.getBoundingClientRect(); + var parentRect = this.offsetParent.getBoundingClientRect(); + + var left = (isRTL() ? anchorRect.left : anchorRect.right) - parentRect.left; + var top = anchorRect.top - parentRect.top; + + cr.ui.positionPopupAtPoint(left, top, this, cr.ui.AnchorType.BEFORE); + + // Handle the bottom of the screen. + if (this.getBoundingClientRect().top != anchorRect.top) { + var bottom = anchorRect.bottom - parentRect.top; + cr.ui.positionPopupAtPoint(left, bottom, this, cr.ui.AnchorType.BEFORE); + } + + this.$.menu.focus(); + }, + + /** + * Toggles the menu for the anchor that is passed in. + * @param {!Element} anchor The location to display the menu. + */ + toggleMenu: function(anchor) { + if (anchor == this.lastAnchor_ && this.menuOpen) + this.closeMenu(); + else + this.openMenu(anchor); + }, +});
diff --git a/ui/webui/resources/cr_elements/network/compiled_resources.gyp b/ui/webui/resources/cr_elements/network/compiled_resources.gyp deleted file mode 100644 index 601aead..0000000 --- a/ui/webui/resources/cr_elements/network/compiled_resources.gyp +++ /dev/null
@@ -1,43 +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. -{ - 'targets': [ - { - 'target_name': 'cr_network_icon', - 'variables': { - 'depends': [ - 'cr_onc_types.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'cr_network_list', - 'variables': { - 'depends': [ - '../../../../../third_party/jstemplate/compiled_resources.gyp:jstemplate', - 'cr_onc_types.js', - 'cr_network_list_item.js', - '../../../../../ui/webui/resources/js/load_time_data.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'cr_network_select', - 'variables': { - 'depends': [ - 'compiled_resources.gyp:cr_network_list', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/ui/webui/resources/cr_elements/network/compiled_resources2.gyp b/ui/webui/resources/cr_elements/network/compiled_resources2.gyp new file mode 100644 index 0000000..2a193a3 --- /dev/null +++ b/ui/webui/resources/cr_elements/network/compiled_resources2.gyp
@@ -0,0 +1,48 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'cr_network_icon', + 'dependencies': [ + 'cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_network_icon_externs', + 'includes': ['../../../../../third_party/closure_compiler/include_js.gypi'], + }, + { + 'target_name': 'cr_network_list', + 'dependencies': [ + 'cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_network_list_item', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + 'cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_network_select', + 'dependencies': [ + '<(EXTERNS_GYP):networking_private', + 'cr_onc_types', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_onc_types', + 'dependencies': [ + '<(EXTERNS_GYP):networking_private', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/ui/webui/resources/cr_elements/policy/compiled_resources.gyp b/ui/webui/resources/cr_elements/policy/compiled_resources.gyp deleted file mode 100644 index 4d35786..0000000 --- a/ui/webui/resources/cr_elements/policy/compiled_resources.gyp +++ /dev/null
@@ -1,81 +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. -{ - 'targets': [ - { - 'target_name': 'cr_policy_indicator_behavior', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'cr_policy_pref_behavior', - 'variables': { - 'depends': [ - '../../../../../third_party/polymer/v1_0/components-chromium/iron-iconset-svg/iron-iconset-svg-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-meta/iron-meta-extracted.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - 'cr_policy_indicator_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'cr_policy_pref_indicator', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - 'cr_policy_indicator_behavior.js', - 'cr_policy_pref_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/settings_private.js' - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'cr_policy_network_behavior', - 'variables': { - 'depends': [ - '../../../../../third_party/polymer/v1_0/components-chromium/iron-iconset-svg/iron-iconset-svg-extracted.js', - '../../../../../third_party/polymer/v1_0/components-chromium/iron-meta/iron-meta-extracted.js', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../network/cr_onc_types.js', - 'cr_policy_indicator_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'cr_policy_network_indicator', - 'variables': { - 'depends': [ - '../../../../../ui/webui/resources/js/compiled_resources.gyp:assert', - '../../../../../ui/webui/resources/js/compiled_resources.gyp:load_time_data', - '../network/cr_onc_types.js', - 'cr_policy_indicator_behavior.js', - 'cr_policy_network_behavior.js', - ], - 'externs': [ - '../../../../../third_party/closure_compiler/externs/networking_private.js', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], - }, - ], -}
diff --git a/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp b/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp new file mode 100644 index 0000000..7e71e2bd --- /dev/null +++ b/ui/webui/resources/cr_elements/policy/compiled_resources2.gyp
@@ -0,0 +1,44 @@ +# 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. +{ + 'targets': [ + { + 'target_name': 'cr_policy_indicator_behavior', + 'dependencies': [ + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:assert', + '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:load_time_data', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_policy_pref_behavior', + 'dependencies': [ + 'cr_policy_indicator_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_policy_pref_indicator', + 'dependencies': [ + '<(EXTERNS_GYP):settings_private', + 'cr_policy_indicator_behavior', + 'cr_policy_pref_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_policy_network_behavior', + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'cr_policy_network_indicator', + 'dependencies': [ + '../network/compiled_resources2.gyp:cr_onc_types', + 'cr_policy_indicator_behavior', + 'cr_policy_network_behavior', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + ], +}
diff --git a/ui/webui/resources/cr_elements_resources.grdp b/ui/webui/resources/cr_elements_resources.grdp index 66b5084..368f5a99 100644 --- a/ui/webui/resources/cr_elements_resources.grdp +++ b/ui/webui/resources/cr_elements_resources.grdp
@@ -117,6 +117,12 @@ <structure name="IDR_CR_ELEMENTS_CR_SEARCH_FIELD_JS" file="../../webui/resources/cr_elements/cr_search_field/cr_search_field.js" type="chrome_html" /> + <structure name="IDR_CR_ELEMENTS_CR_SHARED_MENU_HTML" + file="../../webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.html" + type="chrome_html" /> + <structure name="IDR_CR_ELEMENTS_CR_SHARED_MENU_JS" + file="../../webui/resources/cr_elements/cr_shared_menu/cr_shared_menu.js" + type="chrome_html" /> <structure name="IDR_CR_ELEMENTS_SHARED_CSS" file="../../webui/resources/cr_elements/shared.css" type="chrome_html" />
diff --git a/ui/webui/resources/html/web_ui_listener_behavior.html b/ui/webui/resources/html/web_ui_listener_behavior.html new file mode 100644 index 0000000..1c1906d --- /dev/null +++ b/ui/webui/resources/html/web_ui_listener_behavior.html
@@ -0,0 +1,2 @@ +<link rel="import" href="chrome://resources/html/cr.html"> +<script src="chrome://resources/js/web_ui_listener_behavior.js"></script>
diff --git a/ui/webui/resources/js/chromeos/compiled_resources.gyp b/ui/webui/resources/js/chromeos/compiled_resources2.gyp similarity index 63% rename from ui/webui/resources/js/chromeos/compiled_resources.gyp rename to ui/webui/resources/js/chromeos/compiled_resources2.gyp index 05e7e0a..a363475 100644 --- a/ui/webui/resources/js/chromeos/compiled_resources.gyp +++ b/ui/webui/resources/js/chromeos/compiled_resources2.gyp
@@ -5,13 +5,11 @@ 'targets': [ { 'target_name': 'ui_account_tweaks', - 'variables': { - 'depends': [ - '../compiled_resources.gyp:cr', - '../compiled_resources.gyp:load_time_data', - ], - }, - 'includes': ['../../../../../third_party/closure_compiler/compile_js.gypi'], + 'dependencies': [ + '../compiled_resources2.gyp:cr', + '../compiled_resources2.gyp:load_time_data', + ], + 'includes': ['../../../../../third_party/closure_compiler/compile_js2.gypi'], }, ] }
diff --git a/ui/webui/resources/js/compiled_resources.gyp b/ui/webui/resources/js/compiled_resources.gyp index 28d0d45..d679f4c 100644 --- a/ui/webui/resources/js/compiled_resources.gyp +++ b/ui/webui/resources/js/compiled_resources.gyp
@@ -20,34 +20,6 @@ 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], }, { - 'target_name': 'load_time_data', - 'variables': { - 'depends': [ - '../../../../third_party/jstemplate/util.js', - '../../../../third_party/jstemplate/jsevalcontext.js', - '../../../../third_party/jstemplate/jstemplate.js', - ], - }, - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'util', - 'variables': { - 'depends': ['compiled_resources.gyp:cr', 'assert.js'], - # TODO(jlklein): Get <(VARIABLES) in transient externs/depends working. - 'externs': ['../../../../third_party/closure_compiler/externs/chrome_send.js'], - }, - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'parse_html_subset', - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { - 'target_name': 'promise_resolver', - 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], - }, - { 'target_name': 'i18n_template_no_process', 'variables': { 'depends': ['compiled_resources.gyp:load_time_data'], @@ -63,5 +35,33 @@ }, 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], }, + { + 'target_name': 'load_time_data', + 'variables': { + 'depends': [ + '../../../../third_party/jstemplate/util.js', + '../../../../third_party/jstemplate/jsevalcontext.js', + '../../../../third_party/jstemplate/jstemplate.js', + ], + }, + 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], + }, + { + 'target_name': 'parse_html_subset', + 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], + }, + { + 'target_name': 'promise_resolver', + 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], + }, + { + 'target_name': 'util', + 'variables': { + 'depends': ['compiled_resources.gyp:cr', 'assert.js'], + # TODO(jlklein): Get <(VARIABLES) in transient externs/depends working. + 'externs': ['../../../../third_party/closure_compiler/externs/chrome_send.js'], + }, + 'includes': ['../../../../third_party/closure_compiler/compile_js.gypi'], + }, ], }
diff --git a/ui/webui/resources/js/compiled_resources2.gyp b/ui/webui/resources/js/compiled_resources2.gyp index 5f0d8118..1c1e15fa 100644 --- a/ui/webui/resources/js/compiled_resources2.gyp +++ b/ui/webui/resources/js/compiled_resources2.gyp
@@ -21,31 +21,10 @@ 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], }, { - 'target_name': 'load_time_data', - 'dependencies': ['<(DEPTH)/third_party/jstemplate/compiled_resources2.gyp:jstemplate'], - 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], - }, - { 'target_name': 'event_tracker', 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], }, { - 'target_name': 'util', - 'dependencies': [ - '<(EXTERNS_GYP):chrome_send', - 'cr', - ], - 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], - }, - { - 'target_name': 'parse_html_subset', - 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], - }, - { - 'target_name': 'promise_resolver', - 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], - }, - { 'target_name': 'i18n_template_no_process', 'dependencies': [ 'load_time_data', @@ -70,5 +49,26 @@ ], 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], }, + { + 'target_name': 'load_time_data', + 'dependencies': ['<(DEPTH)/third_party/jstemplate/compiled_resources2.gyp:jstemplate'], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'parse_html_subset', + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'promise_resolver', + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'util', + 'dependencies': [ + '<(EXTERNS_GYP):chrome_send', + 'cr', + ], + 'includes': ['../../../../third_party/closure_compiler/compile_js2.gypi'], + }, ], }
diff --git a/ui/webui/resources/js/cr.js b/ui/webui/resources/js/cr.js index c78ab9d..99478f5 100644 --- a/ui/webui/resources/js/cr.js +++ b/ui/webui/resources/js/cr.js
@@ -13,7 +13,7 @@ var WebUIListener; /** Platform, package, object property, and Event support. **/ -var cr = function() { +var cr = cr || function() { 'use strict'; /**
diff --git a/ui/webui/resources/js/cr/ui/compiled_resources2.gyp b/ui/webui/resources/js/cr/ui/compiled_resources2.gyp index a420949..1bc7c7f 100644 --- a/ui/webui/resources/js/cr/ui/compiled_resources2.gyp +++ b/ui/webui/resources/js/cr/ui/compiled_resources2.gyp
@@ -4,10 +4,18 @@ { 'targets': [ { + 'target_name': 'alert_overlay', + 'dependencies': [ + '../../compiled_resources2.gyp:cr', + '../../compiled_resources2.gyp:util', + ], + 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { 'target_name': 'command', 'dependencies': [ - '<(DEPTH)/ui/webui/resources/js/compiled_resources2.gyp:cr', - '<(DEPTH)/ui/webui/resources/js/cr/compiled_resources2.gyp:ui', + '../../compiled_resources2.gyp:cr', + '../compiled_resources2.gyp:ui', ], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], }, @@ -27,6 +35,11 @@ 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { + 'target_name': 'focus_outline_manager', + 'dependencies': ['../../compiled_resources2.gyp:cr'], + 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { 'target_name': 'focus_row', 'dependencies': [ '../../compiled_resources2.gyp:assert', @@ -37,6 +50,39 @@ 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], }, { + 'target_name': 'menu_button', + 'dependencies': [ + '../../compiled_resources2.gyp:assert', + '../../compiled_resources2.gyp:cr', + '../../compiled_resources2.gyp:event_tracker', + '../compiled_resources2.gyp:ui', + 'menu', + 'menu_item', + 'position_util', + ], + 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'menu_item', + 'dependencies': [ + '../../compiled_resources2.gyp:cr', + '../../compiled_resources2.gyp:load_time_data', + '../compiled_resources2.gyp:ui', + 'command', + ], + 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { + 'target_name': 'menu', + 'dependencies': [ + '../../compiled_resources2.gyp:assert', + '../../compiled_resources2.gyp:cr', + '../compiled_resources2.gyp:ui', + 'menu_item', + ], + 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, + { 'target_name': 'overlay', 'dependencies': [ '../../compiled_resources2.gyp:cr', @@ -44,5 +90,12 @@ ], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], }, + { + 'target_name': 'position_util', + 'dependencies': [ + '../../compiled_resources2.gyp:cr', + ], + 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'], + }, ], }
diff --git a/ui/webui/resources/js/cr/ui/menu_item.js b/ui/webui/resources/js/cr/ui/menu_item.js index 2b8b1233..11af6275 100644 --- a/ui/webui/resources/js/cr/ui/menu_item.js +++ b/ui/webui/resources/js/cr/ui/menu_item.js
@@ -197,7 +197,8 @@ if (!this.disabled && !this.isSeparator() && this.selected) { // Store |contextElement| since it'll be removed by {Menu} on handling // 'activate' event. - var contextElement = this.parentNode.contextElement; + var contextElement = /** @type {{contextElement: Element}} */( + this.parentNode).contextElement; var activationEvent = cr.doc.createEvent('Event'); activationEvent.initEvent('activate', true, true); activationEvent.originalEvent = e;
diff --git a/ui/webui/resources/js/promise_resolver.js b/ui/webui/resources/js/promise_resolver.js index e4fedaa5..0759c95 100644 --- a/ui/webui/resources/js/promise_resolver.js +++ b/ui/webui/resources/js/promise_resolver.js
@@ -16,15 +16,18 @@ * resolver.resolve({hello: 'world'}); */ -/** @constructor */ +/** + * @constructor @struct + * @template T + */ function PromiseResolver() { - /** @type {!Function} */ + /** @type {function(T): void} */ this.resolve; - /** @type {!Function} */ + /** @type {function(*=): void} */ this.reject; - /** @type {!Promise} */ + /** @type {!Promise<T>} */ this.promise = new Promise(function(resolve, reject) { this.resolve = resolve; this.reject = reject;
diff --git a/ui/webui/resources/js/util.js b/ui/webui/resources/js/util.js index a683b5f87..2707dbcd 100644 --- a/ui/webui/resources/js/util.js +++ b/ui/webui/resources/js/util.js
@@ -456,3 +456,12 @@ return original; return original.substring(0, maxLength - 1) + '\u2026'; } + +/** + * Quote a string so it can be used in a regular expression. + * @param {string} str The source string. + * @return {string} The escaped string. + */ +function quoteString(str) { + return str.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, '\\$1'); +}
diff --git a/chrome/browser/resources/settings/web_ui_listener_behavior.js b/ui/webui/resources/js/web_ui_listener_behavior.js similarity index 91% rename from chrome/browser/resources/settings/web_ui_listener_behavior.js rename to ui/webui/resources/js/web_ui_listener_behavior.js index b3c44cd..0b45d83 100644 --- a/chrome/browser/resources/settings/web_ui_listener_behavior.js +++ b/ui/webui/resources/js/web_ui_listener_behavior.js
@@ -5,9 +5,6 @@ /** * @fileoverview Behavior to be used by Polymer elements that want to * automatically remove WebUI listeners when detached. - * - * TODO(dpapad): This file can be useful for any WebUI Polymer code, not just - * for settings, consider moving elsewhere. */ cr.define('settings', function() {
diff --git a/ui/webui/resources/webui_resources.grd b/ui/webui/resources/webui_resources.grd index 87228d02..4b8930c5 100644 --- a/ui/webui/resources/webui_resources.grd +++ b/ui/webui/resources/webui_resources.grd
@@ -309,6 +309,8 @@ file="html/i18n_behavior.html" type="chrome_html" /> <structure name="IDR_WEBUI_HTML_UTIL" file="html/util.html" type="chrome_html" /> + <structure name="IDR_WEBUI_HTML_WEBUI_LISTENER_BEHAVIOR" + file="html/web_ui_listener_behavior.html" type="chrome_html" /> <structure name="IDR_WEBUI_JS_ACTION_LINK" file="js/action_link.js" type="chrome_html" /> @@ -438,6 +440,8 @@ file="js/i18n_behavior.js" type="chrome_html" /> <structure name="IDR_WEBUI_JS_UTIL" file="js/util.js" type="chrome_html" flattenhtml="true" /> + <structure name="IDR_WEBUI_JS_WEBUI_LISTENER_BEHAVIOR" + file="js/web_ui_listener_behavior.js" type="chrome_html" /> <structure name="IDR_WEBUI_JS_WEBUI_RESOURCE_TEST" file="js/webui_resource_test.js" type="chrome_html" /> <if expr="chromeos">
diff --git a/url/mojo/url_gurl_struct_traits_unittest.cc b/url/mojo/url_gurl_struct_traits_unittest.cc index be21f61..4f7e908 100644 --- a/url/mojo/url_gurl_struct_traits_unittest.cc +++ b/url/mojo/url_gurl_struct_traits_unittest.cc
@@ -6,6 +6,7 @@ #include "base/logging.h" #include "base/macros.h" +#include "base/message_loop/message_loop.h" #include "mojo/public/cpp/bindings/binding.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/mojo/url_test.mojom.h"